ops.go 443 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "math"
  11. "net/http"
  12. "os"
  13. "path"
  14. "regexp"
  15. "sort"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "tmr-watch/conf/setting"
  21. "tmr-watch/http/handle/gm"
  22. "tmr-watch/http/handle/restful"
  23. "tmr-watch/http/handle/ymy"
  24. "tmr-watch/models"
  25. "tmr-watch/module"
  26. "tmr-watch/pkg/app"
  27. "tmr-watch/pkg/e"
  28. "tmr-watch/pkg/logging"
  29. "github.com/360EntSecGroup-Skylar/excelize"
  30. "github.com/Anderson-Lu/gofasion/gofasion"
  31. "github.com/astaxie/beego/logs"
  32. "github.com/gin-gonic/gin"
  33. "github.com/qichengzx/coordtransform"
  34. "github.com/tealeg/xlsx"
  35. "github.com/xormplus/xorm"
  36. excelizexuri "github.com/xuri/excelize/v2"
  37. )
  38. // @Summary 根据SQL执行得到数据集
  39. // @Tags getData
  40. // @Accept json
  41. // @Produce json
  42. // @Param sql query string true "sql"
  43. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  44. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  45. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  46. // @Router /data/getdata [POST]
  47. func GetData(c *gin.Context) {
  48. appG := app.Gin{C: c}
  49. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  50. fsion := gofasion.NewFasion(string(dataByte))
  51. sqlstr := fsion.Get("sql").ValueStr()
  52. offset := fsion.Get("offset").ValueDefaultInt(0)
  53. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  54. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  55. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  56. if err != nil {
  57. appG.Response(http.StatusOK, e.ERROR, err.Error())
  58. } else {
  59. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  60. }
  61. }
  62. func Testpartitions(c *gin.Context) {
  63. appG := app.Gin{C: c}
  64. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  65. fsion := gofasion.NewFasion(string(dataByte))
  66. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  67. user := fsion.Get("user").ValueStr() //获取新数据库用户
  68. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  69. host := fsion.Get("host").ValueStr() //获取新数据库名称
  70. port := fsion.Get("port").ValueStr() //获取新数据库名称
  71. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  72. if sqls == nil || err1 != nil {
  73. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  74. }
  75. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  76. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  77. mydb, err := sql.Open("mysql", connecting) //连接新连接
  78. if err != nil {
  79. println("err1", err.Error())
  80. }
  81. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  82. if err != nil {
  83. println("err2", err.Error())
  84. }
  85. mydb.Close()
  86. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  87. mydb, err = sql.Open("mysql", connecting)
  88. if err != nil {
  89. println("err3", err.Error())
  90. }
  91. defer mydb.Close()
  92. if err == nil {
  93. mydb.SetMaxOpenConns(10)
  94. mydb.SetMaxIdleConns(10)
  95. }
  96. errmsg := ""
  97. if err == nil {
  98. //tx ,_ :=mydb.Begin()
  99. for _, sqlstr := range sqlstrs {
  100. //println("sqlstr---",sqlstr)
  101. if sqlstr == "" {
  102. continue
  103. }
  104. _, err = mydb.Exec(sqlstr)
  105. if err != nil {
  106. println("err4", err.Error())
  107. errmsg = err.Error()
  108. //err1 :=tx.Rollback()
  109. }
  110. }
  111. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  112. //err =tx.Commit()
  113. }
  114. if errmsg == "" {
  115. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  116. } else {
  117. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  118. }
  119. }
  120. func TestData(c *gin.Context) {
  121. appG := app.Gin{C: c}
  122. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  123. fsion := gofasion.NewFasion(string(dataByte))
  124. sqlstr := fsion.Get("sql").ValueStr()
  125. token := ""
  126. if tempv, exists := c.Get("jwt_username"); exists {
  127. token = tempv.(string)
  128. }
  129. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  130. }
  131. // @Summary 根据APISQL表中SQL执行得到数据集
  132. // @Tags GetDataByName
  133. // @Accept json
  134. // @Produce json
  135. // @Param sqlname body string true "sqlname"
  136. // @Param offset body int true "offset"
  137. // @Param pagecount body int true "pagecount"
  138. // @Param returntype body string true "returntype"
  139. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  140. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  141. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  142. // @Router /data/GetDataByName [POST]
  143. func GetDataByName(c *gin.Context) {
  144. appG := app.Gin{C: c}
  145. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  146. fsion := gofasion.NewFasion(string(dataByte))
  147. sqlnamestr := fsion.Get("name").ValueStr()
  148. offset := fsion.Get("offset").ValueDefaultInt(0)
  149. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  150. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  151. tx := restful.Engine.NewSession()
  152. err := tx.Begin()
  153. defer func() {
  154. switch {
  155. case err != nil:
  156. logging.Error("tx.Begin 事务启动失败__error:", err)
  157. if tx != nil {
  158. tx.Rollback()
  159. }
  160. default:
  161. if tx != nil {
  162. err = tx.Commit()
  163. }
  164. }
  165. if tx != nil {
  166. tx.Close()
  167. }
  168. }()
  169. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  170. if sql != "" {
  171. s_params := make([]interface{}, 0)
  172. if fsion.HasKey("parammaps") {
  173. parammaps := fsion.Get("parammaps")
  174. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  175. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  176. }
  177. paramslist := strings.Split(p, ",")
  178. if len(paramslist) > 0 && p != "" {
  179. for _, value := range paramslist {
  180. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  181. if tempv, exists := c.Get("jwt_username"); exists {
  182. s_params = append(s_params, tempv.(string))
  183. } else {
  184. s_params = append(s_params, "")
  185. }
  186. } else {
  187. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  188. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  189. // tmrNameList := []string{}
  190. // for _, tmr := range tmrArray {
  191. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  192. // }
  193. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  194. // } else {
  195. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  196. // }
  197. }
  198. }
  199. }
  200. } else if fsion.HasKey("params") {
  201. params := fsion.Get("params").Array()
  202. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  203. for _, v_params := range params {
  204. s_params = append(s_params, v_params.ValueStr())
  205. }
  206. }
  207. if returntype == "xlsx" {
  208. var xlsxfile *xlsx.File
  209. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  210. //c.File("c:/dd.xlsx")
  211. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  212. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  213. c.Header("Content-Transfer-Encoding", "binary")
  214. _ = xlsxfile.Write(c.Writer)
  215. } else {
  216. if sqlnamestr == "getHomepageStr" {
  217. parammaps := fsion.Get("parammaps")
  218. pastureid := parammaps.Get("pastureid").ValueStr()
  219. var montimeList []float64
  220. var montime float64
  221. var wg sync.WaitGroup
  222. now := time.Now()
  223. for i := 0; i < 30; i++ {
  224. wg.Add(1)
  225. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  226. go func(nowstr string) {
  227. defer wg.Done()
  228. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  229. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  230. if len(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})) > 0 {
  231. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  232. montimeList = append(montimeList, m)
  233. }
  234. }(nowstr)
  235. }
  236. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  237. if err != nil {
  238. logging.Error("GetDataByName err: ", err)
  239. msg := geterrmsg(err.Error())
  240. appG.Response(http.StatusOK, e.ERROR, msg)
  241. }
  242. wg.Wait()
  243. for _, m := range montimeList {
  244. montime += m
  245. }
  246. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  247. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  248. return
  249. }
  250. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  251. if err != nil {
  252. logging.Error("GetDataByName err: ", err)
  253. msg := geterrmsg(err.Error())
  254. appG.Response(http.StatusOK, e.ERROR, msg)
  255. } else {
  256. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  257. }
  258. }
  259. } else {
  260. appG.Response(http.StatusOK, e.SUCCESS, nil)
  261. }
  262. }
  263. // @Summary 根据APISQL表中SQL执行得到数据集
  264. // @Tags GetDataByName
  265. // @Accept json
  266. // @Produce json
  267. // @Param sqlname body string true "sqlname"
  268. // @Param offset body int true "offset"
  269. // @Param pagecount body int true "pagecount"
  270. // @Param returntype body string true "returntype"
  271. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  272. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  273. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  274. // @Router /data/GetDataByName [POST]
  275. func GetDataBySqlIN(c *gin.Context) {
  276. appG := app.Gin{C: c}
  277. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  278. fsion := gofasion.NewFasion(string(dataByte))
  279. sqlnamestr := fsion.Get("name").ValueStr()
  280. offset := fsion.Get("offset").ValueDefaultInt(0)
  281. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  282. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  283. tx := restful.Engine.NewSession()
  284. err := tx.Begin()
  285. defer func() {
  286. switch {
  287. case err != nil:
  288. logging.Error("tx.Begin 事务启动失败__error:", err)
  289. if tx != nil {
  290. tx.Rollback()
  291. }
  292. default:
  293. if tx != nil {
  294. err = tx.Commit()
  295. }
  296. }
  297. if tx != nil {
  298. tx.Close()
  299. }
  300. }()
  301. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  302. if sql != "" {
  303. s_params := make([]interface{}, 0)
  304. if fsion.HasKey("parammaps") {
  305. parammaps := fsion.Get("parammaps")
  306. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  307. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  308. }
  309. paramslist := strings.Split(p, ",")
  310. if len(paramslist) > 0 && p != "" {
  311. for _, value := range paramslist {
  312. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  313. if tempv, exists := c.Get("jwt_username"); exists {
  314. s_params = append(s_params, tempv.(string))
  315. } else {
  316. s_params = append(s_params, "")
  317. }
  318. } else {
  319. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  320. }
  321. }
  322. }
  323. } else if fsion.HasKey("params") {
  324. params := fsion.Get("params").Array()
  325. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  326. for _, v_params := range params {
  327. s_params = append(s_params, v_params.ValueStr())
  328. }
  329. }
  330. if returntype == "xlsx" {
  331. var xlsxfile *xlsx.File
  332. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  333. //c.File("c:/dd.xlsx")
  334. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  335. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  336. c.Header("Content-Transfer-Encoding", "binary")
  337. _ = xlsxfile.Write(c.Writer)
  338. } else {
  339. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  340. if err != nil {
  341. logging.Error("GetDataByName err: ", err)
  342. msg := geterrmsg(err.Error())
  343. appG.Response(http.StatusOK, e.ERROR, msg)
  344. } else {
  345. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  346. }
  347. }
  348. } else {
  349. appG.Response(http.StatusOK, e.SUCCESS, nil)
  350. }
  351. }
  352. // 错误处理
  353. // 将报错信息处理成汉字
  354. func geterrmsg(errstr string) (msgstr string) {
  355. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  356. rs := []rune(errstr)
  357. if hzRegexp.MatchString(string(rs[0])) {
  358. msgstr = errstr
  359. return
  360. }
  361. if strings.Contains(errstr, "Duplicate entry") {
  362. strs := strings.Split(errstr, ` key '`)
  363. if len(strs) > 1 {
  364. if len(strs[len(strs)-1]) > 1 {
  365. errstr = "Duplicate entry :" + strs[len(strs)-1]
  366. }
  367. }
  368. }
  369. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  370. if err != nil {
  371. msgstr = errstr
  372. return
  373. }
  374. if msg == nil || len(msg) == 0 {
  375. var param []interface{}
  376. param = append(param, errstr, errstr)
  377. go func() {
  378. tx := restful.Engine.NewSession()
  379. err := tx.Begin()
  380. defer func() {
  381. switch {
  382. case err != nil:
  383. logging.Error("tx.Begin 事务启动失败__error:", err)
  384. if tx != nil {
  385. tx.Rollback()
  386. }
  387. default:
  388. if tx != nil {
  389. err = tx.Commit()
  390. }
  391. }
  392. if tx != nil {
  393. tx.Close()
  394. }
  395. }()
  396. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  397. if err != nil {
  398. logging.Error("insert into err_msg(err,msg) err", err)
  399. }
  400. }()
  401. msgstr = errstr
  402. } else {
  403. msgstr = msg[0]["msg"]
  404. }
  405. return
  406. }
  407. // @Summary 根据APISQL表中SQL执行得到数据集
  408. // @Tags GetDataByNameForm
  409. // @Accept json
  410. // @Produce json
  411. // @Param sqlname body json true "sqlname"
  412. // @Param offset query int true "offset"
  413. // @Param pagecount query int true "pagecount"
  414. // @Param returntype query string true "returntype"
  415. // @Param s formData json true "ss"
  416. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  417. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  418. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  419. // @Router /data/GetDataByNameForm [POST]
  420. func GetDataByNameForm(c *gin.Context) {
  421. appG := app.Gin{C: c}
  422. //sqlnamestr := c.PostForm("measureNumber")
  423. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  424. //fsion := gofasion.NewFasion(string(dataByte))
  425. //sqlnamestr := fsion.Get("name").ValueStr()
  426. //offset := fsion.Get("offset").ValueInt()
  427. //pagecount := fsion.Get("pagecount").ValueInt()
  428. //returntype := fsion.Get("returntype").ValueStr()
  429. //params := fsion.Get("params").Array()
  430. c.Request.ParseForm()
  431. params := c.Request.Form
  432. offset := 0
  433. pageSize_ := 0
  434. returntype := params.Get("page")
  435. if returntype == "" {
  436. returntype = "0"
  437. }
  438. if tempv, exists := c.Get("jwt_username"); exists {
  439. params.Set("JwtUserName", tempv.(string))
  440. } else {
  441. params.Set("JwtUserName", "")
  442. }
  443. sqlnamestr := params.Get("name")
  444. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  445. s_params := make([]interface{}, 0)
  446. if returntype == "1" {
  447. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  448. if error != nil {
  449. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  450. }
  451. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  452. if error != nil {
  453. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  454. }
  455. pageSize_ = pageSize
  456. offset = pageNum
  457. }
  458. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  459. paramslist := strings.Split(p, ",")
  460. if len(paramslist) > 0 && p != "" {
  461. for _, value := range paramslist {
  462. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  463. }
  464. }
  465. if sql != "" {
  466. if returntype == "xlsx" {
  467. var xlsxfile *xlsx.File
  468. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  469. c.Header("Content-Type", "application/octet-stream")
  470. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  471. c.Header("Content-Transfer-Encoding", "binary")
  472. _ = xlsxfile.Write(c.Writer)
  473. } else {
  474. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  475. if err != nil {
  476. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  477. } else {
  478. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  479. }
  480. }
  481. } else {
  482. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  483. }
  484. }
  485. // @Summary 递归获取所有
  486. // @Tags menu
  487. // @Accept json
  488. // @Produce json
  489. // @Param Ton query string true "Ton"
  490. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  491. // @Router /authdata/GetRoleMenus [GET]
  492. func GetRecuDataByName(c *gin.Context) {
  493. appG := app.Gin{C: c}
  494. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  495. fsion := gofasion.NewFasion(string(dataByte))
  496. sqlnamestr := fsion.Get("name").ValueStr()
  497. parentidname := fsion.Get("idname").ValueStr()
  498. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  499. params := make(map[string]interface{})
  500. s_params := make([]interface{}, 0)
  501. if fsion.HasKey("params") {
  502. for _, v_params := range fsion.Get("params").Array() {
  503. s_params = append(s_params, v_params.ValueStr())
  504. }
  505. params["params"] = s_params
  506. } else {
  507. jparams := fsion.Get("parammaps")
  508. paramslist := strings.Split(p, ",")
  509. if len(paramslist) > 0 && p != "" {
  510. for _, value := range paramslist {
  511. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  512. if tempv, exists := c.Get("jwt_username"); exists {
  513. params[value] = tempv.(string)
  514. } else {
  515. params[value] = ""
  516. }
  517. } else {
  518. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  519. }
  520. }
  521. }
  522. }
  523. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  524. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  525. if err != nil {
  526. appG.Response(http.StatusOK, e.ERROR, err.Error())
  527. }
  528. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  529. }
  530. // @Summary 根据APISQL表中SQL执行得到数据集
  531. // @Tags GetDataByNames
  532. // @Accept json
  533. // @Produce json
  534. // @RequestBody sqlname query string true "sqlname"
  535. // @Param offset query int true "offset"
  536. // @Param pagecount query int true "pagecount"
  537. // @Param returntype query string true "returntype"
  538. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  539. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  540. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  541. // @Router /data/GetDataByNames [POST]
  542. func GetDataByNames(c *gin.Context) {
  543. appG := app.Gin{C: c}
  544. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  545. fsion := gofasion.NewFasion(string(dataByte))
  546. sqlParams := fsion.Array()
  547. queryData := make(map[string]interface{})
  548. for _, v := range sqlParams {
  549. fsion2 := gofasion.NewFasion(v.Json())
  550. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  551. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  552. if sql == "" {
  553. errorm := make(map[string]interface{})
  554. errorm["code"] = e.ERROR
  555. errorm["message"] = "sql没找到"
  556. queryData[fsion2.Get("name").ValueStr()] = errorm
  557. continue
  558. } else if sql != "" {
  559. offset := fsion2.Get("offset").ValueInt()
  560. pagecount := fsion2.Get("pagecount").ValueInt()
  561. returntype := fsion2.Get("returntype").ValueStr()
  562. s_params := make([]interface{}, 0)
  563. if fsion2.HasKey("parammaps") {
  564. parammaps := fsion2.Get("parammaps")
  565. paramslist := strings.Split(p, ",")
  566. if len(paramslist) > 0 && p != "" {
  567. for _, value := range paramslist {
  568. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  569. if tempv, exists := c.Get("jwt_username"); exists {
  570. s_params = append(s_params, tempv.(string))
  571. } else {
  572. s_params = append(s_params, "")
  573. }
  574. } else {
  575. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  576. }
  577. }
  578. }
  579. } else if fsion2.HasKey("params") {
  580. params := fsion2.Get("params").Array()
  581. for _, v_params := range params {
  582. s_params = append(s_params, v_params.ValueStr())
  583. }
  584. }
  585. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  586. if err != nil {
  587. errorm := make(map[string]interface{})
  588. errorm["code"] = e.ERROR
  589. errorm["message"] = err.Error()
  590. queryData[fsion2.Get("name").ValueStr()] = errorm
  591. logging.Error("GetDataByNames err: ", err)
  592. continue
  593. } else {
  594. queryData[fsion2.Get("name").ValueStr()] = queryData1
  595. }
  596. }
  597. }
  598. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  599. }
  600. // @Summary 根据APISQL表中SQL执行得到数据集
  601. // @Tags PostDataByNameForm
  602. // @Accept json
  603. // @Produce json
  604. // @Param sqlname query string true "sqlname"
  605. // @Param offset query int true "offset"
  606. // @Param pagecount query int true "pagecount"
  607. // @Param returntype query string true "returntype"
  608. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  609. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  610. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  611. // @Router /data/PostDataByNameForm [POST]
  612. func PostDataByNameForm(c *gin.Context) {
  613. appG := app.Gin{C: c}
  614. c.Request.ParseForm()
  615. params := c.Request.Form
  616. sqlnamestr := params.Get("name")
  617. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  618. s_params := make([]interface{}, 0)
  619. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  620. paramslist := strings.Split(p, ",")
  621. if len(paramslist) > 0 {
  622. for _, value := range paramslist {
  623. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  624. }
  625. }
  626. if sql != "" {
  627. queryData, err := execDataBySql(sql, s_params)
  628. if err != nil {
  629. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  630. } else {
  631. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  632. }
  633. } else {
  634. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  635. }
  636. }
  637. // GetReportform 将数据集转换格式
  638. // @Tags PostDataByNameForm
  639. // @Accept json
  640. // @Produce json
  641. // @Param sqlname query string true "sqlname"
  642. // @Param offset query int true "offset"
  643. // @Param pagecount query int true "pagecount"
  644. // @Param returntype query string true "returntype"
  645. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  646. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  647. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  648. func GetReportform(c *gin.Context) {
  649. appG := app.Gin{C: c}
  650. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  651. fsion := gofasion.NewFasion(string(dataByte))
  652. sqlnamestr := fsion.Get("name").ValueStr()
  653. checked := fsion.Get("checked").ValueStr()
  654. offset := fsion.Get("offset").ValueDefaultInt(0)
  655. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  656. parammaps := fsion.Get("parammaps")
  657. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  658. mode := parammaps.Get("mode").ValueDefaultInt(0)
  659. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  660. tx := restful.Engine.NewSession()
  661. err := tx.Begin()
  662. defer func() {
  663. switch {
  664. case err != nil:
  665. if tx != nil {
  666. tx.Rollback()
  667. }
  668. default:
  669. if tx != nil {
  670. err = tx.Commit()
  671. }
  672. }
  673. if tx != nil {
  674. tx.Close()
  675. }
  676. }()
  677. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  678. if err != nil {
  679. appG.Response(http.StatusOK, e.ERROR, err.Error())
  680. } else {
  681. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  682. }
  683. }
  684. // GetUpkeepPlan 保养计划
  685. func GetUpkeepPlan(c *gin.Context) {
  686. appG := app.Gin{C: c}
  687. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  688. fsion := gofasion.NewFasion(string(dataByte))
  689. sqlnamestr := fsion.Get("name").ValueStr()
  690. offset := fsion.Get("offset").ValueDefaultInt(0)
  691. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  692. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  693. month := fsion.Get("month").ValueDefaultStr("map")
  694. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  695. tx := restful.Engine.NewSession()
  696. err := tx.Begin()
  697. defer func() {
  698. switch {
  699. case err != nil:
  700. if tx != nil {
  701. tx.Rollback()
  702. }
  703. default:
  704. if tx != nil {
  705. err = tx.Commit()
  706. }
  707. }
  708. if tx != nil {
  709. tx.Close()
  710. }
  711. }()
  712. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  713. if sql != "" {
  714. s_params := make([]interface{}, 0)
  715. if fsion.HasKey("parammaps") {
  716. parammaps := fsion.Get("parammaps")
  717. paramslist := strings.Split(p, ",")
  718. if len(paramslist) > 0 && p != "" {
  719. for _, value := range paramslist {
  720. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  721. if tempv, exists := c.Get("jwt_username"); exists {
  722. s_params = append(s_params, tempv.(string))
  723. } else {
  724. s_params = append(s_params, "")
  725. }
  726. } else {
  727. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  728. }
  729. }
  730. }
  731. } else if fsion.HasKey("params") {
  732. params := fsion.Get("params").Array()
  733. for _, v_params := range params {
  734. s_params = append(s_params, v_params.ValueStr())
  735. }
  736. }
  737. if returntype == "xlsx" {
  738. var xlsxfile *xlsx.File
  739. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  740. //c.File("c:/dd.xlsx")
  741. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  742. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  743. c.Header("Content-Transfer-Encoding", "binary")
  744. _ = xlsxfile.Write(c.Writer)
  745. } else {
  746. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  747. if err != nil {
  748. appG.Response(http.StatusOK, e.ERROR, err.Error())
  749. } else {
  750. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  751. if v, ok := value["id"]; ok {
  752. //month = "2020-03"
  753. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  754. if seviceplans != nil {
  755. for _, va := range seviceplans { //根据保养计划获取保养单
  756. //day,_ :=strconv.Atoi(va["day"])
  757. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  758. //buk := make(map[string]map[string]string)
  759. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  760. jstr := ""
  761. if bu["plantime"][8:9] == "0" {
  762. jstr = "m" + bu["plantime"][9:]
  763. } else {
  764. jstr = "m" + bu["plantime"][8:]
  765. }
  766. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  767. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  768. } else {
  769. if bu["flowCompeleted"] >= "2" {
  770. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  771. } else {
  772. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  773. }
  774. }
  775. }
  776. }
  777. }
  778. }
  779. }
  780. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  781. }
  782. }
  783. } else {
  784. appG.Response(http.StatusOK, e.SUCCESS, nil)
  785. }
  786. }
  787. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  788. // todo 优化性能 children统一查询
  789. // @Tags PostDataByNameForm
  790. // @Accept json
  791. // @Produce json
  792. // @Param sqlname query string true "sqlname"
  793. // @Param offset query int true "offset"
  794. // @Param pagecount query int true "pagecount"
  795. // @Param returntype query string true "returntype"
  796. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  797. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  798. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  799. func GetArrList(c *gin.Context) {
  800. appG := app.Gin{C: c}
  801. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  802. fsion := gofasion.NewFasion(string(dataByte))
  803. sqlnamestr := fsion.Get("name").ValueStr()
  804. sqlnamestr1 := fsion.Get("name1").ValueStr()
  805. offset := fsion.Get("offset").ValueDefaultInt(0)
  806. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  807. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  808. month := fsion.Get("month").ValueDefaultStr("map")
  809. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  810. tx := restful.Engine.NewSession()
  811. err := tx.Begin()
  812. defer func() {
  813. switch {
  814. case err != nil:
  815. if tx != nil {
  816. tx.Rollback()
  817. }
  818. default:
  819. if tx != nil {
  820. err = tx.Commit()
  821. }
  822. }
  823. if tx != nil {
  824. tx.Close()
  825. }
  826. }()
  827. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  828. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  829. if sql != "" {
  830. s_params := make([]interface{}, 0)
  831. if fsion.HasKey("parammaps") {
  832. parammaps := fsion.Get("parammaps")
  833. paramslist := strings.Split(p, ",")
  834. if len(paramslist) > 0 && p != "" {
  835. for _, value := range paramslist {
  836. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  837. if tempv, exists := c.Get("jwt_username"); exists {
  838. s_params = append(s_params, tempv.(string))
  839. } else {
  840. s_params = append(s_params, "")
  841. }
  842. } else {
  843. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  844. }
  845. }
  846. }
  847. }
  848. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  849. if err != nil {
  850. appG.Response(http.StatusOK, e.ERROR, err.Error())
  851. } else {
  852. paramslist1 := strings.Split(p1, ",")
  853. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  854. s_params1 := make([]interface{}, 0)
  855. if len(paramslist1) > 0 && p1 != "" {
  856. for _, v := range paramslist1 {
  857. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  858. }
  859. }
  860. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  861. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  862. }
  863. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  864. }
  865. } else {
  866. appG.Response(http.StatusOK, e.SUCCESS, nil)
  867. }
  868. }
  869. func GetAccount(c *gin.Context) {
  870. appG := app.Gin{C: c}
  871. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  872. fsion := gofasion.NewFasion(string(dataByte))
  873. sqlnamestr := fsion.Get("name").ValueStr()
  874. offset := fsion.Get("offset").ValueDefaultInt(0)
  875. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  876. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  877. tx := restful.Engine.NewSession()
  878. err := tx.Begin()
  879. defer func() {
  880. switch {
  881. case err != nil:
  882. logging.Error("tx.Begin 事务启动失败__error:", err)
  883. if tx != nil {
  884. tx.Rollback()
  885. }
  886. default:
  887. if tx != nil {
  888. err = tx.Commit()
  889. }
  890. }
  891. if tx != nil {
  892. tx.Close()
  893. }
  894. }()
  895. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  896. if sql != "" {
  897. s_params := make([]interface{}, 0)
  898. if fsion.HasKey("parammaps") {
  899. parammaps := fsion.Get("parammaps")
  900. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  901. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  902. }
  903. paramslist := strings.Split(p, ",")
  904. if len(paramslist) > 0 && p != "" {
  905. for _, value := range paramslist {
  906. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  907. if tempv, exists := c.Get("jwt_username"); exists {
  908. s_params = append(s_params, tempv.(string))
  909. } else {
  910. s_params = append(s_params, "")
  911. }
  912. } else {
  913. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  914. }
  915. }
  916. }
  917. } else if fsion.HasKey("params") {
  918. params := fsion.Get("params").Array()
  919. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  920. for _, v_params := range params {
  921. s_params = append(s_params, v_params.ValueStr())
  922. }
  923. }
  924. if returntype == "xlsx" {
  925. var xlsxfile *xlsx.File
  926. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  927. //c.File("c:/dd.xlsx")
  928. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  929. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  930. c.Header("Content-Transfer-Encoding", "binary")
  931. _ = xlsxfile.Write(c.Writer)
  932. } else {
  933. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  934. if err != nil {
  935. logging.Error("GetDataByName err: ", err)
  936. msg := geterrmsg(err.Error())
  937. appG.Response(http.StatusOK, e.ERROR, msg)
  938. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  939. } else {
  940. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  941. }
  942. }
  943. } else {
  944. appG.Response(http.StatusOK, e.SUCCESS, nil)
  945. }
  946. }
  947. // PostDataByName 根据APISQL表中SQL执行得到数据集
  948. // @Accept json
  949. // @Produce json
  950. // @Param sqlname query string true "sqlname"
  951. // @Param offset query int true "offset"
  952. // @Param pagecount query int true "pagecount"
  953. // @Param returntype query string true "returntype"
  954. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  955. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  956. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  957. // @Router /data/PostDataByName [POST]
  958. func PostDataByName(c *gin.Context) {
  959. appG := app.Gin{C: c}
  960. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  961. fsion := gofasion.NewFasion(string(dataByte))
  962. var err error
  963. queryData, err := module.PostDataByName(c, fsion)
  964. if err != nil {
  965. appG.Response(http.StatusOK, e.ERROR, err.Error())
  966. return
  967. }
  968. var (
  969. keyWord string
  970. )
  971. switch fsion.Get("name").ValueStr() {
  972. case "insertFeedclass":
  973. keyWord = "feed"
  974. err = module.GroupCategorySync(keyWord, fsion)
  975. case "deleteFeedclass":
  976. keyWord = "feed_delete"
  977. err = module.GroupCategoryDelete(keyWord, fsion)
  978. case "insertCowclass":
  979. keyWord = "cow"
  980. err = module.GroupCategorySync(keyWord, fsion)
  981. case "deleteCowclass":
  982. keyWord = "cow_delete"
  983. err = module.GroupCategoryDelete(keyWord, fsion)
  984. // case "updateFT":
  985. // FtdetailSurplus(fsion)
  986. // case "updateFeed":
  987. // FeedSurplus(fsion)
  988. default:
  989. }
  990. if err != nil {
  991. logging.Error(keyWord, err)
  992. }
  993. if queryData != nil {
  994. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  995. return
  996. }
  997. appG.Response(http.StatusOK, e.SUCCESS, nil)
  998. }
  999. //人脸识别/格润富德接口
  1000. func GetRJSBData(c *gin.Context) {
  1001. appG := app.Gin{C: c}
  1002. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1003. fsion := gofasion.NewFasion(string(dataByte))
  1004. sqlnamestr := fsion.Get("name").ValueStr()
  1005. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1006. offset := fsion.Get("offset").ValueDefaultInt(0)
  1007. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1008. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1009. month := fsion.Get("month").ValueDefaultStr("map")
  1010. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1011. // pagecount = 1
  1012. tx := restful.Engine.NewSession()
  1013. err := tx.Begin()
  1014. defer func() {
  1015. switch {
  1016. case err != nil:
  1017. if tx != nil {
  1018. tx.Rollback()
  1019. }
  1020. default:
  1021. if tx != nil {
  1022. err = tx.Commit()
  1023. }
  1024. }
  1025. if tx != nil {
  1026. tx.Close()
  1027. }
  1028. }()
  1029. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1030. _, 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 )
  1031. where id = (select tmrid from downloadedplan d where d.pid = (select pid from downloadedplan where lpplantype = 5 and mydate =
  1032. date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted= 0 ) and mydate = date_format(now() ,'%Y-%m-%d')
  1033. and lpplantype in(0,1)) `).Execute()
  1034. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1035. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1036. if sql != "" {
  1037. s_params := make([]interface{}, 0)
  1038. if fsion.HasKey("parammaps") {
  1039. parammaps := fsion.Get("parammaps")
  1040. paramslist := strings.Split(p, ",")
  1041. if len(paramslist) > 0 && p != "" {
  1042. for _, value := range paramslist {
  1043. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1044. if tempv, exists := c.Get("jwt_username"); exists {
  1045. s_params = append(s_params, tempv.(string))
  1046. } else {
  1047. s_params = append(s_params, "")
  1048. }
  1049. } else {
  1050. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1051. }
  1052. }
  1053. }
  1054. }
  1055. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1056. if err != nil {
  1057. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1058. } else {
  1059. paramslist1 := strings.Split(p1, ",")
  1060. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1061. s_params1 := make([]interface{}, 0)
  1062. if len(paramslist1) > 0 && p1 != "" {
  1063. for _, v := range paramslist1 {
  1064. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1065. }
  1066. }
  1067. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1068. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1069. }
  1070. var wg sync.WaitGroup
  1071. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1072. wg.Add(1)
  1073. go func(value map[string]interface{}) {
  1074. defer wg.Done()
  1075. // ,havebutton = 1
  1076. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1077. }(value)
  1078. }
  1079. wg.Wait()
  1080. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1081. }
  1082. fmt.Println("先锋获取数据:", time.Now(), queryData)
  1083. } else {
  1084. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1085. }
  1086. }
  1087. func PostRJSBData(c *gin.Context) {
  1088. appG := app.Gin{C: c}
  1089. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1090. fsion := gofasion.NewFasion(string(dataByte))
  1091. logging.Info("PostRJSBData err: ", string(dataByte))
  1092. s_params := make([]interface{}, 0)
  1093. tx := restful.Engine.NewSession()
  1094. err := tx.Begin()
  1095. defer func() {
  1096. switch {
  1097. case err != nil:
  1098. if tx != nil {
  1099. tx.Rollback()
  1100. }
  1101. default:
  1102. if tx != nil {
  1103. err = tx.Commit()
  1104. }
  1105. }
  1106. if tx != nil {
  1107. tx.Close()
  1108. }
  1109. }()
  1110. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1111. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1112. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1113. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1114. if !fsion.HasKey("parammaps") {
  1115. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1116. return
  1117. }
  1118. parammaps := fsion.Get("parammaps")
  1119. paramslist := strings.Split(p, ",")
  1120. if len(paramslist) > 0 && p != "" {
  1121. for _, value := range paramslist {
  1122. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1123. }
  1124. }
  1125. projuctid := parammaps.Get("projuctid").ValueStr()
  1126. _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
  1127. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1128. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1129. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1130. and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1131. if err != nil {
  1132. logging.Error("PostRJSBData-0 err: ", err)
  1133. msg := geterrmsg(err.Error())
  1134. // appG.Response(http.StatusOK, e.ERROR, msg)
  1135. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1136. return
  1137. }
  1138. _, err = tx.SQL(sql, s_params...).Execute()
  1139. if err != nil {
  1140. logging.Error("PostRJSBData err: ", err)
  1141. msg := geterrmsg(err.Error())
  1142. // appG.Response(http.StatusOK, e.ERROR, msg)
  1143. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1144. return
  1145. }
  1146. s_params = make([]interface{}, 0)
  1147. paramslist = strings.Split(p1, ",")
  1148. if len(paramslist) > 0 && p1 != "" {
  1149. for _, value := range paramslist {
  1150. // if value == "ID" {
  1151. // id := parammaps.Get("ID").ValueStr()
  1152. // pastureid := parammaps.Get("pastureid").ValueStr()
  1153. // 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
  1154. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1155. // if err != nil {
  1156. // logging.Error("PostRJSBData err: ", err)
  1157. // msg := geterrmsg(err.Error())
  1158. // appG.Response(http.StatusOK, e.ERROR, msg)
  1159. // return
  1160. // }
  1161. // for _, item := range datalist {
  1162. // id = item["id"]
  1163. // }
  1164. // s_params = append(s_params, id)
  1165. // } else {
  1166. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1167. // }
  1168. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1169. }
  1170. }
  1171. _, err = tx.SQL(sql1, s_params...).Execute()
  1172. if err != nil {
  1173. logging.Error("PostRJSBData1 err: ", err)
  1174. msg := geterrmsg(err.Error())
  1175. appG.Response(http.StatusOK, e.ERROR, msg)
  1176. return
  1177. }
  1178. s_params = make([]interface{}, 0)
  1179. paramslist = strings.Split(p2, ",")
  1180. if len(paramslist) > 0 && p2 != "" {
  1181. for _, value := range paramslist {
  1182. if value == "ID" {
  1183. id := parammaps.Get("ID").ValueStr()
  1184. pastureid := parammaps.Get("pastureid").ValueStr()
  1185. 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
  1186. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1187. if err != nil {
  1188. logging.Error("PostRJSBData err: ", err)
  1189. msg := geterrmsg(err.Error())
  1190. appG.Response(http.StatusOK, e.ERROR, msg)
  1191. return
  1192. }
  1193. for _, item := range datalist {
  1194. id = item["id"]
  1195. }
  1196. s_params = append(s_params, id)
  1197. } else {
  1198. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1199. }
  1200. }
  1201. }
  1202. _, err = tx.SQL(sql2, s_params...).Execute()
  1203. if err != nil {
  1204. logging.Error("PostRJSBData2 err: ", err)
  1205. msg := geterrmsg(err.Error())
  1206. appG.Response(http.StatusOK, e.ERROR, msg)
  1207. return
  1208. }
  1209. s_params = make([]interface{}, 0)
  1210. paramslist = strings.Split(p3, ",")
  1211. if len(paramslist) > 0 && p3 != "" {
  1212. for _, value := range paramslist {
  1213. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1214. }
  1215. }
  1216. _, err = tx.SQL(sql3, s_params...).Execute()
  1217. if err != nil {
  1218. logging.Error("PostRJSBData3 err: ", err)
  1219. msg := geterrmsg(err.Error())
  1220. appG.Response(http.StatusOK, e.ERROR, msg)
  1221. return
  1222. }
  1223. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1224. }
  1225. func PostRJSBDatas(c *gin.Context) {
  1226. appG := app.Gin{C: c}
  1227. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1228. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1229. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1230. fmt.Println("先锋回传数据:", time.Now(), string(dataByte))
  1231. tx := restful.Engine.NewSession()
  1232. err := tx.Begin()
  1233. defer func() {
  1234. switch {
  1235. case err != nil:
  1236. if tx != nil {
  1237. tx.Rollback()
  1238. }
  1239. default:
  1240. if tx != nil {
  1241. err = tx.Commit()
  1242. }
  1243. }
  1244. if tx != nil {
  1245. tx.Close()
  1246. }
  1247. }()
  1248. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1249. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1250. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1251. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1252. for _, fsion := range fsions {
  1253. if !fsion.HasKey("parammaps") {
  1254. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1255. return
  1256. }
  1257. parammaps := fsion.Get("parammaps")
  1258. ID := parammaps.Get("ID").ValueStr()
  1259. if ID == "" {
  1260. continue
  1261. }
  1262. s_params := make([]interface{}, 0)
  1263. paramslist := strings.Split(p, ",")
  1264. if len(paramslist) > 0 && p != "" {
  1265. for _, value := range paramslist {
  1266. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1267. }
  1268. }
  1269. _, err := tx.SQL(sql, s_params...).Execute()
  1270. if err != nil {
  1271. logging.Error("PostRJSBData err: ", err)
  1272. msg := geterrmsg(err.Error())
  1273. // appG.Response(http.StatusOK, e.ERROR, msg)
  1274. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1275. return
  1276. }
  1277. s_params = make([]interface{}, 0)
  1278. paramslist = strings.Split(p1, ",")
  1279. if len(paramslist) > 0 && p1 != "" {
  1280. for _, value := range paramslist {
  1281. // if value == "ID" {
  1282. // id := parammaps.Get("ID").ValueStr()
  1283. // pastureid := parammaps.Get("pastureid").ValueStr()
  1284. // 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
  1285. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1286. // if err != nil {
  1287. // logging.Error("PostRJSBData err: ", err)
  1288. // msg := geterrmsg(err.Error())
  1289. // appG.Response(http.StatusOK, e.ERROR, msg)
  1290. // return
  1291. // }
  1292. // for _, item := range datalist {
  1293. // id = item["id"]
  1294. // }
  1295. // s_params = append(s_params, id)
  1296. // } else {
  1297. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1298. // }
  1299. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1300. }
  1301. }
  1302. _, err = tx.SQL(sql1, s_params...).Execute()
  1303. if err != nil {
  1304. logging.Error("PostRJSBData1 err: ", err)
  1305. msg := geterrmsg(err.Error())
  1306. appG.Response(http.StatusOK, e.ERROR, msg)
  1307. return
  1308. }
  1309. s_params = make([]interface{}, 0)
  1310. paramslist = strings.Split(p2, ",")
  1311. if len(paramslist) > 0 && p2 != "" {
  1312. for _, value := range paramslist {
  1313. if value == "ID" {
  1314. id := parammaps.Get("ID").ValueStr()
  1315. pastureid := parammaps.Get("pastureid").ValueStr()
  1316. 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
  1317. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1318. if err != nil {
  1319. logging.Error("PostRJSBData err: ", err)
  1320. msg := geterrmsg(err.Error())
  1321. appG.Response(http.StatusOK, e.ERROR, msg)
  1322. return
  1323. }
  1324. for _, item := range datalist {
  1325. id = item["id"]
  1326. }
  1327. s_params = append(s_params, id)
  1328. } else {
  1329. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1330. }
  1331. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1332. }
  1333. }
  1334. _, err = tx.SQL(sql2, s_params...).Execute()
  1335. if err != nil {
  1336. logging.Error("PostRJSBData2 err: ", err)
  1337. msg := geterrmsg(err.Error())
  1338. appG.Response(http.StatusOK, e.ERROR, msg)
  1339. return
  1340. }
  1341. s_params = make([]interface{}, 0)
  1342. paramslist = strings.Split(p3, ",")
  1343. if len(paramslist) > 0 && p3 != "" {
  1344. for _, value := range paramslist {
  1345. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1346. }
  1347. }
  1348. _, err = tx.SQL(sql3, s_params...).Execute()
  1349. if err != nil {
  1350. logging.Error("PostRJSBData3 err: ", err)
  1351. msg := geterrmsg(err.Error())
  1352. appG.Response(http.StatusOK, e.ERROR, msg)
  1353. return
  1354. }
  1355. // ALTER TABLE `tmr`
  1356. // ADD COLUMN `concentrate` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 未回传 1 已回传' AFTER `appoint`
  1357. projuctid := parammaps.Get("projuctid").ValueStr()
  1358. _, err = tx.SQL(`update tmr set xianfeng = 0, concentrate = (select d.id from downloadedplan d
  1359. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1360. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1361. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1362. and lpplantype in(0,1)) and ( select count(1) from downloadedplan where id = ? and iscompleted = 0 ) = 0 `,
  1363. projuctid, projuctid, projuctid, projuctid, projuctid).Execute()
  1364. if err != nil {
  1365. logging.Error("PostRJSBData-0 err: ", err)
  1366. msg := geterrmsg(err.Error())
  1367. // appG.Response(http.StatusOK, e.ERROR, msg)
  1368. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1369. return
  1370. }
  1371. count, _ := tx.SQL(`select count(1) from downloadedplan where id = ? and iscompleted = 0`, projuctid).Count()
  1372. if count == 0 {
  1373. fmt.Println(projuctid, "先锋回传计划已完成", count, err)
  1374. }
  1375. }
  1376. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1377. }
  1378. // @Summary 根据APISQL表中SQL执行得到数据集
  1379. // @Tags ExecDataByConfig
  1380. // @Accept json
  1381. // @Produce json
  1382. // @Param sqlname query string true "sqlname"
  1383. // @Param offset query int true "offset"
  1384. // @Param pagecount query int true "pagecount"
  1385. // @Param returntype query string true "returntype"
  1386. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1387. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1388. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1389. // @Router /data/PostDataByName [POST]
  1390. func ExecDataByConfig(c *gin.Context) {
  1391. appG := app.Gin{C: c}
  1392. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1393. tempval_ := make(map[string]interface{})
  1394. tempCommon := make(map[string]interface{})
  1395. tempval := make([]map[string]interface{}, 0)
  1396. err := json.Unmarshal(dataByte, &tempval_)
  1397. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1398. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1399. if err != nil {
  1400. } else {
  1401. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1402. tempCommon = v
  1403. }
  1404. if v, ok := tempval_["data"].([]interface{}); ok {
  1405. for _, Tvalue := range v {
  1406. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1407. tempval = append(tempval, v1)
  1408. }
  1409. }
  1410. }
  1411. tx := restful.Engine.NewSession()
  1412. err := tx.Begin()
  1413. if err != nil {
  1414. logging.Error("tx.Begin 事务启动失败__error:", err)
  1415. }
  1416. defer func() {
  1417. switch {
  1418. case err != nil:
  1419. if tx != nil {
  1420. tx.Rollback()
  1421. }
  1422. default:
  1423. if tx != nil {
  1424. err = tx.Commit()
  1425. }
  1426. }
  1427. if tx != nil {
  1428. tx.Close()
  1429. }
  1430. }()
  1431. if err == nil {
  1432. if tempv, exists := c.Get("jwt_username"); exists {
  1433. tempCommon["jwt_username"] = tempv.(string)
  1434. }
  1435. for _, paramvalue := range tempval {
  1436. fmt.Println(paramvalue["name"])
  1437. if paramvalue["name"].(string) == "updateBigFP" {
  1438. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1439. if err != nil {
  1440. msg := geterrmsg(err.Error())
  1441. appG.Response(http.StatusOK, e.ERROR, msg)
  1442. return
  1443. }
  1444. }
  1445. }
  1446. for _, paramvalue := range tempval {
  1447. if _, ok := paramvalue["resultname"]; !ok {
  1448. paramvalue["resultname"] = paramvalue["name"]
  1449. }
  1450. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1451. if err != nil {
  1452. logging.Error("ExecDataParam error:", err)
  1453. break
  1454. }
  1455. // if paramvalue["name"].(string) == "createdownloadedplan" {
  1456. // checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1457. // }
  1458. }
  1459. if err == nil {
  1460. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1461. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1462. } else {
  1463. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1464. }
  1465. } else {
  1466. msg := geterrmsg(err.Error())
  1467. appG.Response(http.StatusOK, e.ERROR, msg)
  1468. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1469. }
  1470. }
  1471. }
  1472. if err != nil {
  1473. msg := geterrmsg(err.Error())
  1474. appG.Response(http.StatusOK, e.ERROR, msg)
  1475. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1476. }
  1477. }
  1478. func interfacetostring(val interface{}) string {
  1479. switch val.(type) {
  1480. case string:
  1481. ss := val.(string)
  1482. return ss
  1483. break
  1484. case int:
  1485. ss := val.(int)
  1486. return strconv.Itoa(ss)
  1487. break
  1488. case int64:
  1489. ss := val.(int64)
  1490. return strconv.FormatInt(ss, 10)
  1491. break
  1492. case float64:
  1493. ss := val.(float64)
  1494. return strconv.FormatFloat(ss, 'E', -1, 32)
  1495. break
  1496. }
  1497. return ""
  1498. }
  1499. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1500. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1501. tempstrb := strings.IndexAny(valuestring, "@")
  1502. tempstre := strings.IndexAny(valuestring, ".")
  1503. if tempstrb > -1 && tempstre > -1 {
  1504. for _, ParamMapList := range ParamMap {
  1505. if v, ok := ParamMapList["resultname"]; ok {
  1506. if v == valuestring[tempstrb+1:tempstre] {
  1507. if v1, ok := ParamMapList["resultmaps"]; ok {
  1508. if newA, ok := v1.([]map[string]interface{}); ok {
  1509. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1510. } else if newA, ok := v1.(map[string]interface{}); ok {
  1511. return interfacetostring(newA[valuestring[tempstre+1:]])
  1512. }
  1513. }
  1514. }
  1515. }
  1516. }
  1517. } else {
  1518. return valuestring
  1519. }
  1520. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1521. return fmt.Sprintf("%f", valuestring)
  1522. }
  1523. return ""
  1524. }
  1525. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1526. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1527. tempstrb := strings.IndexAny(valuestring, "@")
  1528. tempstre := strings.IndexAny(valuestring, ".")
  1529. if tempstrb > -1 && tempstre > -1 {
  1530. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1531. if s, ok := v.(string); ok {
  1532. return s
  1533. } else if s, ok := v.(float64); ok {
  1534. return strconv.FormatFloat(s, 'f', -1, 64)
  1535. // return strconv.FormatInt(int64(s), 10)
  1536. }
  1537. }
  1538. }
  1539. }
  1540. return ""
  1541. }
  1542. 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) {
  1543. sqlname := fasion["name"].(string)
  1544. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1545. if v, ok := fasion["type"]; ok {
  1546. sqltype = v.(string)
  1547. }
  1548. sql := ""
  1549. p := ""
  1550. s_params := make([]interface{}, 0)
  1551. if sqltype != "" {
  1552. sql, p = restful.GetSqlByName(sqlname, tx)
  1553. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1554. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1555. paramslist := strings.Split(p, ",")
  1556. if len(paramslist) > 0 && p != "" {
  1557. for _, value := range paramslist {
  1558. ss := ""
  1559. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1560. ids, err := setting.SnowIds.NextId()
  1561. if err != nil {
  1562. ids = time.Now().UnixNano()
  1563. logging.Info("create SnowIds err", err)
  1564. }
  1565. s_params = append(s_params, ids)
  1566. } else {
  1567. if ss == "" && CommonParamMap != nil {
  1568. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1569. ss = valuestring
  1570. tempstrb := strings.IndexAny(valuestring, "@")
  1571. tempstre := strings.IndexAny(valuestring, ".")
  1572. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1573. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1574. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1575. }
  1576. } else {
  1577. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1578. ss = ""
  1579. }
  1580. }
  1581. }
  1582. }
  1583. if ss == "" && ParentParamMap != nil {
  1584. ss = getParamValue_(v, value, ParentParamMap)
  1585. }
  1586. if ss == "" && sameParamMap != nil {
  1587. ss = getParamValue(v, value, sameParamMap)
  1588. }
  1589. if ss == "" && ParamMap != nil {
  1590. ss = getParamValue(v, value, ParamMap)
  1591. }
  1592. s_params = append(s_params, ss)
  1593. }
  1594. }
  1595. }
  1596. }
  1597. }
  1598. if sql == "" {
  1599. sqltype = ""
  1600. }
  1601. if sqltype == "s1" {
  1602. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1603. if v, ok := tempValParam.(map[string]interface{}); ok {
  1604. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1605. }
  1606. if err != nil {
  1607. return nil, err
  1608. }
  1609. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1610. if err != nil {
  1611. return nil, err
  1612. }
  1613. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1614. } else if sqltype == "sm" {
  1615. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1616. if v, ok := tempValParam.(map[string]interface{}); ok {
  1617. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1618. } else {
  1619. }
  1620. if err != nil {
  1621. return nil, err
  1622. }
  1623. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1624. if err != nil {
  1625. return nil, err
  1626. }
  1627. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1628. } else if sqltype == "v" {
  1629. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1630. if v, ok := tempValParam.(map[string]interface{}); ok {
  1631. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1632. } else {
  1633. }
  1634. if err != nil {
  1635. return nil, err
  1636. }
  1637. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1638. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1639. }
  1640. } else if sqltype == "e" {
  1641. tempVal_arrary := make([]map[string]interface{}, 0)
  1642. tempVal_map := make(map[string]interface{})
  1643. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1644. if err == nil {
  1645. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1646. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1647. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1648. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1649. return tempVal_arrary, err
  1650. }
  1651. return nil, err
  1652. } else {
  1653. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1654. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1655. if err != nil {
  1656. return nil, err
  1657. }
  1658. return nil, err
  1659. }
  1660. }
  1661. return nil, nil
  1662. }
  1663. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1664. var err error
  1665. subarray, ok := fasion["children"]
  1666. if ok {
  1667. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1668. tempVal_arrary := make([]map[string]interface{}, 0)
  1669. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1670. tempVal_ := make(map[string]interface{})
  1671. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1672. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1673. } else {
  1674. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1675. }
  1676. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1677. if err != nil {
  1678. return err
  1679. }
  1680. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1681. }
  1682. v.(map[string]interface{})["children"] = tempVal_arrary
  1683. }
  1684. }
  1685. return nil
  1686. }
  1687. // @Summary 删除图片
  1688. // @Tags RemovePicByName
  1689. // @Accept json
  1690. // @Produce json
  1691. // @Param sqlname query string true "sqlname"
  1692. // @Param offset query int true "offset"
  1693. // @Param pagecount query int true "pagecount"
  1694. // @Param returntype query string true "returntype"
  1695. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1696. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1697. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1698. // @Router /data/PostDataByName [POST]
  1699. func RemovePicByName(c *gin.Context) {
  1700. logging.Info("RemovePicByName ", c.Keys)
  1701. appG := app.Gin{C: c}
  1702. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1703. fsion := gofasion.NewFasion(string(dataByte))
  1704. sqlnamestr := fsion.Get("name").ValueStr()
  1705. picname := fsion.Get("picname").ValueStr()
  1706. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1707. params := fsion.Get("params").Array()
  1708. s_params := make([]interface{}, 0)
  1709. for _, v_params := range params {
  1710. s_params = append(s_params, v_params.ValueStr())
  1711. }
  1712. if sql != "" {
  1713. queryData, err := execDataBySql(sql, s_params)
  1714. if picname != "" {
  1715. // Destination
  1716. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1717. err := os.Remove(distPath) //删除文件test.txt
  1718. if err != nil {
  1719. //如果删除失败则输出 file remove Error!
  1720. fmt.Println("file remove Error!")
  1721. //输出错误详细信息
  1722. fmt.Printf("%s", err)
  1723. } else {
  1724. //如果删除成功则输出 file remove OK!
  1725. fmt.Print("file remove OK!")
  1726. }
  1727. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1728. err = os.Remove(distPath) //删除文件test.txt
  1729. if err != nil {
  1730. //如果删除失败则输出 file remove Error!
  1731. fmt.Println("file remove Error!")
  1732. //输出错误详细信息
  1733. fmt.Printf("%s", err)
  1734. } else {
  1735. //如果删除成功则输出 file remove OK!
  1736. fmt.Print("file remove OK!")
  1737. }
  1738. }
  1739. if err != nil {
  1740. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1741. } else {
  1742. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1743. }
  1744. } else {
  1745. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1746. }
  1747. }
  1748. // @Summary 删除文件
  1749. // @Tags RemoveFileByName
  1750. // @Accept json
  1751. // @Produce json
  1752. // @Param sqlname query string true "sqlname"
  1753. // @Param offset query int true "offset"
  1754. // @Param pagecount query int true "pagecount"
  1755. // @Param returntype query string true "returntype"
  1756. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1757. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1758. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1759. // @Router /data/PostDataByName [POST]
  1760. func RemoveFileByName(c *gin.Context) {
  1761. appG := app.Gin{C: c}
  1762. id := c.Param("id")
  1763. logging.Info("DownloadFile ", c.Keys, id)
  1764. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1765. if eqdoc == nil {
  1766. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1767. return
  1768. }
  1769. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1770. err = os.Remove(distPath) //删除文件test.txt
  1771. if err != nil {
  1772. //如果删除失败则输出 file remove Error!
  1773. fmt.Println("file remove Error!")
  1774. //输出错误详细信息
  1775. fmt.Printf("%s", err)
  1776. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1777. return
  1778. }
  1779. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1780. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1781. }
  1782. // @Summary 根据APISQL表中SQL执行得到数据集
  1783. // @Tags PostDataByName
  1784. // @Accept json
  1785. // @Produce json
  1786. // @Param sqlname query string true "sqlname"
  1787. // @Param offset query int true "offset"
  1788. // @Param pagecount query int true "pagecount"
  1789. // @Param returntype query string true "returntype"
  1790. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1791. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1792. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1793. // @Router /data/PostDataByName [POST]
  1794. func UpdateDataRelation(c *gin.Context) {
  1795. appG := app.Gin{C: c}
  1796. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1797. fsion := gofasion.NewFasion(string(dataByte))
  1798. tablename := fsion.Get("name").ValueStr()
  1799. dataname := fsion.Get("dataname").ValueStr()
  1800. datavalue := fsion.Get("datavalue").ValueStr()
  1801. valuename := fsion.Get("valuename").ValueStr()
  1802. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1803. values := fsion.Get("values").Array()
  1804. tx := restful.Engine.NewSession()
  1805. err := tx.Begin()
  1806. defer func() {
  1807. switch {
  1808. case err != nil:
  1809. if tx != nil {
  1810. tx.Rollback()
  1811. }
  1812. default:
  1813. if tx != nil {
  1814. err = tx.Commit()
  1815. }
  1816. }
  1817. if tx != nil {
  1818. tx.Close()
  1819. }
  1820. }()
  1821. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1822. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1823. d_params := make([]interface{}, 4)
  1824. d_params[0] = datavalue
  1825. s_params := ""
  1826. for _, v_values := range values {
  1827. d_params[1] = v_values.ValueStr()
  1828. if s_params == "" {
  1829. s_params = v_values.ValueStr()
  1830. } else {
  1831. s_params = s_params + "," + v_values.ValueStr()
  1832. }
  1833. d_params[2] = d_params[1]
  1834. d_params[3] = d_params[0]
  1835. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1836. if err != nil {
  1837. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1838. break
  1839. }
  1840. }
  1841. if s_params != "" {
  1842. deleteSqlstr := "delete from " + tablename + " " +
  1843. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1844. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1845. if err != nil {
  1846. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1847. } else if err == nil {
  1848. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1849. }
  1850. } else {
  1851. deleteSqlstr := "delete from " + tablename + " " +
  1852. " where " + dataname + " = " + datavalue
  1853. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1854. if err != nil {
  1855. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1856. } else if err == nil {
  1857. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1858. }
  1859. }
  1860. }
  1861. // @Summary 根据APISQL表中SQL执行得到数据集
  1862. // @Tags PostDatasByName
  1863. // @Accept json
  1864. // @Produce json
  1865. // @Param sqlname query string true "sqlname"
  1866. // @Param offset query int true "offset"
  1867. // @Param pagecount query int true "pagecount"
  1868. // @Param returntype query string true "returntype"
  1869. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1870. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1871. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1872. // @Router /data/PostDatasByName [POST]
  1873. func PostDataByNames(c *gin.Context) {
  1874. appG := app.Gin{C: c}
  1875. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1876. fsion := gofasion.NewFasion(string(dataByte))
  1877. sqlParams := fsion.Get("array").Array()
  1878. queryData := make(map[string]interface{})
  1879. for _, v := range sqlParams {
  1880. fsion2 := gofasion.NewFasion(v.Json())
  1881. ss := fsion2.Get("name")
  1882. aa := fsion2.Get("params")
  1883. fmt.Println(ss, aa)
  1884. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1885. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1886. if sql == "" {
  1887. errorm := make(map[string]interface{})
  1888. errorm["code"] = e.ERROR
  1889. errorm["message"] = "sql没有找到"
  1890. errorm["param"] = ""
  1891. queryData[fsion2.Get("name").ValueStr()] = errorm
  1892. continue
  1893. } else if sql != "" {
  1894. s_params := make([]interface{}, 0)
  1895. if fsion2.HasKey("parammaps") {
  1896. parammaps := fsion2.Get("parammaps")
  1897. paramslist := strings.Split(p, ",")
  1898. if len(paramslist) > 0 && p != "" {
  1899. for _, value := range paramslist {
  1900. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1901. if tempv, exists := c.Get("jwt_username"); exists {
  1902. s_params = append(s_params, tempv.(string))
  1903. } else {
  1904. s_params = append(s_params, "")
  1905. }
  1906. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1907. ids, err := setting.SnowIds.NextId()
  1908. if err != nil {
  1909. ids = time.Now().UnixNano()
  1910. logging.Info("create SnowIds err", err)
  1911. }
  1912. s_params = append(s_params, ids)
  1913. } else {
  1914. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1915. }
  1916. }
  1917. }
  1918. } else if fsion2.HasKey("params") {
  1919. params := fsion2.Get("params").Array()
  1920. //ids,err := setting.SnowIds.NextId()
  1921. //if err !=nil{
  1922. // ids = time.Now().UnixNano()
  1923. // logging.Info("create SnowIds err",err)
  1924. //}
  1925. //s_params = append(s_params, ids)
  1926. for _, v_params := range params {
  1927. s_params = append(s_params, v_params.ValueStr())
  1928. }
  1929. }
  1930. _, err := execDataBySql(sql, s_params)
  1931. if err != nil {
  1932. logging.Error("PostDataByName err: ", err)
  1933. errorm := make(map[string]interface{})
  1934. errorm["code"] = e.ERROR
  1935. errorm["message"] = err.Error()
  1936. errorm["param"] = s_params
  1937. queryData[fsion2.Get("name").ValueStr()] = errorm
  1938. continue
  1939. } else {
  1940. errorm := make(map[string]interface{})
  1941. errorm["code"] = e.SUCCESS
  1942. errorm["message"] = "success"
  1943. queryData[fsion2.Get("name").ValueStr()] = errorm
  1944. continue
  1945. }
  1946. } else {
  1947. errorm := make(map[string]interface{})
  1948. errorm["code"] = e.ERROR
  1949. errorm["message"] = "NO SQL"
  1950. errorm["param"] = ""
  1951. queryData[fsion2.Get("name").ValueStr()] = errorm
  1952. }
  1953. }
  1954. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1955. }
  1956. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1957. if offset > 0 {
  1958. offset = offset - 1
  1959. }
  1960. //if pagecount == 0 {
  1961. // pagecount = setting.AppSetting.PageSize
  1962. //}else if pagecount>setting.AppSetting.PageSize{
  1963. // pagecount = setting.AppSetting.PageSize
  1964. //}
  1965. if returntype == "list" {
  1966. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1967. return queryData, err
  1968. } else if returntype == "listlist" {
  1969. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1970. return queryData, err
  1971. } else {
  1972. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1973. return queryData, err
  1974. }
  1975. }
  1976. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1977. if offset > 0 {
  1978. offset = offset - 1
  1979. }
  1980. //if pagecount == 0 {
  1981. // pagecount = setting.AppSetting.PageSize
  1982. //}else if pagecount>setting.AppSetting.PageSize{
  1983. // pagecount = setting.AppSetting.PageSize
  1984. //}
  1985. if returntype == "list" {
  1986. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1987. return queryData, err
  1988. } else if returntype == "listlist" {
  1989. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1990. return queryData, err
  1991. } else {
  1992. fmt.Println(params)
  1993. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1994. return queryData, err
  1995. }
  1996. }
  1997. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1998. paramslist := strings.Split(Params, ",")
  1999. s_params := make([]interface{}, 0)
  2000. if isList {
  2001. for _, v_params := range thisParams["params"].([]interface{}) {
  2002. s_params = append(s_params, v_params)
  2003. }
  2004. } else {
  2005. paramslist := strings.Split(Params, ",")
  2006. if len(paramslist) > 0 && Params != "" {
  2007. for _, value := range paramslist {
  2008. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2009. }
  2010. }
  2011. }
  2012. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  2013. for _, queryData_ := range queryData {
  2014. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  2015. if isList {
  2016. if queryData_[idname] != nil {
  2017. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  2018. }
  2019. } else {
  2020. if queryData_[idname] != nil {
  2021. thisParams[idname] = queryData_[idname].(interface{})
  2022. }
  2023. if len(paramslist) > 0 && Params != "" {
  2024. s_params = make([]interface{}, 0)
  2025. for _, value := range paramslist {
  2026. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2027. }
  2028. }
  2029. }
  2030. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  2031. } else {
  2032. }
  2033. }
  2034. return queryData, err
  2035. }
  2036. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2037. queryData, err := restful.ExecQuery(sqlstr, params)
  2038. return queryData, err
  2039. }
  2040. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2041. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2042. return queryData, err
  2043. }
  2044. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2045. queryData, err := restful.ExecQuery(sqlstr, params)
  2046. return queryData, err
  2047. }
  2048. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2049. // @Tags ImportExcel
  2050. // @Accept json
  2051. // @Produce json
  2052. // @Param file query string true "文件名"
  2053. // @Param name header string true "执行sql的名字"
  2054. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2055. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2056. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2057. // @Router /data/ImportExcel [POST]
  2058. func ImportExcel(c *gin.Context) {
  2059. appG := app.Gin{C: c}
  2060. inputdata := ""
  2061. c.Request.ParseForm()
  2062. params := c.Request.Form
  2063. file, _, err := c.Request.FormFile("file")
  2064. if err != nil {
  2065. appG.Response(http.StatusOK, e.ERROR, err)
  2066. return
  2067. }
  2068. sqlnamestrs := params.Get("name")
  2069. sheetname := params.Get("sheetname")
  2070. pastureid := params.Get("pastureid")
  2071. //importParams := params.Get("importParams")
  2072. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2073. // 必输项参数 (字符串格式 "field1,field2,field3")
  2074. requiredParams := params.Get("requiredParams")
  2075. // 日期参数
  2076. dateParams := params.Get("dateParams")
  2077. // 数字参数
  2078. numParams := params.Get("numParams")
  2079. //将字符串分割开
  2080. dateParamslist := strings.Split(dateParams, ",")
  2081. requiredParamslist := strings.Split(requiredParams, ",")
  2082. numParamslist := strings.Split(numParams, ",")
  2083. queryData := make([]interface{}, 0)
  2084. sqlslist := strings.Split(sqlnamestrs, ",")
  2085. xlsx1, err := excelize.OpenReader(file)
  2086. if err != nil {
  2087. fmt.Println(err)
  2088. return
  2089. }
  2090. ok := 0
  2091. error := 0
  2092. isdone := true
  2093. rows := xlsx1.GetRows(sheetname)
  2094. // 限制10000条,多余的截取掉
  2095. if len(rows) > 10000 {
  2096. rows = rows[:10000]
  2097. }
  2098. for i, row := range rows {
  2099. if i > 0 {
  2100. entry := make(map[string]interface{})
  2101. outentry := make(map[string]interface{})
  2102. for j, colCell := range rows[0] {
  2103. for k, colCell1 := range row {
  2104. if j == k {
  2105. outentry[colCell] = colCell1
  2106. entry[colCell] = colCell1
  2107. }
  2108. }
  2109. }
  2110. inputdata = ""
  2111. a := ""
  2112. fmt.Println(outentry, entry)
  2113. //校验日期格式
  2114. for _, v := range dateParamslist {
  2115. if v == "" {
  2116. continue
  2117. }
  2118. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2119. dtime, err := TransfTime(d.(string))
  2120. if err != nil {
  2121. a = strings.Trim(v, " ")
  2122. break
  2123. }
  2124. outentry[strings.Trim(v, " ")] = dtime
  2125. }
  2126. }
  2127. if a != "" {
  2128. outentry["error_msg"] = a + " 格式错误"
  2129. error++
  2130. queryData = append(queryData, outentry)
  2131. continue
  2132. }
  2133. a = ""
  2134. //校验必填格式
  2135. for _, v := range requiredParamslist {
  2136. if v == "" {
  2137. continue
  2138. }
  2139. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2140. a = strings.Trim(v, " ")
  2141. break
  2142. }
  2143. }
  2144. if a != "" {
  2145. outentry["error_msg"] = a + " 未填或格式错误"
  2146. error++
  2147. queryData = append(queryData, outentry)
  2148. continue
  2149. }
  2150. a = ""
  2151. //校验数字格式
  2152. for _, v := range numParamslist {
  2153. if v == "" {
  2154. continue
  2155. }
  2156. d, ok := outentry[strings.Trim(v, " ")]
  2157. if !ok || d == "" {
  2158. outentry[strings.Trim(v, " ")] = 0
  2159. } else {
  2160. var fl float64
  2161. switch d.(type) {
  2162. case string:
  2163. fl, err = strconv.ParseFloat(d.(string), 64)
  2164. }
  2165. if err != nil || fl < 0 {
  2166. a = strings.Trim(v, " ")
  2167. break
  2168. }
  2169. }
  2170. }
  2171. if a != "" {
  2172. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2173. error++
  2174. queryData = append(queryData, outentry)
  2175. continue
  2176. }
  2177. tx := restful.Engine.NewSession()
  2178. err := tx.Begin()
  2179. for _, sqlnamestr := range sqlslist {
  2180. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2181. paramslist := strings.Split(paramslists, ",")
  2182. if len(paramslist) > 0 {
  2183. s_params := make([]interface{}, 0)
  2184. for _, value := range paramslist {
  2185. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2186. if tempv, exists := c.Get("jwt_username"); exists {
  2187. s_params = append(s_params, tempv.(string))
  2188. } else {
  2189. s_params = append(s_params, "")
  2190. }
  2191. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2192. s_params = append(s_params, pastureid)
  2193. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2194. ids, err := setting.SnowIds.NextId()
  2195. if err != nil {
  2196. ids = time.Now().UnixNano()
  2197. logging.Info("create SnowIds err", err)
  2198. }
  2199. s_params = append(s_params, ids)
  2200. } else {
  2201. if outentry[strings.Trim(value, " ")] == nil {
  2202. s_params = append(s_params, "")
  2203. } else {
  2204. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2205. }
  2206. }
  2207. }
  2208. outentry["input"] = inputdata
  2209. fmt.Println(sql, s_params)
  2210. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2211. if err != nil {
  2212. if tx != nil {
  2213. tx.Rollback()
  2214. }
  2215. if tx != nil {
  2216. tx.Close()
  2217. }
  2218. msg := geterrmsg(err.Error())
  2219. outentry["error_msg"] = msg
  2220. error++
  2221. queryData = append(queryData, outentry)
  2222. isdone = true
  2223. break
  2224. } else {
  2225. if len(returnmsgmap1) > 0 {
  2226. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2227. if tx != nil {
  2228. tx.Rollback()
  2229. }
  2230. if tx != nil {
  2231. tx.Close()
  2232. }
  2233. msg := geterrmsg(va.(string))
  2234. outentry["error_msg"] = msg
  2235. error++
  2236. queryData = append(queryData, outentry)
  2237. isdone = true
  2238. break
  2239. }
  2240. }
  2241. isdone = false
  2242. }
  2243. }
  2244. }
  2245. switch {
  2246. case err != nil:
  2247. if tx != nil {
  2248. tx.Rollback()
  2249. }
  2250. default:
  2251. if tx != nil {
  2252. err = tx.Commit()
  2253. }
  2254. }
  2255. if tx != nil {
  2256. tx.Close()
  2257. }
  2258. }
  2259. if !isdone {
  2260. ok++
  2261. isdone = true
  2262. }
  2263. }
  2264. data := make(map[string]interface{})
  2265. data["result"] = queryData
  2266. data["success"] = ok
  2267. data["err_count"] = error
  2268. appG.Response(http.StatusOK, e.SUCCESS, data)
  2269. }
  2270. func TransfTime(timestr string) (string, error) {
  2271. if timestr == "" {
  2272. return time.Now().Format("2006-01-02"), nil
  2273. }
  2274. days, err := strconv.Atoi(timestr)
  2275. if err != nil {
  2276. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2277. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2278. }
  2279. _, err := time.Parse("2006-01-02", timestr)
  2280. if err != nil {
  2281. t, err := time.Parse("2006/01/02", timestr)
  2282. if err != nil {
  2283. t, err := time.Parse("2006.01.02", timestr)
  2284. if err != nil {
  2285. return "", err
  2286. } else {
  2287. return t.Format("2006-01-02"), nil
  2288. }
  2289. } else {
  2290. return t.Format("2006-01-02"), nil
  2291. }
  2292. } else {
  2293. return timestr, nil
  2294. }
  2295. }
  2296. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2297. times = times.AddDate(0, 0, days)
  2298. return times.Format("2006-01-02"), nil
  2299. }
  2300. func Createchart(c *gin.Context) {
  2301. appG := app.Gin{C: c}
  2302. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2303. fsion := gofasion.NewFasion(string(dataByte))
  2304. chart_name := fsion.Get("chart_name").ValueStr()
  2305. desc := fsion.Get("desc").ValueStr()
  2306. pastureid := fsion.Get("pastureid").ValueStr()
  2307. source_id := fsion.Get("source_id").ValueStr()
  2308. emp := fsion.Get("emp").ValueStr()
  2309. content := fsion.Get("content").Json()
  2310. var mapResult map[string]interface{}
  2311. err1 := json.Unmarshal([]byte(content), &mapResult)
  2312. if err1 != nil {
  2313. fmt.Println("JsonToMapDemo err: ", err1)
  2314. }
  2315. tx := restful.Engine.NewSession()
  2316. err := tx.Begin()
  2317. defer func() {
  2318. switch {
  2319. case err != nil:
  2320. logging.Error("tx.Begin 事务启动失败__error:", err)
  2321. if tx != nil {
  2322. tx.Rollback()
  2323. }
  2324. default:
  2325. if tx != nil {
  2326. err = tx.Commit()
  2327. }
  2328. }
  2329. if tx != nil {
  2330. tx.Close()
  2331. }
  2332. }()
  2333. ids, err := setting.SnowIds.NextId()
  2334. if err != nil {
  2335. ids = time.Now().UnixNano()
  2336. logging.Info("create SnowIds err", err)
  2337. }
  2338. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2339. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2340. if err != nil {
  2341. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2342. } else {
  2343. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2344. }
  2345. }
  2346. func Updatedashboard(c *gin.Context) {
  2347. appG := app.Gin{C: c}
  2348. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2349. fsion := gofasion.NewFasion(string(dataByte))
  2350. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2351. pastureid := fsion.Get("pastureid").ValueStr()
  2352. content := fsion.Get("content").Json()
  2353. var mapResult map[string]interface{}
  2354. err1 := json.Unmarshal([]byte(content), &mapResult)
  2355. if err1 != nil {
  2356. fmt.Println("JsonToMapDemo err: ", err1)
  2357. }
  2358. layout := mapResult["layout"]
  2359. tx := restful.Engine.NewSession()
  2360. err := tx.Begin()
  2361. defer func() {
  2362. switch {
  2363. case err != nil:
  2364. logging.Error("tx.Begin 事务启动失败__error:", err)
  2365. if tx != nil {
  2366. tx.Rollback()
  2367. }
  2368. default:
  2369. if tx != nil {
  2370. err = tx.Commit()
  2371. }
  2372. }
  2373. if tx != nil {
  2374. tx.Close()
  2375. }
  2376. }()
  2377. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2378. if err != nil {
  2379. println("2", err.Error())
  2380. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2381. } else {
  2382. if exec != nil {
  2383. if exec[0]["content"] == nil {
  2384. mapR := make(map[string]interface{})
  2385. mapR["layout"] = layout
  2386. mjson, _ := json.Marshal(mapR)
  2387. mString := string(mjson)
  2388. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2389. if err3 != nil {
  2390. println("3", err3.Error())
  2391. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2392. } else {
  2393. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2394. }
  2395. } else {
  2396. var mapR map[string]interface{}
  2397. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2398. if err1 != nil {
  2399. fmt.Println("JsonToMapDemo err: ", err2)
  2400. }
  2401. mapR["layout"] = layout
  2402. mjson, _ := json.Marshal(mapR)
  2403. mString := string(mjson)
  2404. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2405. if err3 != nil {
  2406. println("3", err3.Error())
  2407. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2408. } else {
  2409. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2410. }
  2411. }
  2412. } else {
  2413. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2414. }
  2415. }
  2416. }
  2417. func ExecSQL(c *gin.Context) {
  2418. appG := app.Gin{C: c}
  2419. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2420. fsion := gofasion.NewFasion(string(dataByte))
  2421. content := fsion.Get("content").Json()
  2422. pastureid := fsion.Get("pastureid").ValueStr()
  2423. var mapResult map[string]interface{}
  2424. err1 := json.Unmarshal([]byte(content), &mapResult)
  2425. if err1 != nil {
  2426. fmt.Println("JsonToMapDemo err: ", err1)
  2427. }
  2428. sqlstr := "select "
  2429. groupstr := " GROUP BY "
  2430. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2431. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2432. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2433. }
  2434. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2435. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2436. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2437. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2438. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2439. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2440. sqlstr = sqlstr + tem + ","
  2441. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2442. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2443. sqlstr = sqlstr + tem + ","
  2444. } else {
  2445. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2446. sqlstr = sqlstr + tem + ","
  2447. }
  2448. }
  2449. if _, ok := mapResult["selectedCalcul2"]; ok {
  2450. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2451. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2452. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2453. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2454. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2455. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2456. sqlstr = sqlstr + tem + ","
  2457. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2458. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2459. sqlstr = sqlstr + tem + ","
  2460. } else {
  2461. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2462. sqlstr = sqlstr + tem + ","
  2463. }
  2464. }
  2465. }
  2466. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2467. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2468. sqlstr = sqlstr + " where pastureid=" + pastureid
  2469. if len(mapResult["filters"].([]interface{})) > 0 {
  2470. sqlstr = sqlstr + " and "
  2471. }
  2472. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2473. for _, value := range mapResult["filters"].([]interface{}) {
  2474. switch value.(map[string]interface{})["filterOperator"].(string) {
  2475. case ">", "=", "<", ">=", "<=", "!=", "like":
  2476. 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 "
  2477. case "IN":
  2478. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2479. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2480. sqlstr = sqlstr + value1.(string) + ","
  2481. }
  2482. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2483. sqlstr = sqlstr + ")" + " AND "
  2484. case "BETWEEN":
  2485. 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 "
  2486. }
  2487. }
  2488. if len(mapResult["filters"].([]interface{})) > 0 {
  2489. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2490. }
  2491. //
  2492. groupstr = groupstr[0 : len(groupstr)-1]
  2493. sqlstr = sqlstr + groupstr + " "
  2494. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2495. sqlstr = sqlstr + " order by "
  2496. }
  2497. //
  2498. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2499. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2500. sqlstr = sqlstr + value.(string) + " "
  2501. } else {
  2502. sqlstr = sqlstr + value.(string) + ","
  2503. }
  2504. }
  2505. //
  2506. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2507. tx := restful.Engine.NewSession()
  2508. err := tx.Begin()
  2509. defer func() {
  2510. switch {
  2511. case err != nil:
  2512. logging.Error("tx.Begin 事务启动失败__error:", err)
  2513. if tx != nil {
  2514. tx.Rollback()
  2515. }
  2516. default:
  2517. if tx != nil {
  2518. err = tx.Commit()
  2519. }
  2520. }
  2521. if tx != nil {
  2522. tx.Close()
  2523. }
  2524. }()
  2525. exec, err := tx.SQL(sqlstr).Query().List()
  2526. if err != nil {
  2527. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2528. } else {
  2529. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2530. }
  2531. }
  2532. func Dashboards(c *gin.Context) {
  2533. appG := app.Gin{C: c}
  2534. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2535. fsion := gofasion.NewFasion(string(dataByte))
  2536. sqlnamestr := fsion.Get("name").ValueStr()
  2537. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2538. offset := fsion.Get("offset").ValueDefaultInt(0)
  2539. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2540. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2541. month := fsion.Get("month").ValueDefaultStr("map")
  2542. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2543. tx := restful.Engine.NewSession()
  2544. err := tx.Begin()
  2545. defer func() {
  2546. switch {
  2547. case err != nil:
  2548. if tx != nil {
  2549. tx.Rollback()
  2550. }
  2551. default:
  2552. if tx != nil {
  2553. err = tx.Commit()
  2554. }
  2555. }
  2556. if tx != nil {
  2557. tx.Close()
  2558. }
  2559. }()
  2560. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2561. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2562. if sql != "" {
  2563. s_params := make([]interface{}, 0)
  2564. if fsion.HasKey("parammaps") {
  2565. parammaps := fsion.Get("parammaps")
  2566. paramslist := strings.Split(p, ",")
  2567. if len(paramslist) > 0 && p != "" {
  2568. for _, value := range paramslist {
  2569. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2570. if tempv, exists := c.Get("jwt_username"); exists {
  2571. s_params = append(s_params, tempv.(string))
  2572. } else {
  2573. s_params = append(s_params, "")
  2574. }
  2575. } else {
  2576. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2577. }
  2578. }
  2579. }
  2580. }
  2581. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2582. if err != nil {
  2583. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2584. } else {
  2585. //paramslist1 := strings.Split(p1, ",")
  2586. dids := make([]interface{}, 0)
  2587. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2588. var mapResult map[string]interface{}
  2589. dids = append(dids, value["dashboard_id"])
  2590. if value["content"] != nil {
  2591. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2592. if err1 != nil {
  2593. println("JsonToMapDemo1 err: ", err1)
  2594. }
  2595. temap := make(map[string]interface{})
  2596. tem := mapResult["layout"].([]interface{})
  2597. if v, ok := value["chartids"]; ok {
  2598. chartids := strings.Split(v.(string), ",")
  2599. for _, va := range chartids {
  2600. a := false
  2601. for _, v2 := range tem {
  2602. if v2.(map[string]interface{})["id"].(string) == va {
  2603. a = true
  2604. //println("va1======",va)
  2605. }
  2606. }
  2607. if !a {
  2608. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2609. va + "\",\"id\":\"" + va +
  2610. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2611. var mapTem map[string]interface{}
  2612. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2613. if err1 != nil {
  2614. println("JsonToMapDemo err: ", err1)
  2615. }
  2616. tem = append(tem, mapTem)
  2617. }
  2618. }
  2619. temap["layout"] = tem
  2620. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2621. }
  2622. } else {
  2623. temap := make(map[string]interface{})
  2624. tem := make([]interface{}, 0)
  2625. if v, ok := value["chartids"]; ok {
  2626. chartids := strings.Split(v.(string), ",")
  2627. for _, va := range chartids {
  2628. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2629. va + "\",\"id\":\"" + va +
  2630. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2631. var mapTem map[string]interface{}
  2632. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2633. if err1 != nil {
  2634. println("JsonToMapDemo err: ", err1)
  2635. }
  2636. tem = append(tem, mapTem)
  2637. }
  2638. temap["layout"] = tem
  2639. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2640. }
  2641. }
  2642. }
  2643. queryData.(map[string]interface{})["order"] = dids
  2644. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2645. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2646. }
  2647. } else {
  2648. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2649. }
  2650. }
  2651. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2652. fsion := gofasion.NewFasion(parammaps)
  2653. sqlnamestr := fsion.Get("name").ValueStr()
  2654. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2655. offset := fsion.Get("offset").ValueDefaultInt(0)
  2656. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2657. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2658. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2659. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2660. body := []byte("")
  2661. if sql != "" {
  2662. s_params := make([]interface{}, 0)
  2663. if fsion.HasKey("parammaps") {
  2664. parammaps := fsion.Get("parammaps")
  2665. paramslist := strings.Split(p, ",")
  2666. if len(paramslist) > 0 && p != "" {
  2667. for _, value := range paramslist {
  2668. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2669. }
  2670. }
  2671. }
  2672. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2673. if err != nil {
  2674. } else {
  2675. paramslist1 := strings.Split(p1, ",")
  2676. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2677. s_params1 := make([]interface{}, 0)
  2678. if len(paramslist1) > 0 && p1 != "" {
  2679. for _, v := range paramslist1 {
  2680. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2681. }
  2682. }
  2683. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2684. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2685. body, _ = json.Marshal(queryData)
  2686. }
  2687. }
  2688. }
  2689. bs := bytes.NewBuffer(body)
  2690. client := &http.Client{}
  2691. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2692. req, err := http.NewRequest(RequestMethod,
  2693. url,
  2694. bs,
  2695. )
  2696. if err != nil {
  2697. }
  2698. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2699. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2700. if err != nil {
  2701. // handle error
  2702. }
  2703. resp, err := client.Do(req)
  2704. if err != nil {
  2705. return ""
  2706. }
  2707. defer resp.Body.Close()
  2708. result_body, err := ioutil.ReadAll(resp.Body)
  2709. if err != nil {
  2710. return ""
  2711. }
  2712. fmt.Println(string(result_body))
  2713. return ""
  2714. }
  2715. func GetSummary(c *gin.Context) {
  2716. appG := app.Gin{C: c}
  2717. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2718. fsion := gofasion.NewFasion(string(dataByte))
  2719. offset := fsion.Get("offset").ValueDefaultInt(0)
  2720. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2721. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2722. parammaps := fsion.Get("parammaps")
  2723. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2724. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2725. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2726. tx := restful.Engine.NewSession()
  2727. defer tx.Close()
  2728. sqlnamestr := ""
  2729. if genre == "0" {
  2730. if status == "0" {
  2731. sqlnamestr = "getAccuracyJSY"
  2732. } else if status == "1" {
  2733. sqlnamestr = "getAccuracyHFT"
  2734. } else if status == "2" {
  2735. sqlnamestr = "getAccuracyHNS"
  2736. } else if status == "3" {
  2737. sqlnamestr = "getAccuracyHSC"
  2738. } else if status == "4" {
  2739. sqlnamestr = "getAccuracyHCC"
  2740. } else if status == "5" {
  2741. sqlnamestr = "getAccuracyMC"
  2742. } else if status == "6" {
  2743. sqlnamestr = "getAccuracyFeedHL"
  2744. } else if status == "7" {
  2745. sqlnamestr = "getAccuracyRT"
  2746. }
  2747. } else {
  2748. if status == "0" {
  2749. sqlnamestr = "getAccuracySCCJSY"
  2750. } else if status == "1" {
  2751. sqlnamestr = "getAccuracySFT"
  2752. } else if status == "2" {
  2753. sqlnamestr = "getAccuracySNS"
  2754. } else if status == "3" {
  2755. sqlnamestr = "getAccuracySSC"
  2756. } else if status == "4" {
  2757. sqlnamestr = "getAccuracySCC"
  2758. } else if status == "5" {
  2759. sqlnamestr = "getAccuracySLCL"
  2760. } else if status == "7" {
  2761. sqlnamestr = "getAccuracySCCRT"
  2762. }
  2763. }
  2764. if isDate == "1" {
  2765. sqlnamestr += "Date"
  2766. }
  2767. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2768. // fmt.Println(sqlnamestr, sql)
  2769. if sql != "" {
  2770. s_params := make([]interface{}, 0)
  2771. // if fsion.HasKey("parammaps") {
  2772. fmt.Println(s_params, "222", p)
  2773. paramslist := strings.Split(p, ",")
  2774. if len(paramslist) > 0 && p != "" {
  2775. for _, value := range paramslist {
  2776. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2777. if tempv, exists := c.Get("jwt_username"); exists {
  2778. s_params = append(s_params, tempv.(string))
  2779. } else {
  2780. s_params = append(s_params, "")
  2781. }
  2782. } else {
  2783. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2784. }
  2785. }
  2786. }
  2787. if returntype == "xlsx" {
  2788. var xlsxfile *xlsx.File
  2789. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2790. //c.File("c:/dd.xlsx")
  2791. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2792. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2793. c.Header("Content-Transfer-Encoding", "binary")
  2794. _ = xlsxfile.Write(c.Writer)
  2795. } else {
  2796. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2797. if err != nil {
  2798. logging.Error("GetDataByName err: ", err)
  2799. msg := geterrmsg(err.Error())
  2800. appG.Response(http.StatusOK, e.ERROR, msg)
  2801. } else {
  2802. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2803. }
  2804. }
  2805. } else {
  2806. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2807. }
  2808. }
  2809. // type lpplanStruct struct {
  2810. // Id int64 `xorm:"id"`
  2811. // Tmrname string `xorm:"tmrname"`
  2812. // Tmrid int64 `xorm:"tmrid"`
  2813. // Sort int64 `xorm:"sort"`
  2814. // Sel int64 `xorm:"sel"`
  2815. // Times int64 `xorm:"times"`
  2816. // Ftname string `xorm:"ftname"`
  2817. // Ftid int64 `xorm:"ftid"`
  2818. // Maxweight float64 `xorm:"maxweight"`
  2819. // Sumweight float64 `xorm:"sumweight"`
  2820. // Sumcowcount int64 `xorm:"sumcowcount"`
  2821. // Pastureid string `xorm:"pastureid"`
  2822. // Display string `xorm:"display"`
  2823. // Issplit int64 `xorm:"issplit"`
  2824. // BeginTime string `xorm:"begintime"`
  2825. // }
  2826. func UpdateFTdetail(c *gin.Context) {
  2827. appG := app.Gin{C: c}
  2828. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2829. tempval_ := make(map[string]interface{})
  2830. tempCommon := make(map[string]interface{})
  2831. tempval := make([]map[string]interface{}, 0)
  2832. fTChange := make(map[string]interface{}, 0)
  2833. // fpdOldDataList := make([]map[string]interface{}, 0)
  2834. // fpdDataList := make([]map[string]interface{}, 0)
  2835. fsion := gofasion.NewFasion(string(dataByte))
  2836. // parammaps := fsion.Get("parammaps")
  2837. createdate := time.Now().Format("2006-01-02 15:04:05")
  2838. err := json.Unmarshal(dataByte, &tempval_)
  2839. if err != nil {
  2840. appG.Response(http.StatusOK, e.ERROR, false)
  2841. return
  2842. }
  2843. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2844. tx := restful.Engine.NewSession()
  2845. if v, ok := tempval_["data"].([]interface{}); ok {
  2846. for _, Tvalue := range v {
  2847. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2848. if v1["name"] == "updateFPbyFTChange" {
  2849. fTChange = v1
  2850. continue
  2851. }
  2852. tempval = append(tempval, v1)
  2853. }
  2854. }
  2855. }
  2856. parammaps := fTChange["parammaps"].(map[string]interface{})
  2857. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2858. // if err != nil {
  2859. // logs.Error(err)
  2860. // appG.Response(http.StatusOK, e.ERROR, false)
  2861. // return
  2862. // }
  2863. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2864. // if err != nil {
  2865. // logs.Error(err)
  2866. // appG.Response(http.StatusOK, e.ERROR, false)
  2867. // return
  2868. // }
  2869. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2870. // if err != nil {
  2871. // logs.Error(err)
  2872. // appG.Response(http.StatusOK, e.ERROR, false)
  2873. // return
  2874. // }
  2875. err = tx.Begin()
  2876. if err != nil {
  2877. logging.Error("tx.Begin 事务启动失败__error:", err)
  2878. }
  2879. defer func() {
  2880. if err != nil {
  2881. if tx != nil {
  2882. tx.Rollback()
  2883. }
  2884. }
  2885. if tx != nil {
  2886. tx.Close()
  2887. }
  2888. }()
  2889. if err != nil {
  2890. } else {
  2891. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2892. tempCommon = v
  2893. }
  2894. // 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 ,
  2895. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2896. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2897. // UNION
  2898. // 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 ,
  2899. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2900. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2901. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2902. if err == nil {
  2903. if tempv, exists := c.Get("jwt_username"); exists {
  2904. tempCommon["jwt_username"] = tempv.(string)
  2905. }
  2906. for _, paramvalue := range tempval {
  2907. if _, ok := paramvalue["resultname"]; !ok {
  2908. paramvalue["resultname"] = paramvalue["name"]
  2909. }
  2910. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2911. if err != nil {
  2912. logging.Error("ExecDataParam error:", err)
  2913. break
  2914. }
  2915. }
  2916. if err != nil {
  2917. msg := geterrmsg(err.Error())
  2918. appG.Response(http.StatusOK, e.ERROR, msg)
  2919. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2920. }
  2921. }
  2922. }
  2923. tx.Commit()
  2924. // go func() {
  2925. if fTChange != nil {
  2926. parammaps := fTChange["parammaps"].(map[string]interface{})
  2927. if parammaps["type"].(float64) == 1 {
  2928. _, err = tx.SQL(`UPDATE feedp fp
  2929. set
  2930. ccountratio = ccount *(ratio /100 ),
  2931. fp.ftweight= IFNULL(IF(
  2932. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2933. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2934. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2935. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2936. ),0),fp.feedweight = IFNULL(IF(
  2937. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2938. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2939. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2940. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2941. ),0) +ifnull(fp.supplyweight,0)
  2942. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2943. _, err = tx.SQL(`UPDATE fpdetail fpd
  2944. INNER JOIN feedp fp
  2945. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2946. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2947. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2948. } else {
  2949. _, err = tx.SQL(`UPDATE feedp fp
  2950. SET ccountratio = ccount *(ratio /100 ),
  2951. fp.supplyweight= IFNULL(IF(
  2952. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2953. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2954. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2955. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2956. ),0),fp.feedweight = IFNULL(IF(
  2957. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2958. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2959. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2960. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2961. ),0) +ifnull(fp.supplyweight,0)
  2962. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2963. _, err = tx.SQL(`UPDATE fpdetail fpd
  2964. INNER JOIN feedp fp
  2965. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2966. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2967. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2968. }
  2969. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  2970. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  2971. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  2972. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  2973. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  2974. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  2975. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  2976. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  2977. join feedtemplet ft on ft.id = fp.ftid where ft.id = ?`, parammaps["ftid"]).QueryString()
  2978. // fmt.Println(ftId)
  2979. FpdBatchEditGrfd(fmt.Sprintf("%v", parammaps["pastureid"]), values1)
  2980. // 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 ,
  2981. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2982. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2983. // UNION
  2984. // 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 ,
  2985. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2986. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2987. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2988. // lpplanList := make([]*lpplanStruct, 0)
  2989. // err = tx.SQL(`select id,times,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpplan.pastureid ) = 0 ,
  2990. // ifnull((select maxstirfeed from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),100000),(select ifnull(volume,0) from tmr where id = lpplan.tmrid ) *
  2991. // (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)
  2992. // if err != nil {
  2993. // logs.Error(err, 1)
  2994. // return
  2995. // }
  2996. // lppidlist := []string{}
  2997. // for _, lpp := range lpplanList {
  2998. // lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2999. // }
  3000. // if len(lppidlist) <= 0 {
  3001. // appG.Response(http.StatusOK, e.SUCCESS, true)
  3002. // return
  3003. // }
  3004. // lpplandtl1AllList := make([]*lpplandtl1, 0)
  3005. // err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  3006. // order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  3007. // if err != nil {
  3008. // // tx.Rollback()
  3009. // logs.Error(err, 2, parammaps["pastureid"])
  3010. // return
  3011. // }
  3012. // for _, lpp := range lpplandtl1AllList {
  3013. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  3014. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  3015. // if err != nil {
  3016. // logs.Error(err)
  3017. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3018. // return
  3019. // }
  3020. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3021. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  3022. // if err != nil {
  3023. // logs.Error(err)
  3024. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3025. // return
  3026. // }
  3027. // }
  3028. // var wg sync.WaitGroup
  3029. // for _, old := range fpdOldDataList {
  3030. // for _, fpd := range fpdDataList {
  3031. // wg.Add(1)
  3032. // go func(old, fpd map[string]interface{}) {
  3033. // updateLppandList := make([]*lpplandtl1, 0)
  3034. // defer wg.Done()
  3035. // if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3036. // fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3037. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3038. // oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3039. // // if weight > oldweight {
  3040. // // return
  3041. // // }
  3042. // var w float64
  3043. // var status int
  3044. // if weight < oldweight {
  3045. // if weight >= 0 {
  3046. // return
  3047. // }
  3048. // w = weight
  3049. // status = 0
  3050. // } else {
  3051. // if oldweight > 0 {
  3052. // return
  3053. // }
  3054. // w = weight
  3055. // status = 1
  3056. // }
  3057. // // fweight = w
  3058. // for _, lpp := range lpplanList {
  3059. // var fweight float64
  3060. // var lweight float64
  3061. // lpplandtl1List := make([]*lpplandtl1, 0)
  3062. // fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3063. // for _, lppland := range lpplandtl1AllList {
  3064. // if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3065. // lpplandtl1List = append(lpplandtl1List, lppland)
  3066. // }
  3067. // }
  3068. // if len(lpplandtl1List) == 0 {
  3069. // continue
  3070. // }
  3071. // for _, lppland := range lpplandtl1List {
  3072. // lweight += lppland.Lweight
  3073. // }
  3074. // if status == 0 {
  3075. // if lweight <= 0 {
  3076. // continue
  3077. // }
  3078. // } else {
  3079. // if lpp.Maxweight <= lweight {
  3080. // continue
  3081. // }
  3082. // }
  3083. // for _, lppland := range lpplandtl1List {
  3084. // if fpdid == lppland.Fpdid {
  3085. // if status == 1 {
  3086. // // if w <= lppland.Lweight {
  3087. // if lpp.Maxweight <= lweight {
  3088. // continue
  3089. // }
  3090. // if w+lweight <= lpp.Maxweight {
  3091. // lppland.Lweight += w
  3092. // lweight += w
  3093. // fweight += w
  3094. // w = 0
  3095. // } else {
  3096. // w = w - (lpp.Maxweight - lweight)
  3097. // n := (lpp.Maxweight - lweight)
  3098. // lppland.Lweight = lppland.Lweight + n
  3099. // lweight += n
  3100. // fweight += n
  3101. // }
  3102. // } else {
  3103. // if lppland.Lweight == 0 {
  3104. // continue
  3105. // }
  3106. // if w+lppland.Lweight >= 0 {
  3107. // lppland.Lweight = lppland.Lweight + w
  3108. // lweight = lweight + w
  3109. // fweight = fweight + w
  3110. // w = 0
  3111. // } else {
  3112. // w = w + lppland.Lweight
  3113. // lweight = lweight - lppland.Lweight
  3114. // fweight = fweight - lppland.Lweight
  3115. // lppland.Lweight = 0
  3116. // }
  3117. // }
  3118. // updateLppandList = append(updateLppandList, lppland)
  3119. // break
  3120. // }
  3121. // }
  3122. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3123. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3124. // WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3125. // if err != nil {
  3126. // // tx.Rollback()
  3127. // logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3128. // return
  3129. // }
  3130. // for _, lppland := range updateLppandList {
  3131. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3132. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3133. // if err != nil {
  3134. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3135. // // tx.Rollback()
  3136. // logs.Error(err, 3)
  3137. // return
  3138. // }
  3139. // // defer wg.Done()
  3140. // }
  3141. // updateLppandList = []*lpplandtl1{}
  3142. // if w == 0 {
  3143. // break
  3144. // }
  3145. // }
  3146. // }
  3147. // }(old, fpd)
  3148. // }
  3149. // }
  3150. // wg.Wait()
  3151. }
  3152. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3153. if err != nil {
  3154. logs.Error(err)
  3155. appG.Response(http.StatusOK, e.ERROR, false)
  3156. return
  3157. }
  3158. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3159. if err != nil {
  3160. logs.Error(err)
  3161. appG.Response(http.StatusOK, e.ERROR, false)
  3162. return
  3163. }
  3164. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3165. if err != nil {
  3166. logs.Error(err)
  3167. appG.Response(http.StatusOK, e.ERROR, false)
  3168. return
  3169. }
  3170. now := createdate
  3171. // for _, oldFpd := range oldFpdDataList {
  3172. for _, newFpd := range newFpdDataList {
  3173. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3174. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3175. // go func() {
  3176. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3177. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3178. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3179. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3180. if err != nil {
  3181. logs.Error(err)
  3182. appG.Response(http.StatusOK, e.ERROR, false)
  3183. return
  3184. }
  3185. // }()
  3186. }
  3187. // break
  3188. // }
  3189. // }
  3190. // }
  3191. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3192. for _, newLpplandtl1 := range newLpplandtl1List {
  3193. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3194. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3195. // go func() {
  3196. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3197. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3198. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3199. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3200. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3201. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3202. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3203. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3204. if err != nil {
  3205. logs.Error(err)
  3206. appG.Response(http.StatusOK, e.ERROR, false)
  3207. return
  3208. }
  3209. // }()
  3210. // }
  3211. // break
  3212. // }
  3213. // }
  3214. }
  3215. // for _, oldFeedp := range oldFeedpList {
  3216. for _, newFeedp := range newFeedpList {
  3217. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3218. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3219. // go func() {
  3220. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3221. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3222. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3223. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3224. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3225. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3226. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3227. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3228. if err != nil {
  3229. logs.Error(err)
  3230. appG.Response(http.StatusOK, e.ERROR, false)
  3231. return
  3232. }
  3233. }
  3234. // ,,parammaps["ftid"])
  3235. // surplus, surplusId, id, pastureId string
  3236. // FtdetailSurplusFt(parammaps["ftid"].)
  3237. ftList1, err := tx.SQL(` SELECT
  3238. f.id,
  3239. f.surplus surplusId,
  3240. f.pastureid,
  3241. s.surplus
  3242. FROM
  3243. feedtemplet f
  3244. JOIN surplus s ON s.id = f.surplus
  3245. WHERE
  3246. f.id = ?`, parammaps["ftid"]).QueryString()
  3247. for _, ft := range ftList1 {
  3248. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3249. }
  3250. appG.Response(http.StatusOK, e.SUCCESS, true)
  3251. }
  3252. type lpplandtlInfo struct {
  3253. Id int64 `xorm:"id"`
  3254. Pastureid int64 `xorm:"pastureid"`
  3255. Lppid int64 `xorm:"lppid"`
  3256. Barid int64 `xorm:"barid"`
  3257. Barname string `xorm:"barname"`
  3258. Fpdid int64 `xorm:"fpdid"`
  3259. Fttype int64 `xorm:"fttype"`
  3260. Lweight float64 `xorm:"lweight"`
  3261. Sort int64 `xorm:"sort"`
  3262. Tmrid int64 `xorm:"tmrid"`
  3263. Tmrname string `xorm:"tmrname"`
  3264. Cowcount int64 `xorm:"cowcount"`
  3265. Ccountradio float64 `xorm:"ccountradio"`
  3266. Background string `xorm:"background"`
  3267. Lweighthis float64 `xorm:"lweighthis"`
  3268. Maxweight float64 `xorm:"maxweight"`
  3269. }
  3270. func UpdateFpdetailBar(c *gin.Context) {
  3271. appG := app.Gin{C: c}
  3272. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3273. fsion := gofasion.NewFasion(string(dataByte))
  3274. pastureid := fsion.Get("pastureid").ValueStr()
  3275. id := fsion.Get("id").ValueStr()
  3276. tx := restful.Engine.NewSession()
  3277. tx.Begin()
  3278. 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 `,
  3279. pastureid, id).Query().List()
  3280. if err != nil {
  3281. logs.Error(err)
  3282. }
  3283. for _, fpd := range fpdList {
  3284. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3285. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3286. pastureid, fpd["id"]).Query().List()
  3287. if err != nil {
  3288. tx.Rollback()
  3289. logs.Error(err)
  3290. appG.Response(http.StatusOK, e.ERROR, false)
  3291. return
  3292. }
  3293. var lweight float64
  3294. for _, lppland := range lpplandList {
  3295. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3296. lweight += lweight1
  3297. }
  3298. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3299. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3300. if fpdweight >= ptuse && lweight == ptuse {
  3301. continue
  3302. } else {
  3303. if lweight <= fpdweight {
  3304. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3305. if err != nil {
  3306. tx.Rollback()
  3307. logs.Error(err)
  3308. appG.Response(http.StatusOK, e.ERROR, false)
  3309. return
  3310. }
  3311. } else {
  3312. weight := fpdweight - lweight
  3313. for _, lppland := range lpplandList {
  3314. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3315. if weight >= lpplandlweight {
  3316. weight = weight - lpplandlweight
  3317. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3318. if err != nil {
  3319. tx.Rollback()
  3320. logs.Error(err)
  3321. appG.Response(http.StatusOK, e.ERROR, false)
  3322. return
  3323. }
  3324. } else {
  3325. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3326. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3327. // if err != nil {
  3328. // tx.Rollback()
  3329. // logs.Error(err)
  3330. // appG.Response(http.StatusOK, e.ERROR, false)
  3331. // return
  3332. // }
  3333. weight = 0
  3334. break
  3335. }
  3336. }
  3337. }
  3338. }
  3339. }
  3340. fsionData := fsion.Get("data").Array()
  3341. for _, list := range fsionData {
  3342. ftmap := make(map[string]interface{})
  3343. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3344. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3345. ftmap["times"] = list.Get("times").ValueInt64()
  3346. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3347. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3348. // fmt.Println(ftmap)
  3349. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3350. // and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3351. // if count == 1 {
  3352. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3353. // and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3354. // if err != nil {
  3355. // tx.Rollback()
  3356. // logs.Error(err)
  3357. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3358. // return
  3359. // }
  3360. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3361. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3362. // if err != nil {
  3363. // tx.Rollback()
  3364. // logs.Error(err)
  3365. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3366. // return
  3367. // }
  3368. // }
  3369. fpdDataList, err := tx.SQL(`
  3370. 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 ,
  3371. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3372. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3373. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3374. if err != nil {
  3375. tx.Rollback()
  3376. logs.Error(err)
  3377. }
  3378. for _, fpd := range fpdDataList {
  3379. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3380. fttype := -1
  3381. if fpd["fttype"].(string) == "1" {
  3382. fttype = 1
  3383. }
  3384. var fweight float64
  3385. var lweight float64
  3386. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3387. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  3388. t.maxstirfeed,(select ifnull(volume,0) from tmr where id = lpp.tmrid ) *
  3389. (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  3390. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3391. join tmr t on t.id = lpp.tmrid
  3392. where lppland.fpdid =?
  3393. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3394. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3395. if err != nil {
  3396. tx.Rollback()
  3397. logs.Error(err)
  3398. }
  3399. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3400. var w float64
  3401. var status int
  3402. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3403. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3404. if weight >= 0 {
  3405. continue
  3406. }
  3407. w = weight
  3408. status = 0
  3409. } else {
  3410. // continue
  3411. if weight <= 0 {
  3412. continue
  3413. }
  3414. w = weight
  3415. status = 1
  3416. }
  3417. // for _, lppland := range lpplandtl1List {
  3418. // lweight += lppland.Lweight
  3419. // }
  3420. for _, lppland := range lpplandtl1List {
  3421. lpplandInfo := new(lpplandtlInfo)
  3422. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3423. lweight = lpplandInfo.Lweight
  3424. if status == 1 {
  3425. // if w <= lppland.Lweight {
  3426. if lppland.Maxweight <= lweight {
  3427. continue
  3428. }
  3429. if w+lweight <= lppland.Maxweight {
  3430. lppland.Lweight += w
  3431. lweight += w
  3432. fweight += w
  3433. w = 0
  3434. } else {
  3435. w = w - (lppland.Maxweight - lweight)
  3436. n := (lppland.Maxweight - lweight)
  3437. lppland.Lweight = lppland.Lweight + n
  3438. lweight += n
  3439. fweight += n
  3440. }
  3441. } else {
  3442. if lppland.Lweight == 0 {
  3443. continue
  3444. }
  3445. if w+lppland.Lweight >= 0 {
  3446. lppland.Lweight = lppland.Lweight + w
  3447. lweight = lweight + w
  3448. fweight = fweight + w
  3449. w = 0
  3450. } else {
  3451. w = w + lppland.Lweight
  3452. lweight = lweight - lppland.Lweight
  3453. fweight = fweight - lppland.Lweight
  3454. lppland.Lweight = 0
  3455. }
  3456. }
  3457. if lppland.Lweight > 0 {
  3458. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3459. if err != nil {
  3460. tx.Rollback()
  3461. logs.Error(err)
  3462. return
  3463. }
  3464. } else {
  3465. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3466. if err != nil {
  3467. tx.Rollback()
  3468. logs.Error(err)
  3469. return
  3470. }
  3471. }
  3472. if w == 0 {
  3473. break
  3474. }
  3475. // break
  3476. }
  3477. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3478. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3479. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3480. if err != nil {
  3481. tx.Rollback()
  3482. logs.Error(err)
  3483. }
  3484. if w == 0 {
  3485. break
  3486. }
  3487. }
  3488. }
  3489. }
  3490. tx.Commit()
  3491. now := time.Now()
  3492. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3493. if err != nil {
  3494. logs.Error(err)
  3495. appG.Response(http.StatusOK, e.ERROR, false)
  3496. return
  3497. }
  3498. for _, newLpplandtl1 := range newLpplandtl1List {
  3499. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3500. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3501. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3502. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3503. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3504. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3505. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3506. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3507. if err != nil {
  3508. logs.Error(err)
  3509. appG.Response(http.StatusOK, e.ERROR, false)
  3510. return
  3511. }
  3512. }
  3513. appG.Response(http.StatusOK, e.SUCCESS, true)
  3514. }
  3515. func GetProcessAnalysis(c *gin.Context) {
  3516. appG := app.Gin{C: c}
  3517. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3518. fsion := gofasion.NewFasion(string(dataByte))
  3519. sqlnamestr := fsion.Get("name").ValueStr()
  3520. offset := fsion.Get("offset").ValueDefaultInt(0)
  3521. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3522. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3523. parammaps := fsion.Get("parammaps")
  3524. tx := restful.Engine.NewSession()
  3525. err := tx.Begin()
  3526. defer func() {
  3527. switch {
  3528. case err != nil:
  3529. logging.Error("tx.Begin 事务启动失败__error:", err)
  3530. if tx != nil {
  3531. tx.Rollback()
  3532. }
  3533. default:
  3534. if tx != nil {
  3535. err = tx.Commit()
  3536. }
  3537. }
  3538. if tx != nil {
  3539. tx.Close()
  3540. }
  3541. }()
  3542. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3543. s_params := make([]interface{}, 0)
  3544. paramslist := strings.Split(p, ",")
  3545. if len(paramslist) > 0 && p != "" {
  3546. for _, value := range paramslist {
  3547. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3548. if tempv, exists := c.Get("jwt_username"); exists {
  3549. s_params = append(s_params, tempv.(string))
  3550. } else {
  3551. s_params = append(s_params, "")
  3552. }
  3553. } else {
  3554. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3555. }
  3556. }
  3557. }
  3558. tmrtnameStr := ""
  3559. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3560. if len(tmrtnameStr) == 0 {
  3561. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3562. } else {
  3563. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3564. }
  3565. }
  3566. if len(tmrtnameStr) > 0 {
  3567. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3568. }
  3569. sql += " ORDER BY d.intime"
  3570. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3571. if err != nil {
  3572. logging.Error("GetDataByName err: ", err)
  3573. msg := geterrmsg(err.Error())
  3574. appG.Response(http.StatusOK, e.ERROR, msg)
  3575. } else {
  3576. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3577. }
  3578. }
  3579. func UpdateFeedtempletStatus(c *gin.Context) {
  3580. appG := app.Gin{C: c}
  3581. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3582. fsion := gofasion.NewFasion(string(dataByte))
  3583. parammaps := fsion.Get("parammaps")
  3584. tx := restful.Engine.NewSession()
  3585. tx.Begin()
  3586. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3587. if err != nil {
  3588. tx.Rollback()
  3589. logs.Error(err)
  3590. appG.Response(http.StatusOK, e.ERROR, err)
  3591. return
  3592. }
  3593. tx.Commit()
  3594. appG.Response(http.StatusOK, e.SUCCESS, true)
  3595. }
  3596. func AddFtdry(c *gin.Context) {
  3597. appG := app.Gin{C: c}
  3598. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3599. fsion := gofasion.NewFasion(string(dataByte))
  3600. sqlnamestr := fsion.Get("name").ValueStr()
  3601. s_params := make([]interface{}, 0)
  3602. tx := restful.Engine.NewSession()
  3603. err := tx.Begin()
  3604. defer func() {
  3605. switch {
  3606. case err != nil:
  3607. if tx != nil {
  3608. tx.Rollback()
  3609. }
  3610. default:
  3611. if tx != nil {
  3612. err = tx.Commit()
  3613. }
  3614. }
  3615. if tx != nil {
  3616. tx.Close()
  3617. }
  3618. }()
  3619. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3620. if sql != "" {
  3621. parammaps := fsion.Get("parammaps")
  3622. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3623. paramslist := strings.Split(p, ",")
  3624. if len(paramslist) > 0 && p != "" {
  3625. for _, value := range paramslist {
  3626. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3627. if tempv, exists := c.Get("jwt_username"); exists {
  3628. s_params = append(s_params, tempv.(string))
  3629. } else {
  3630. s_params = append(s_params, "")
  3631. }
  3632. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3633. ids, err := setting.SnowIds.NextId()
  3634. if err != nil {
  3635. ids = time.Now().UnixNano()
  3636. logging.Info("create SnowIds err", err)
  3637. }
  3638. s_params = append(s_params, ids)
  3639. } else {
  3640. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3641. }
  3642. }
  3643. }
  3644. var actweight float64
  3645. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3646. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3647. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3648. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3649. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3650. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3651. 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()
  3652. if err != nil {
  3653. logging.Error("AddFtdry err: ", err)
  3654. msg := geterrmsg(err.Error())
  3655. appG.Response(http.StatusOK, e.ERROR, msg)
  3656. }
  3657. if len(actweightList) > 0 {
  3658. for _, item := range actweightList {
  3659. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3660. if err != nil {
  3661. logging.Error("AddFtdry err: ", err)
  3662. msg := geterrmsg(err.Error())
  3663. appG.Response(http.StatusOK, e.ERROR, msg)
  3664. }
  3665. actweight = fl
  3666. }
  3667. } else {
  3668. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3669. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3670. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3671. if err != nil {
  3672. logging.Error("AddFtdry err: ", err)
  3673. msg := geterrmsg(err.Error())
  3674. appG.Response(http.StatusOK, e.ERROR, msg)
  3675. }
  3676. for _, item := range dryList {
  3677. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3678. if err != nil {
  3679. logging.Error("AddFtdry err: ", err)
  3680. msg := geterrmsg(err.Error())
  3681. appG.Response(http.StatusOK, e.ERROR, msg)
  3682. }
  3683. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3684. }
  3685. }
  3686. if sqlnamestr == "insertFtdry" {
  3687. s_params = append(s_params, actweight)
  3688. } else if sqlnamestr == "updateFtdry" {
  3689. sql = fmt.Sprintf(sql, actweight)
  3690. }
  3691. queryData, err := execDataBySqlT(sql, s_params, tx)
  3692. if err != nil {
  3693. logging.Error("AddFtdry err: ", err)
  3694. msg := geterrmsg(err.Error())
  3695. appG.Response(http.StatusOK, e.ERROR, msg)
  3696. } else {
  3697. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3698. }
  3699. } else {
  3700. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3701. }
  3702. }
  3703. func CheckDates(c *gin.Context) {
  3704. tx := restful.Engine.NewSession()
  3705. defer tx.Close()
  3706. appG := app.Gin{C: c}
  3707. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3708. tempval_ := make(map[string]interface{})
  3709. tempCommon := make(map[string]interface{})
  3710. tempval := make([]map[string]interface{}, 0)
  3711. err := json.Unmarshal(dataByte, &tempval_)
  3712. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3713. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3714. if err != nil {
  3715. } else {
  3716. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3717. tempCommon = v
  3718. }
  3719. if v, ok := tempval_["data"].([]interface{}); ok {
  3720. for _, Tvalue := range v {
  3721. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3722. tempval = append(tempval, v1)
  3723. }
  3724. }
  3725. }
  3726. if err == nil {
  3727. if tempv, exists := c.Get("jwt_username"); exists {
  3728. tempCommon["jwt_username"] = tempv.(string)
  3729. }
  3730. for _, paramvalue := range tempval {
  3731. if _, ok := paramvalue["resultname"]; !ok {
  3732. paramvalue["resultname"] = paramvalue["name"]
  3733. }
  3734. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3735. if err != nil {
  3736. logging.Error("ExecDataParam error:", err)
  3737. }
  3738. }
  3739. if err == nil {
  3740. vmsg := ""
  3741. for _, item := range tempval {
  3742. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3743. for _, childrenList := range list.([]interface{}) {
  3744. for k, children := range childrenList.(map[string]interface{}) {
  3745. if k != "children" {
  3746. continue
  3747. }
  3748. for _, v := range children.([]map[string]interface{}) {
  3749. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3750. if k1 == "list" {
  3751. for _, v2 := range v1.([]map[string]interface{}) {
  3752. if v2["vmsg"].(string) != "1" {
  3753. if len(vmsg) == 0 {
  3754. vmsg = v2["vmsg"].(string)
  3755. } else {
  3756. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3757. }
  3758. }
  3759. }
  3760. }
  3761. }
  3762. }
  3763. }
  3764. }
  3765. }
  3766. }
  3767. if len(vmsg) > 0 {
  3768. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3769. } else {
  3770. appG.Response(http.StatusOK, e.SUCCESS, true)
  3771. }
  3772. } else {
  3773. msg := geterrmsg(err.Error())
  3774. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3775. }
  3776. }
  3777. }
  3778. if err != nil {
  3779. msg := geterrmsg(err.Error())
  3780. appG.Response(http.StatusOK, e.ERROR, msg)
  3781. }
  3782. }
  3783. 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) {
  3784. sqlname := fasion["name"].(string)
  3785. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3786. if v, ok := fasion["type"]; ok {
  3787. sqltype = v.(string)
  3788. }
  3789. sql := ""
  3790. p := ""
  3791. s_params := make([]interface{}, 0)
  3792. if sqltype != "" {
  3793. sql, p = restful.GetSqlByName(sqlname, tx)
  3794. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3795. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3796. paramslist := strings.Split(p, ",")
  3797. if len(paramslist) > 0 && p != "" {
  3798. for _, value := range paramslist {
  3799. ss := ""
  3800. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3801. ids, err := setting.SnowIds.NextId()
  3802. if err != nil {
  3803. ids = time.Now().UnixNano()
  3804. logging.Info("create SnowIds err", err)
  3805. }
  3806. s_params = append(s_params, ids)
  3807. } else {
  3808. if ss == "" && CommonParamMap != nil {
  3809. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3810. ss = valuestring
  3811. tempstrb := strings.IndexAny(valuestring, "@")
  3812. tempstre := strings.IndexAny(valuestring, ".")
  3813. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3814. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3815. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3816. }
  3817. } else {
  3818. ss = ""
  3819. }
  3820. }
  3821. }
  3822. if ss == "" && ParentParamMap != nil {
  3823. ss = getParamValue_(v, value, ParentParamMap)
  3824. }
  3825. if ss == "" && sameParamMap != nil {
  3826. ss = getParamValue(v, value, sameParamMap)
  3827. }
  3828. if ss == "" && ParamMap != nil {
  3829. ss = getParamValue(v, value, ParamMap)
  3830. }
  3831. s_params = append(s_params, ss)
  3832. }
  3833. }
  3834. }
  3835. }
  3836. }
  3837. if sql == "" {
  3838. sqltype = ""
  3839. }
  3840. if sql != "" {
  3841. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3842. if err != nil {
  3843. return nil, err
  3844. }
  3845. // fmt.Println(tempValParam)
  3846. return tempValParam.(map[string]interface{}), nil
  3847. } else {
  3848. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3849. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3850. if err != nil {
  3851. return nil, err
  3852. }
  3853. return nil, err
  3854. }
  3855. }
  3856. return nil, nil
  3857. }
  3858. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3859. var err error
  3860. subarray, ok := fasion["children"]
  3861. if ok {
  3862. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3863. tempVal_arrary := make([]map[string]interface{}, 0)
  3864. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3865. tempVal_ := make(map[string]interface{})
  3866. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3867. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3868. } else {
  3869. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3870. }
  3871. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3872. if err != nil {
  3873. return err
  3874. }
  3875. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3876. }
  3877. v.(map[string]interface{})["children"] = tempVal_arrary
  3878. }
  3879. }
  3880. return nil
  3881. }
  3882. func FpdImportExcel(c *gin.Context) {
  3883. appG := app.Gin{C: c}
  3884. inputdata := ""
  3885. c.Request.ParseForm()
  3886. params := c.Request.Form
  3887. file, _, err := c.Request.FormFile("file")
  3888. if err != nil {
  3889. appG.Response(http.StatusOK, e.ERROR, err)
  3890. return
  3891. }
  3892. sqlnamestrs := params.Get("name")
  3893. sheetname := params.Get("sheetname")
  3894. pastureid := params.Get("pastureid")
  3895. // importParams := params.Get("importParams")
  3896. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3897. // 必输项参数 (字符串格式 "field1,field2,field3")
  3898. requiredParams := params.Get("requiredParams")
  3899. // 日期参数
  3900. dateParams := params.Get("dateParams")
  3901. // 数字参数
  3902. numParams := params.Get("numParams")
  3903. //将字符串分割开
  3904. dateParamslist := strings.Split(dateParams, ",")
  3905. requiredParamslist := strings.Split(requiredParams, ",")
  3906. numParamslist := strings.Split(numParams, ",")
  3907. queryData := make([]interface{}, 0)
  3908. sqlslist := strings.Split(sqlnamestrs, ",")
  3909. xlsx1, err := excelize.OpenReader(file)
  3910. if err != nil {
  3911. fmt.Println(err)
  3912. return
  3913. }
  3914. ok := 0
  3915. error := 0
  3916. isdone := true
  3917. tx := restful.Engine.NewSession()
  3918. defer tx.Close()
  3919. languageStatus := GetLanguageStatus()
  3920. if languageStatus == "0" {
  3921. 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
  3922. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3923. if err != nil {
  3924. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3925. return
  3926. }
  3927. rows := xlsx1.GetRows(sheetname)
  3928. // 限制10000条,多余的截取掉
  3929. if len(rows) > 10000 {
  3930. rows = rows[:10000]
  3931. }
  3932. dataList := make(map[string][]*upFpdetail, 0)
  3933. for i, row := range rows {
  3934. if i > 0 {
  3935. entry := make(map[string]interface{})
  3936. outentry := make(map[string]interface{})
  3937. for j, colCell := range rows[0] {
  3938. for k, colCell1 := range row {
  3939. if j == k {
  3940. outentry[colCell] = colCell1
  3941. entry[colCell] = colCell1
  3942. }
  3943. }
  3944. }
  3945. inputdata = ""
  3946. a := ""
  3947. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3948. //校验日期格式
  3949. for _, v := range dateParamslist {
  3950. if v == "" {
  3951. continue
  3952. }
  3953. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3954. dtime, err := TransfTime(d.(string))
  3955. if err != nil {
  3956. a = strings.Trim(v, " ")
  3957. break
  3958. }
  3959. outentry[strings.Trim(v, " ")] = dtime
  3960. }
  3961. }
  3962. if a != "" {
  3963. outentry["error_msg"] = a + " 格式错误"
  3964. error++
  3965. queryData = append(queryData, outentry)
  3966. continue
  3967. }
  3968. a = ""
  3969. //校验必填格式
  3970. for _, v := range requiredParamslist {
  3971. if v == "" {
  3972. continue
  3973. }
  3974. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3975. a = strings.Trim(v, " ")
  3976. break
  3977. }
  3978. }
  3979. if a != "" {
  3980. outentry["error_msg"] = a + " 未填或格式错误"
  3981. error++
  3982. queryData = append(queryData, outentry)
  3983. continue
  3984. }
  3985. a = ""
  3986. //校验数字格式
  3987. for _, v := range numParamslist {
  3988. if v == "" {
  3989. continue
  3990. }
  3991. d, ok := outentry[strings.Trim(v, " ")]
  3992. if !ok || d == "" {
  3993. outentry[strings.Trim(v, " ")] = 0
  3994. } else {
  3995. var fl float64
  3996. switch d.(type) {
  3997. case string:
  3998. fl, err = strconv.ParseFloat(d.(string), 64)
  3999. }
  4000. if err != nil || fl < 0 {
  4001. a = strings.Trim(v, " ")
  4002. break
  4003. }
  4004. }
  4005. }
  4006. if a != "" {
  4007. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  4008. error++
  4009. queryData = append(queryData, outentry)
  4010. continue
  4011. }
  4012. errExist := false
  4013. for _, sqlnamestr := range sqlslist {
  4014. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4015. paramslist := strings.Split(paramslists, ",")
  4016. if len(paramslist) > 0 {
  4017. s_params := make([]interface{}, 0)
  4018. for _, value := range paramslist {
  4019. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4020. if tempv, exists := c.Get("jwt_username"); exists {
  4021. s_params = append(s_params, tempv.(string))
  4022. } else {
  4023. s_params = append(s_params, "")
  4024. }
  4025. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4026. s_params = append(s_params, pastureid)
  4027. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4028. ids, err := setting.SnowIds.NextId()
  4029. if err != nil {
  4030. ids = time.Now().UnixNano()
  4031. logging.Info("create SnowIds err", err)
  4032. }
  4033. s_params = append(s_params, ids)
  4034. } else {
  4035. if outentry[strings.Trim(value, " ")] == nil {
  4036. s_params = append(s_params, "")
  4037. } else {
  4038. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4039. }
  4040. }
  4041. }
  4042. outentry["input"] = inputdata
  4043. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4044. if err != nil {
  4045. errExist = true
  4046. // if tx != nil {
  4047. // tx.Rollback()
  4048. // }
  4049. // if tx != nil {
  4050. // tx.Close()
  4051. // }
  4052. msg := geterrmsg(err.Error())
  4053. outentry["error_msg"] = msg
  4054. error++
  4055. queryData = append(queryData, outentry)
  4056. isdone = true
  4057. break
  4058. } else {
  4059. if len(returnmsgmap1) > 0 {
  4060. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4061. // if tx != nil {
  4062. // tx.Rollback()
  4063. // }
  4064. // if tx != nil {
  4065. // tx.Close()
  4066. // }
  4067. msg := geterrmsg(va.(string))
  4068. outentry["error_msg"] = msg
  4069. error++
  4070. queryData = append(queryData, outentry)
  4071. isdone = true
  4072. break
  4073. }
  4074. }
  4075. isdone = false
  4076. }
  4077. }
  4078. }
  4079. fmt.Println(outentry["栏舍名称"])
  4080. if !errExist {
  4081. dataexcel := make(map[string]interface{}, 0)
  4082. if _, ok := outentry["栏舍名称"]; ok {
  4083. dataexcel["barname"] = outentry["栏舍名称"]
  4084. }
  4085. if _, ok := outentry["实际牛头数"]; ok {
  4086. dataexcel["ccount"] = outentry["实际牛头数"]
  4087. }
  4088. // if _, ok := outentry["实际羊只数"]; ok {
  4089. // dataexcel["ccount"] = outentry["实际羊只数"]
  4090. // }
  4091. if _, ok := outentry["系数(%)"]; ok {
  4092. dataexcel["ratio"] = outentry["系数(%)"]
  4093. }
  4094. if _, ok := outentry["配方模板"]; ok {
  4095. dataexcel["ftname"] = outentry["配方模板"]
  4096. }
  4097. if _, ok := outentry["补料配方"]; ok {
  4098. dataexcel["ptsfname"] = outentry["补料配方"]
  4099. }
  4100. if _, ok := outentry["第一班比例(%)"]; ok {
  4101. dataexcel["1"] = outentry["第一班比例(%)"]
  4102. if fmt.Sprintf("%v", dataexcel["1"]) == "" {
  4103. dataexcel["1"] = 0
  4104. }
  4105. } else {
  4106. dataexcel["1"] = 0
  4107. }
  4108. if _, ok := outentry["第二班比例(%)"]; ok {
  4109. dataexcel["2"] = outentry["第二班比例(%)"]
  4110. if fmt.Sprintf("%v", dataexcel["2"]) == "" {
  4111. dataexcel["2"] = 0
  4112. }
  4113. } else {
  4114. dataexcel["2"] = 0
  4115. }
  4116. if _, ok := outentry["第三班比例(%)"]; ok {
  4117. dataexcel["3"] = outentry["第三班比例(%)"]
  4118. if fmt.Sprintf("%v", dataexcel["3"]) == "" {
  4119. dataexcel["3"] = 0
  4120. }
  4121. } else {
  4122. dataexcel["3"] = 0
  4123. }
  4124. if _, ok := outentry["第四班比例(%)"]; ok {
  4125. dataexcel["4"] = outentry["第四班比例(%)"]
  4126. if fmt.Sprintf("%v", dataexcel["4"]) == "" {
  4127. dataexcel["4"] = 0
  4128. }
  4129. } else {
  4130. dataexcel["4"] = 0
  4131. }
  4132. if _, ok := outentry["第五班比例(%)"]; ok {
  4133. dataexcel["5"] = outentry["第五班比例(%)"]
  4134. if fmt.Sprintf("%v", dataexcel["5"]) == "" {
  4135. dataexcel["5"] = 0
  4136. }
  4137. } else {
  4138. dataexcel["5"] = 0
  4139. }
  4140. if _, ok := outentry["第六班比例(%)"]; ok {
  4141. dataexcel["6"] = outentry["第六班比例(%)"]
  4142. if fmt.Sprintf("%v", dataexcel["6"]) == "" {
  4143. dataexcel["6"] = 0
  4144. }
  4145. } else {
  4146. dataexcel["6"] = 0
  4147. }
  4148. dataWeight := new(models.FpdetailEdit)
  4149. // dataWeightMap := make(map[string]interface{}, 0)
  4150. if _, ok := outentry["第一班重量"]; ok {
  4151. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4152. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4153. }
  4154. if _, ok := outentry["第二班重量"]; ok {
  4155. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4156. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4157. }
  4158. if _, ok := outentry["第三班重量"]; ok {
  4159. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4160. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4161. }
  4162. if _, ok := outentry["第四班重量"]; ok {
  4163. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4164. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4165. }
  4166. if _, ok := outentry["第五班重量"]; ok {
  4167. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4168. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4169. }
  4170. if _, ok := outentry["第六班重量"]; ok {
  4171. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4172. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4173. }
  4174. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4175. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4176. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4177. // fmt.Println(err)
  4178. if fmt.Sprintf("%v", dataexcel["ccount"]) == "0" {
  4179. dataWeight.Weight1 = 0
  4180. dataWeight.Weight2 = 0
  4181. dataWeight.Weight3 = 0
  4182. dataWeight.Weight4 = 0
  4183. dataWeight.Weight5 = 0
  4184. dataWeight.Weight6 = 0
  4185. }
  4186. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4187. if weight > 0 {
  4188. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4189. if err != nil {
  4190. logs.Error(err)
  4191. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4192. return
  4193. }
  4194. if !existbar {
  4195. continue
  4196. }
  4197. _, 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()
  4198. if err != nil {
  4199. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4200. return
  4201. }
  4202. _, 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()
  4203. if err != nil {
  4204. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4205. return
  4206. }
  4207. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4208. if err != nil {
  4209. logs.Error(err)
  4210. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4211. return
  4212. }
  4213. if !existft {
  4214. continue
  4215. }
  4216. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4217. if err != nil {
  4218. logs.Error(err)
  4219. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4220. return
  4221. }
  4222. if !ftexist {
  4223. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4224. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4225. if err != nil {
  4226. logs.Error(err)
  4227. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4228. return
  4229. }
  4230. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4231. if err != nil {
  4232. logs.Error(err)
  4233. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4234. return
  4235. }
  4236. }
  4237. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4238. if err != nil {
  4239. logs.Error(err)
  4240. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4241. return
  4242. }
  4243. if !exist {
  4244. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4245. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4246. if err != nil {
  4247. logs.Error(err)
  4248. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4249. return
  4250. }
  4251. }
  4252. var feedpargs []interface{}
  4253. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4254. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4255. if _, ok := dataexcel["ftname"]; ok {
  4256. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4257. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4258. // upFeedpSql += `,ftweight = ? `
  4259. // feedpargs = append(feedpargs, weight)
  4260. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4261. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4262. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4263. } else {
  4264. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4265. }
  4266. if _, ok := dataexcel["ptsfname"]; ok {
  4267. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4268. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4269. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4270. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4271. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4272. } else {
  4273. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4274. }
  4275. upFeedpSql += " where barname = ? and pastureid = ? "
  4276. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4277. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4278. if err != nil {
  4279. logs.Error(err)
  4280. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4281. return
  4282. }
  4283. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4284. if err != nil {
  4285. logs.Error(err)
  4286. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4287. return
  4288. }
  4289. if !exist1 {
  4290. _, 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) `,
  4291. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4292. if err != nil {
  4293. logs.Error(err)
  4294. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4295. return
  4296. }
  4297. }
  4298. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4299. if err != nil {
  4300. logs.Error(err)
  4301. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4302. return
  4303. }
  4304. if !exist2 {
  4305. _, 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) `,
  4306. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4307. if err != nil {
  4308. logs.Error(err)
  4309. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4310. return
  4311. }
  4312. }
  4313. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4314. if err != nil {
  4315. logs.Error(err)
  4316. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4317. return
  4318. }
  4319. if !exist3 {
  4320. _, 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) `,
  4321. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4322. if err != nil {
  4323. logs.Error(err)
  4324. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4325. return
  4326. }
  4327. }
  4328. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4329. if err != nil {
  4330. logs.Error(err)
  4331. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4332. return
  4333. }
  4334. if !exist4 {
  4335. _, 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) `,
  4336. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4337. if err != nil {
  4338. logs.Error(err)
  4339. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4340. return
  4341. }
  4342. }
  4343. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4344. if err != nil {
  4345. logs.Error(err)
  4346. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4347. return
  4348. }
  4349. if !exist5 {
  4350. _, 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) `,
  4351. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4352. if err != nil {
  4353. logs.Error(err)
  4354. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4355. return
  4356. }
  4357. }
  4358. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4359. if err != nil {
  4360. logs.Error(err)
  4361. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4362. return
  4363. }
  4364. if !exist6 {
  4365. _, 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) `,
  4366. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4367. if err != nil {
  4368. logs.Error(err)
  4369. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4370. return
  4371. }
  4372. }
  4373. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4374. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4375. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4376. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4377. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4378. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4379. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4380. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4381. and pastureid = ? and times = ?`
  4382. var fpdargs1 []interface{}
  4383. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4384. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4385. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4386. if err != nil {
  4387. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4388. return
  4389. }
  4390. var fpdargs2 []interface{}
  4391. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4392. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4393. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4394. if err != nil {
  4395. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4396. return
  4397. }
  4398. var fpdargs3 []interface{}
  4399. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4400. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4401. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4402. if err != nil {
  4403. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4404. return
  4405. }
  4406. var fpdargs4 []interface{}
  4407. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4408. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4409. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4410. if err != nil {
  4411. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4412. return
  4413. }
  4414. var fpdargs5 []interface{}
  4415. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4416. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4417. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4418. if err != nil {
  4419. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4420. return
  4421. }
  4422. var fpdargs6 []interface{}
  4423. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4424. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4425. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4426. if err != nil {
  4427. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4428. return
  4429. }
  4430. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4431. 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()
  4432. if err != nil {
  4433. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4434. return
  4435. }
  4436. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4437. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4438. upFpdetailList := make([]*upFpdetail, 0)
  4439. for _, newfpd := range newList {
  4440. for _, oldfpd := range oldFpdList {
  4441. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4442. var oldweight, newweight float64
  4443. if oldfpd["weight"] != nil {
  4444. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4445. }
  4446. if newfpd["weight"] != nil {
  4447. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4448. }
  4449. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4450. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4451. Old: oldweight,
  4452. New: newweight,
  4453. Times: newfpd["times"].(int64),
  4454. Ptid: newfpd["ptid"].(int64),
  4455. Fweight: fweight,
  4456. Id: oldfpd["id"].(int64),
  4457. })
  4458. break
  4459. }
  4460. }
  4461. }
  4462. // fmt.Println(dataexcel["barname"])
  4463. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4464. } else {
  4465. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4466. if err != nil {
  4467. logs.Error(err)
  4468. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4469. return
  4470. }
  4471. if !existbar {
  4472. continue
  4473. }
  4474. _, 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()
  4475. if err != nil {
  4476. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4477. return
  4478. }
  4479. _, 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()
  4480. if err != nil {
  4481. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4482. return
  4483. }
  4484. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4485. if err != nil {
  4486. logs.Error(err)
  4487. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4488. return
  4489. }
  4490. if !existft {
  4491. continue
  4492. }
  4493. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4494. if err != nil {
  4495. logs.Error(err)
  4496. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4497. return
  4498. }
  4499. if !ftexist {
  4500. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4501. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4502. if err != nil {
  4503. logs.Error(err)
  4504. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4505. return
  4506. }
  4507. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4508. if err != nil {
  4509. logs.Error(err)
  4510. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4511. return
  4512. }
  4513. }
  4514. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4515. if err != nil {
  4516. logs.Error(err)
  4517. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4518. return
  4519. }
  4520. if !exist {
  4521. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4522. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4523. if err != nil {
  4524. logs.Error(err)
  4525. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4526. return
  4527. }
  4528. }
  4529. var feedpargs []interface{}
  4530. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4531. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4532. if _, ok := dataexcel["ftname"]; ok {
  4533. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4534. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4535. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4536. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4537. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4538. } else {
  4539. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4540. }
  4541. if _, ok := dataexcel["ptsfname"]; ok {
  4542. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4543. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4544. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4545. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4546. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4547. } else {
  4548. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4549. }
  4550. upFeedpSql += " where barname = ? and pastureid = ? "
  4551. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4552. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4553. if err != nil {
  4554. logs.Error(err)
  4555. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4556. return
  4557. }
  4558. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4559. if err != nil {
  4560. logs.Error(err)
  4561. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4562. return
  4563. }
  4564. if !exist1 {
  4565. _, 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) `,
  4566. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4567. if err != nil {
  4568. logs.Error(err)
  4569. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4570. return
  4571. }
  4572. }
  4573. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4574. if err != nil {
  4575. logs.Error(err)
  4576. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4577. return
  4578. }
  4579. if !exist2 {
  4580. _, 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) `,
  4581. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4582. if err != nil {
  4583. logs.Error(err)
  4584. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4585. return
  4586. }
  4587. }
  4588. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4589. if err != nil {
  4590. logs.Error(err)
  4591. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4592. return
  4593. }
  4594. if !exist3 {
  4595. _, 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) `,
  4596. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4597. if err != nil {
  4598. logs.Error(err)
  4599. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4600. return
  4601. }
  4602. }
  4603. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4604. if err != nil {
  4605. logs.Error(err)
  4606. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4607. return
  4608. }
  4609. if !exist4 {
  4610. _, 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) `,
  4611. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4612. if err != nil {
  4613. logs.Error(err)
  4614. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4615. return
  4616. }
  4617. }
  4618. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4619. if err != nil {
  4620. logs.Error(err)
  4621. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4622. return
  4623. }
  4624. if !exist5 {
  4625. _, 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) `,
  4626. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4627. if err != nil {
  4628. logs.Error(err)
  4629. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4630. return
  4631. }
  4632. }
  4633. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4634. if err != nil {
  4635. logs.Error(err)
  4636. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4637. return
  4638. }
  4639. if !exist6 {
  4640. _, 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) `,
  4641. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4642. if err != nil {
  4643. logs.Error(err)
  4644. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4645. return
  4646. }
  4647. }
  4648. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4649. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4650. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4651. and pastureid = ? and times = ?`
  4652. var fpdargs1 []interface{}
  4653. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4654. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4655. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4656. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4657. if err != nil {
  4658. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4659. return
  4660. }
  4661. var fpdargs2 []interface{}
  4662. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4663. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4664. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4665. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4666. if err != nil {
  4667. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4668. return
  4669. }
  4670. var fpdargs3 []interface{}
  4671. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4672. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4673. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4674. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4675. if err != nil {
  4676. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4677. return
  4678. }
  4679. var fpdargs4 []interface{}
  4680. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4681. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4682. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4683. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4684. if err != nil {
  4685. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4686. return
  4687. }
  4688. var fpdargs5 []interface{}
  4689. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4690. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4691. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4692. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4693. if err != nil {
  4694. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4695. return
  4696. }
  4697. var fpdargs6 []interface{}
  4698. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4699. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4700. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4701. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4702. if err != nil {
  4703. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4704. return
  4705. }
  4706. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4707. 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()
  4708. if err != nil {
  4709. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4710. return
  4711. }
  4712. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4713. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4714. upFpdetailList := make([]*upFpdetail, 0)
  4715. for _, newfpd := range newList {
  4716. for _, oldfpd := range oldFpdList {
  4717. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4718. var oldweight, newweight float64
  4719. if oldfpd["weight"] != nil {
  4720. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4721. }
  4722. if newfpd["weight"] != nil {
  4723. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4724. }
  4725. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4726. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4727. Old: oldweight,
  4728. New: newweight,
  4729. Times: newfpd["times"].(int64),
  4730. Ptid: newfpd["ptid"].(int64),
  4731. Fweight: fweight,
  4732. Id: oldfpd["id"].(int64),
  4733. })
  4734. break
  4735. }
  4736. }
  4737. }
  4738. // fmt.Println(dataexcel["barname"])
  4739. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4740. }
  4741. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4742. }
  4743. }
  4744. if !isdone {
  4745. ok++
  4746. isdone = true
  4747. }
  4748. }
  4749. for barname, v := range dataList {
  4750. // for _, v1 := range v {
  4751. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4752. // and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4753. // if count == 1 {
  4754. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4755. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4756. // if err != nil {
  4757. // logs.Error(err)
  4758. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4759. // return
  4760. // }
  4761. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4762. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4763. // if err != nil {
  4764. // logs.Error(err)
  4765. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4766. // return
  4767. // }
  4768. // }
  4769. // }
  4770. updateFpdetailByBar(pastureid, barname, v)
  4771. }
  4772. } else {
  4773. 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
  4774. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4775. if err != nil {
  4776. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4777. return
  4778. }
  4779. rows := xlsx1.GetRows(sheetname)
  4780. // 限制10000条,多余的截取掉
  4781. if len(rows) > 10000 {
  4782. rows = rows[:10000]
  4783. }
  4784. dataList := make(map[string][]*upFpdetail, 0)
  4785. for i, row := range rows {
  4786. if i > 0 {
  4787. entry := make(map[string]interface{})
  4788. outentry := make(map[string]interface{})
  4789. for j, colCell := range rows[0] {
  4790. for k, colCell1 := range row {
  4791. if j == k {
  4792. outentry[colCell] = colCell1
  4793. entry[colCell] = colCell1
  4794. }
  4795. }
  4796. }
  4797. inputdata = ""
  4798. a := ""
  4799. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4800. //校验日期格式
  4801. for _, v := range dateParamslist {
  4802. if v == "" {
  4803. continue
  4804. }
  4805. if d, ok := outentry[v]; ok {
  4806. dtime, err := TransfTime(d.(string))
  4807. if err != nil {
  4808. a = v
  4809. break
  4810. }
  4811. outentry[v] = dtime
  4812. }
  4813. }
  4814. if a != "" {
  4815. outentry["error_msg"] = a + " format error"
  4816. error++
  4817. queryData = append(queryData, outentry)
  4818. continue
  4819. }
  4820. a = ""
  4821. //校验必填格式
  4822. for _, v := range requiredParamslist {
  4823. if v == "" {
  4824. continue
  4825. }
  4826. if d, ok := outentry[v]; !ok || d == "" {
  4827. a = v
  4828. break
  4829. }
  4830. }
  4831. if a != "" {
  4832. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4833. error++
  4834. queryData = append(queryData, outentry)
  4835. continue
  4836. }
  4837. a = ""
  4838. //校验数字格式
  4839. for _, v := range numParamslist {
  4840. if v == "" {
  4841. continue
  4842. }
  4843. d, ok := outentry[v]
  4844. if !ok || d == "" {
  4845. outentry[v] = 0
  4846. } else {
  4847. var fl float64
  4848. switch d.(type) {
  4849. case string:
  4850. fl, err = strconv.ParseFloat(d.(string), 64)
  4851. }
  4852. if err != nil || fl < 0 {
  4853. a = v
  4854. break
  4855. }
  4856. }
  4857. }
  4858. if a != "" {
  4859. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4860. error++
  4861. queryData = append(queryData, outentry)
  4862. continue
  4863. }
  4864. errExist := false
  4865. for _, sqlnamestr := range sqlslist {
  4866. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4867. paramslist := strings.Split(paramslists, ",")
  4868. if len(paramslist) > 0 {
  4869. s_params := make([]interface{}, 0)
  4870. for _, value := range paramslist {
  4871. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4872. if tempv, exists := c.Get("jwt_username"); exists {
  4873. s_params = append(s_params, tempv.(string))
  4874. } else {
  4875. s_params = append(s_params, "")
  4876. }
  4877. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4878. s_params = append(s_params, pastureid)
  4879. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4880. ids, err := setting.SnowIds.NextId()
  4881. if err != nil {
  4882. ids = time.Now().UnixNano()
  4883. logging.Info("create SnowIds err", err)
  4884. }
  4885. s_params = append(s_params, ids)
  4886. } else {
  4887. if outentry[strings.Trim(value, " ")] == nil {
  4888. s_params = append(s_params, "")
  4889. } else {
  4890. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4891. }
  4892. }
  4893. }
  4894. outentry["input"] = inputdata
  4895. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4896. if err != nil {
  4897. errExist = true
  4898. // if tx != nil {
  4899. // tx.Rollback()
  4900. // }
  4901. // if tx != nil {
  4902. // tx.Close()
  4903. // }
  4904. msg := geterrmsg(err.Error())
  4905. outentry["error_msg"] = msg
  4906. error++
  4907. queryData = append(queryData, outentry)
  4908. isdone = true
  4909. break
  4910. } else {
  4911. if len(returnmsgmap1) > 0 {
  4912. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4913. // if tx != nil {
  4914. // tx.Rollback()
  4915. // }
  4916. // if tx != nil {
  4917. // tx.Close()
  4918. // }
  4919. msg := geterrmsg(va.(string))
  4920. outentry["error_msg"] = msg
  4921. error++
  4922. queryData = append(queryData, outentry)
  4923. isdone = true
  4924. break
  4925. }
  4926. }
  4927. isdone = false
  4928. }
  4929. }
  4930. }
  4931. if !errExist {
  4932. dataexcel := make(map[string]interface{}, 0)
  4933. if _, ok := outentry["Pen Name"]; ok {
  4934. dataexcel["barname"] = outentry["Pen Name"]
  4935. }
  4936. if _, ok := outentry["Actual Cattle Number"]; ok {
  4937. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4938. }
  4939. if _, ok := outentry["Coefficient(%)"]; ok {
  4940. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4941. }
  4942. if _, ok := outentry["Formula Template"]; ok {
  4943. dataexcel["ftname"] = outentry["Formula Template"]
  4944. }
  4945. if _, ok := outentry["Supplement Formula"]; ok {
  4946. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4947. }
  4948. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4949. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4950. }
  4951. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4952. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4953. }
  4954. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4955. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4956. }
  4957. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4958. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4959. }
  4960. if _, ok := outentry["Fifth Shift Ratio(%)"]; ok {
  4961. dataexcel["5"] = outentry["Fifth Shift Ratio(%)"]
  4962. }
  4963. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4964. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4965. }
  4966. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4967. if err != nil {
  4968. logs.Error(err)
  4969. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4970. return
  4971. }
  4972. if !existbar {
  4973. continue
  4974. }
  4975. _, 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()
  4976. if err != nil {
  4977. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4978. return
  4979. }
  4980. _, 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()
  4981. if err != nil {
  4982. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4983. return
  4984. }
  4985. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4986. if err != nil {
  4987. logs.Error(err)
  4988. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  4989. return
  4990. }
  4991. if !existft {
  4992. continue
  4993. }
  4994. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4995. if err != nil {
  4996. logs.Error(err)
  4997. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4998. return
  4999. }
  5000. if !ftexist {
  5001. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  5002. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5003. if err != nil {
  5004. logs.Error(err)
  5005. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5006. return
  5007. }
  5008. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5009. if err != nil {
  5010. logs.Error(err)
  5011. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5012. return
  5013. }
  5014. }
  5015. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5016. if err != nil {
  5017. logs.Error(err)
  5018. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5019. return
  5020. }
  5021. if !exist {
  5022. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  5023. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  5024. if err != nil {
  5025. logs.Error(err)
  5026. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5027. return
  5028. }
  5029. }
  5030. var feedpargs []interface{}
  5031. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  5032. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  5033. if _, ok := dataexcel["ftname"]; ok {
  5034. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  5035. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  5036. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  5037. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  5038. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5039. } else {
  5040. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  5041. }
  5042. if _, ok := dataexcel["ptsfname"]; ok {
  5043. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  5044. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  5045. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  5046. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  5047. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5048. } else {
  5049. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  5050. }
  5051. upFeedpSql += " where barname = ? and pastureid = ? "
  5052. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  5053. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  5054. if err != nil {
  5055. logs.Error(err)
  5056. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5057. return
  5058. }
  5059. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  5060. if err != nil {
  5061. logs.Error(err)
  5062. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5063. return
  5064. }
  5065. if !exist1 {
  5066. _, 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) `,
  5067. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5068. if err != nil {
  5069. logs.Error(err)
  5070. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5071. return
  5072. }
  5073. }
  5074. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5075. if err != nil {
  5076. logs.Error(err)
  5077. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5078. return
  5079. }
  5080. if !exist2 {
  5081. _, 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) `,
  5082. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5083. if err != nil {
  5084. logs.Error(err)
  5085. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5086. return
  5087. }
  5088. }
  5089. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5090. if err != nil {
  5091. logs.Error(err)
  5092. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5093. return
  5094. }
  5095. if !exist3 {
  5096. _, 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) `,
  5097. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5098. if err != nil {
  5099. logs.Error(err)
  5100. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5101. return
  5102. }
  5103. }
  5104. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5105. if err != nil {
  5106. logs.Error(err)
  5107. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5108. return
  5109. }
  5110. if !exist4 {
  5111. _, 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) `,
  5112. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5113. if err != nil {
  5114. logs.Error(err)
  5115. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5116. return
  5117. }
  5118. }
  5119. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5120. if err != nil {
  5121. logs.Error(err)
  5122. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5123. return
  5124. }
  5125. if !exist5 {
  5126. _, 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) `,
  5127. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5128. if err != nil {
  5129. logs.Error(err)
  5130. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5131. return
  5132. }
  5133. }
  5134. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5135. if err != nil {
  5136. logs.Error(err)
  5137. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5138. return
  5139. }
  5140. if !exist6 {
  5141. _, 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) `,
  5142. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5143. if err != nil {
  5144. logs.Error(err)
  5145. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5146. return
  5147. }
  5148. }
  5149. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5150. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5151. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5152. and pastureid = ? and times = ?`
  5153. var fpdargs1 []interface{}
  5154. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5155. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5156. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5157. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5158. if err != nil {
  5159. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5160. return
  5161. }
  5162. var fpdargs2 []interface{}
  5163. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5164. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5165. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5166. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5167. if err != nil {
  5168. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5169. return
  5170. }
  5171. var fpdargs3 []interface{}
  5172. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5173. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5174. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5175. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5176. if err != nil {
  5177. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5178. return
  5179. }
  5180. var fpdargs4 []interface{}
  5181. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5182. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5183. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5184. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5185. if err != nil {
  5186. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5187. return
  5188. }
  5189. var fpdargs5 []interface{}
  5190. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5191. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5192. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5193. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5194. if err != nil {
  5195. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5196. return
  5197. }
  5198. var fpdargs6 []interface{}
  5199. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5200. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5201. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5202. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5203. if err != nil {
  5204. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5205. return
  5206. }
  5207. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5208. 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()
  5209. if err != nil {
  5210. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5211. return
  5212. }
  5213. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5214. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5215. upFpdetailList := make([]*upFpdetail, 0)
  5216. for _, newfpd := range newList {
  5217. for _, oldfpd := range oldFpdList {
  5218. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5219. var oldweight, newweight float64
  5220. if oldfpd["weight"] != nil {
  5221. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5222. }
  5223. if newfpd["weight"] != nil {
  5224. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5225. }
  5226. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5227. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5228. Old: oldweight,
  5229. New: newweight,
  5230. Times: newfpd["times"].(int64),
  5231. Ptid: newfpd["ptid"].(int64),
  5232. Fweight: fweight,
  5233. Id: oldfpd["id"].(int64),
  5234. })
  5235. break
  5236. }
  5237. }
  5238. }
  5239. // fmt.Println(dataexcel["barname"])
  5240. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5241. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5242. }
  5243. }
  5244. if !isdone {
  5245. ok++
  5246. isdone = true
  5247. }
  5248. }
  5249. for barname, v := range dataList {
  5250. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5251. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5252. if err != nil {
  5253. logs.Error(err)
  5254. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5255. return
  5256. }
  5257. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5258. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5259. if err != nil {
  5260. logs.Error(err)
  5261. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5262. return
  5263. }
  5264. updateFpdetailByBar(pastureid, barname, v)
  5265. }
  5266. }
  5267. data := make(map[string]interface{})
  5268. data["result"] = queryData
  5269. data["success"] = ok
  5270. data["err_count"] = error
  5271. appG.Response(http.StatusOK, e.SUCCESS, data)
  5272. }
  5273. type upFpdetail struct {
  5274. Old float64
  5275. New float64
  5276. Times int64
  5277. Ptid int64
  5278. Fweight float64
  5279. Id int64
  5280. // Ptsid string
  5281. }
  5282. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5283. tx := restful.Engine.NewSession()
  5284. defer tx.Close()
  5285. tx.Begin()
  5286. 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 `,
  5287. pastureid, barname).Query().List()
  5288. if err != nil {
  5289. logs.Error(err)
  5290. }
  5291. for _, fpd := range fpdList {
  5292. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5293. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5294. pastureid, fpd["id"], fpd["times"]).Query().List()
  5295. if err != nil {
  5296. tx.Rollback()
  5297. logs.Error(err)
  5298. return err
  5299. }
  5300. var lweight float64
  5301. for _, lppland := range lpplandList {
  5302. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5303. lweight += lweight1
  5304. }
  5305. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5306. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5307. if fpdweight >= ptuse && lweight == ptuse {
  5308. continue
  5309. } else {
  5310. if lweight <= fpdweight {
  5311. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5312. if err != nil {
  5313. tx.Rollback()
  5314. logs.Error(err)
  5315. return err
  5316. }
  5317. } else {
  5318. weight := lweight - fpdweight
  5319. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5320. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5321. if err != nil {
  5322. tx.Rollback()
  5323. logs.Error(err)
  5324. return err
  5325. }
  5326. for _, lppland := range lpplandList {
  5327. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5328. if weight >= lpplandlweight {
  5329. weight = weight - lpplandlweight
  5330. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5331. if err != nil {
  5332. tx.Rollback()
  5333. logs.Error(err)
  5334. return err
  5335. }
  5336. } else {
  5337. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5338. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5339. if err != nil {
  5340. tx.Rollback()
  5341. logs.Error(err)
  5342. return err
  5343. }
  5344. weight = 0
  5345. break
  5346. }
  5347. }
  5348. }
  5349. }
  5350. }
  5351. for _, list := range dataList {
  5352. ftmap := make(map[string]interface{})
  5353. ftmap["old"] = list.Old
  5354. ftmap["new"] = list.New
  5355. ftmap["times"] = list.Times
  5356. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5357. ftmap["ptsid"] = ""
  5358. // fmt.Println(ftmap)
  5359. // 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 ,
  5360. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5361. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5362. // UNION
  5363. fpdDataList, err := tx.SQL(`
  5364. 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 ,
  5365. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5366. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5367. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5368. if err != nil {
  5369. tx.Rollback()
  5370. logs.Error(err)
  5371. }
  5372. for _, fpd := range fpdDataList {
  5373. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5374. // fttype := -1
  5375. // if fpd["fttype"].(string) == "1" {
  5376. fttype := 1
  5377. // }
  5378. var fweight float64
  5379. var lweight float64
  5380. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5381. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  5382. t.maxstirfeed,t.volume * (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  5383. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5384. join tmr t on t.id = lpp.tmrid
  5385. where lppland.fpdid =?
  5386. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5387. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5388. if err != nil {
  5389. tx.Rollback()
  5390. logs.Error(err)
  5391. }
  5392. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5393. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5394. // 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
  5395. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5396. var w float64
  5397. var status int
  5398. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5399. if weight >= 0 {
  5400. continue
  5401. }
  5402. w = weight
  5403. status = 0
  5404. } else {
  5405. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5406. // continue
  5407. // }
  5408. w = weight
  5409. status = 1
  5410. }
  5411. // for _, lppland := range lpplandtl1List {
  5412. // lweight += lppland.Lweight
  5413. // }
  5414. for _, lppland := range lpplandtl1List {
  5415. lpplandInfo := new(lpplandtlInfo)
  5416. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5417. lweight = lpplandInfo.Lweight
  5418. if status == 1 {
  5419. // if w <= lppland.Lweight {
  5420. if lppland.Maxweight <= lweight {
  5421. continue
  5422. }
  5423. if w+lweight <= lppland.Maxweight {
  5424. lppland.Lweight += w
  5425. lweight += w
  5426. fweight += w
  5427. w = 0
  5428. } else {
  5429. w = w - (lppland.Maxweight - lweight)
  5430. n := (lppland.Maxweight - lweight)
  5431. lppland.Lweight = lppland.Lweight + n
  5432. lweight += n
  5433. fweight += n
  5434. }
  5435. } else {
  5436. if lppland.Lweight == 0 {
  5437. continue
  5438. }
  5439. if w+lppland.Lweight >= 0 {
  5440. lppland.Lweight = lppland.Lweight + w
  5441. lweight = lweight + w
  5442. fweight = fweight + w
  5443. w = 0
  5444. } else {
  5445. w = w + lppland.Lweight
  5446. lweight = lweight - lppland.Lweight
  5447. fweight = fweight - lppland.Lweight
  5448. lppland.Lweight = 0
  5449. }
  5450. }
  5451. if lppland.Lweight > 0 {
  5452. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5453. if err != nil {
  5454. tx.Rollback()
  5455. logs.Error(err)
  5456. return err
  5457. }
  5458. } else {
  5459. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5460. if err != nil {
  5461. tx.Rollback()
  5462. logs.Error(err)
  5463. return err
  5464. }
  5465. }
  5466. if w == 0 {
  5467. break
  5468. }
  5469. }
  5470. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5471. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5472. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5473. if err != nil {
  5474. tx.Rollback()
  5475. logs.Error(err)
  5476. }
  5477. if w == 0 {
  5478. break
  5479. }
  5480. }
  5481. }
  5482. }
  5483. err = tx.Commit()
  5484. if err != nil {
  5485. logs.Error(err)
  5486. tx.Rollback()
  5487. return err
  5488. }
  5489. now := time.Now()
  5490. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5491. if err != nil {
  5492. logs.Error(err)
  5493. return nil
  5494. }
  5495. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5496. if err != nil {
  5497. logs.Error(err)
  5498. return nil
  5499. }
  5500. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5501. if err != nil {
  5502. logs.Error(err)
  5503. return nil
  5504. }
  5505. for _, newLpplandtl1 := range newLpplandtl1List {
  5506. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5507. background,cowcount,ccountradio,lweighthis,createdate)
  5508. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5509. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5510. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5511. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5512. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5513. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5514. if err != nil {
  5515. logs.Error(err)
  5516. // appG.Response(http.StatusOK, e.ERROR, false)
  5517. return err
  5518. }
  5519. }
  5520. for _, newFpd := range newFpdDataList {
  5521. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5522. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5523. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5524. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5525. if err != nil {
  5526. logs.Error(err)
  5527. // appG.Response(http.StatusOK, e.ERROR, false)
  5528. return err
  5529. }
  5530. }
  5531. for _, newFeedp := range newFeedpList {
  5532. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5533. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5534. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5535. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5536. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5537. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5538. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5539. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5540. if err != nil {
  5541. logs.Error(err)
  5542. // appG.Response(http.StatusOK, e.ERROR, false)
  5543. return err
  5544. }
  5545. }
  5546. return nil
  5547. }
  5548. func DeleteFTdetail(c *gin.Context) {
  5549. appG := app.Gin{C: c}
  5550. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5551. fsion := gofasion.NewFasion(string(dataByte))
  5552. parammaps := fsion.Get("parammaps")
  5553. pastureid := parammaps.Get("pastureid").ValueStr()
  5554. ftid := parammaps.Get("ftid").ValueStr()
  5555. tx := restful.Engine.NewSession()
  5556. defer tx.Close()
  5557. tx.Begin()
  5558. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5559. if err != nil {
  5560. tx.Rollback()
  5561. logs.Error(err)
  5562. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5563. return
  5564. }
  5565. if parammaps.Get("type").ValueStr() == "1" {
  5566. _, err := tx.SQL(`UPDATE feedp fp
  5567. set
  5568. fp.ftweight= IFNULL(IF(
  5569. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5570. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5571. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5572. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5573. ),0),fp.feedweight = IFNULL(IF(
  5574. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5575. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5576. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5577. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5578. ),0) +ifnull(fp.supplyweight,0)
  5579. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5580. if err != nil {
  5581. tx.Rollback()
  5582. logs.Error(err)
  5583. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5584. return
  5585. }
  5586. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5587. _, err = tx.SQL(`
  5588. UPDATE fpdetail fpd
  5589. INNER JOIN feedp fp
  5590. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5591. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5592. ptuse= 0
  5593. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5594. if err != nil {
  5595. tx.Rollback()
  5596. logs.Error(err)
  5597. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5598. return
  5599. }
  5600. } else {
  5601. _, err := tx.SQL(`UPDATE feedp fp
  5602. SET
  5603. fp.supplyweight= IFNULL(IF(
  5604. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5605. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5606. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5607. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5608. ),0),fp.feedweight = IFNULL(IF(
  5609. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5610. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5611. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5612. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5613. ),0) + ifnull(fp.supplyweight,0)
  5614. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5615. if err != nil {
  5616. tx.Rollback()
  5617. logs.Error(err)
  5618. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5619. return
  5620. }
  5621. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5622. _, err = tx.SQL(`
  5623. UPDATE fpdetail fpd
  5624. INNER JOIN feedp fp
  5625. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5626. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5627. ptsrate = 0
  5628. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5629. if err != nil {
  5630. tx.Rollback()
  5631. logs.Error(err)
  5632. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5633. return
  5634. }
  5635. }
  5636. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5637. if err != nil {
  5638. tx.Rollback()
  5639. logs.Error(err)
  5640. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5641. return
  5642. }
  5643. err = tx.Commit()
  5644. if err != nil {
  5645. tx.Rollback()
  5646. logs.Error(err)
  5647. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5648. return
  5649. }
  5650. appG.Response(http.StatusOK, e.SUCCESS, true)
  5651. }
  5652. func DeleteSpillageAll(c *gin.Context) {
  5653. appG := app.Gin{C: c}
  5654. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5655. fsion := gofasion.NewFasion(string(dataByte))
  5656. parammaps := fsion.Get("parammaps")
  5657. pastureid := parammaps.Get("pastureid").ValueStr()
  5658. times := parammaps.Get("times").ValueStr()
  5659. barid := parammaps.Get("barid").ValueStr()
  5660. tx := restful.Engine.NewSession()
  5661. defer tx.Close()
  5662. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5663. if err != nil {
  5664. logs.Error(err)
  5665. appG.Response(http.StatusOK, e.ERROR, false)
  5666. return
  5667. }
  5668. now := time.Now()
  5669. for _, item := range lpplandtl1List {
  5670. go func(item map[string]interface{}) {
  5671. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5672. background,cowcount,ccountradio,lweighthis,createdate)
  5673. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5674. item["pastureid"], item["lppid"], item["barid"],
  5675. item["barname"], item["fpdid"], item["fttype"],
  5676. item["lweight"], item["sort"], item["tmrid"],
  5677. item["tmrname"], item["background"], item["cowcount"],
  5678. item["ccountradio"], item["lweighthis"], now).Execute()
  5679. if err != nil {
  5680. logs.Error(err)
  5681. appG.Response(http.StatusOK, e.ERROR, false)
  5682. return
  5683. }
  5684. }(item)
  5685. }
  5686. tx.Begin()
  5687. _, 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()
  5688. if err != nil {
  5689. tx.Rollback()
  5690. logs.Error(err)
  5691. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5692. return
  5693. }
  5694. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5695. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5696. if err != nil {
  5697. tx.Rollback()
  5698. logs.Error(err)
  5699. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5700. return
  5701. }
  5702. err = tx.Commit()
  5703. if err != nil {
  5704. tx.Rollback()
  5705. logs.Error(err)
  5706. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5707. return
  5708. }
  5709. appG.Response(http.StatusOK, e.SUCCESS, true)
  5710. }
  5711. func GetTMRListEnableTypeAll(c *gin.Context) {
  5712. appG := app.Gin{C: c}
  5713. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5714. fsion := gofasion.NewFasion(string(dataByte))
  5715. parammaps := fsion.Get("parammaps")
  5716. pastureid := parammaps.Get("pastureid").ValueStr()
  5717. tx := restful.Engine.NewSession()
  5718. defer tx.Close()
  5719. dataList, err := tx.SQL(`SELECT
  5720. eqcode,
  5721. tname,
  5722. datacaptureno,
  5723. trim(tclassid) tclassid,
  5724. concat(tname,' / ',eqcode) tmrmix,
  5725. d.label tclassname,
  5726. maxstirfeed,
  5727. remark,
  5728. tmr.enable,
  5729. TRIM(tmr.id) id,
  5730. TRIM(tmr.pastureid)pastureid
  5731. FROM
  5732. tmr
  5733. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5734. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5735. ORDER BY id DESC`, pastureid).Query().List()
  5736. if err != nil {
  5737. logs.Error(err)
  5738. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5739. return
  5740. }
  5741. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5742. if err != nil {
  5743. logs.Error(err)
  5744. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5745. return
  5746. }
  5747. var carNum int64
  5748. for _, sysopt := range sysoptData {
  5749. if sysopt["inforvalue"] == nil {
  5750. carNum = 1
  5751. } else {
  5752. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5753. }
  5754. }
  5755. id := 200
  5756. n := 0
  5757. for i := carNum; i > 0; i-- {
  5758. id++
  5759. n++
  5760. data := make(map[string]interface{}, 0)
  5761. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5762. data["tname"] = fmt.Sprintf("任意车%d", n)
  5763. data["datacaptureno"] = -2
  5764. data["tclassid"] = -2
  5765. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5766. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5767. data["maxstirfeed"] = 100000
  5768. data["remark"] = fmt.Sprintf("任意车%d", n)
  5769. data["enable"] = 1
  5770. data["id"] = fmt.Sprintf("%d", id)
  5771. data["pastureid"] = pastureid
  5772. // data := make(map[string]interface{}, 0)
  5773. // data["eqcode"] = fmt.Sprintf("AnyCar%d", n)
  5774. // data["tname"] = fmt.Sprintf("AnyCar%d", n)
  5775. // data["datacaptureno"] = -2
  5776. // data["tclassid"] = -2
  5777. // data["tmrmix"] = fmt.Sprintf("AnyCar%d", n)
  5778. // data["tclassname"] = fmt.Sprintf("AnyCar%d", n)
  5779. // data["maxstirfeed"] = 100000
  5780. // data["remark"] = fmt.Sprintf("AnyCar%d", n)
  5781. // data["enable"] = 1
  5782. // data["id"] = fmt.Sprintf("%d", id)
  5783. // data["pastureid"] = pastureid
  5784. dataList = append(dataList, data)
  5785. }
  5786. // UNION ALL
  5787. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5788. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5789. }
  5790. func GetFeedpHistory(c *gin.Context) {
  5791. appG := app.Gin{C: c}
  5792. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5793. fsion := gofasion.NewFasion(string(dataByte))
  5794. // parammaps := fsion.Get("parammaps")
  5795. bar := fsion.Get("barname").ValueStr()
  5796. startDate := fsion.Get("startDate").ValueStr()
  5797. endDate := fsion.Get("endDate").ValueStr()
  5798. tx := restful.Engine.NewSession()
  5799. defer tx.Close()
  5800. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5801. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5802. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5803. if err != nil {
  5804. logs.Error(err)
  5805. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5806. return
  5807. }
  5808. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5809. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5810. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5811. if err != nil {
  5812. logs.Error(err)
  5813. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5814. return
  5815. }
  5816. for _, feedp := range feedpList {
  5817. // LastftList, err := tx.SQL(` select tname ,id
  5818. // from feedtemplethistory where id = ?
  5819. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5820. // if err != nil {
  5821. // logs.Error(err)
  5822. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5823. // return
  5824. // }
  5825. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5826. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5827. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5828. if err != nil {
  5829. logs.Error(err)
  5830. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5831. return
  5832. }
  5833. var ftname interface{}
  5834. ftnamestatus := 0
  5835. ftname = feedp["ftname"]
  5836. var lastftid int64
  5837. if len(nextfeedpList) > 0 {
  5838. for _, ft := range nextfeedpList {
  5839. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5840. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5841. lastftid = ft["ftid"].(int64)
  5842. ftnamestatus = 1
  5843. break
  5844. }
  5845. }
  5846. }
  5847. for i, fpd := range fpdList {
  5848. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5849. fpd["weightstatus"] = 0
  5850. fpd["tratiostatus"] = 0
  5851. fpd["ftnamestatus"] = ftnamestatus
  5852. for k, fpd2 := range fpdList {
  5853. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5854. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5855. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5856. fpd["weightstatus"] = 1
  5857. }
  5858. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5859. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5860. fpd["tratiostatus"] = 1
  5861. }
  5862. break
  5863. }
  5864. }
  5865. fpd["barid"] = feedp["barid"]
  5866. fpd["barname"] = feedp["barname"]
  5867. fpd["ccount"] = feedp["ccount"]
  5868. fpd["ratio"] = feedp["ratio"]
  5869. fpd["ccountratio"] = feedp["ccountratio"]
  5870. fpd["ftid"] = feedp["ftid"]
  5871. fpd["ftname"] = ftname
  5872. fpd["ccountstatus"] = 0
  5873. fpd["ccountratiostatus"] = 0
  5874. fpd["ratiostatus"] = 0
  5875. fpd["ftnamestatus"] = 0
  5876. fpd["lastftid"] = lastftid
  5877. for _, next := range nextfeedpList {
  5878. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5879. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5880. fpd["ccountstatus"] = 1
  5881. }
  5882. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5883. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5884. fpd["ccountratiostatus"] = 1
  5885. }
  5886. if next["ratio"].(string) != fpd["ratio"].(string) {
  5887. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5888. fpd["ratiostatus"] = 1
  5889. }
  5890. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5891. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5892. // fpd["ftnamestatus"] = 1
  5893. // }
  5894. }
  5895. }
  5896. }
  5897. }
  5898. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5899. }
  5900. // func GetLpplandtl1History(c *gin.Context) {
  5901. // appG := app.Gin{C: c}
  5902. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5903. // fsion := gofasion.NewFasion(string(dataByte))
  5904. // // parammaps := fsion.Get("parammaps")
  5905. // barid := fsion.Get("barid").ValueStr()
  5906. // startDate := fsion.Get("startDate").ValueStr()
  5907. // endDate := fsion.Get("endDate").ValueStr()
  5908. // tx := restful.Engine.NewSession()
  5909. // defer tx.Close()
  5910. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5911. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5912. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5913. // // if err != nil {
  5914. // // logs.Error(err)
  5915. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5916. // // return
  5917. // // }
  5918. // // for _, feedp := range feedpList {
  5919. // // fmt.Println(feedp)
  5920. // // for i, fpd := range fpdList {
  5921. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5922. // // for k, fpd2 := range fpdList {
  5923. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5924. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5925. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5926. // // }
  5927. // // break
  5928. // // }
  5929. // // }
  5930. // // fpd["barid"] = feedp["barid"]
  5931. // // fpd["barname"] = feedp["barname"]
  5932. // // fpd["ccount"] = feedp["ccount"]
  5933. // // fpd["ratio"] = feedp["ratio"]
  5934. // // fpd["ccountratio"] = feedp["ccountratio"]
  5935. // // fpd["ftid"] = feedp["ftid"]
  5936. // // fpd["ftname"] = feedp["ftname"]
  5937. // // }
  5938. // // }
  5939. // // }
  5940. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5941. // }
  5942. func GetRemind(c *gin.Context) {
  5943. appG := app.Gin{C: c}
  5944. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5945. fsion := gofasion.NewFasion(string(dataByte))
  5946. parammaps := fsion.Get("parammaps")
  5947. pastureid := parammaps.Get("pastureid").ValueStr()
  5948. tx := restful.Engine.NewSession()
  5949. defer tx.Close()
  5950. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5951. if err != nil {
  5952. logs.Error(err)
  5953. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5954. return
  5955. }
  5956. // pastureid = "3"
  5957. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5958. if err != nil {
  5959. logs.Error(err)
  5960. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5961. return
  5962. }
  5963. defer resp.Body.Close()
  5964. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5965. buf.ReadFrom(resp.Body)
  5966. fmt.Println(string(buf.Bytes()))
  5967. respMap := make(map[string]interface{}, 0)
  5968. err = json.Unmarshal(buf.Bytes(), &respMap)
  5969. if err != nil {
  5970. logs.Error(err)
  5971. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5972. return
  5973. }
  5974. for _, data := range dataList {
  5975. r := make(map[string]interface{}, 0)
  5976. r["sys_name"] = ""
  5977. r["service_id"] = ""
  5978. r["pasture_id"] = ""
  5979. r["type_name"] = ""
  5980. r["remind_type_id"] = ""
  5981. r["remind_type"] = ""
  5982. r["push_date"] = ""
  5983. r["push_time"] = ""
  5984. r["interval_time"] = ""
  5985. r["push_limit"] = ""
  5986. r["template_id"] = ""
  5987. r["roles_id"] = ""
  5988. r["users_id"] = ""
  5989. r["date_type"] = ""
  5990. r["cycle_type"] = ""
  5991. data["data"] = r
  5992. for _, resp := range respMap["data"].([]interface{}) {
  5993. resp1 := resp.(map[string]interface{})
  5994. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5995. if resp1["push_time"] == nil {
  5996. resp1["push_time"] = ""
  5997. }
  5998. data["data"] = resp1
  5999. break
  6000. }
  6001. }
  6002. }
  6003. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  6004. }
  6005. type NoticeMsgtype struct {
  6006. SysName string `json:"sys_name"`
  6007. PastureId int64 `json:"pasture_id"`
  6008. ServiceId int64 `json:"service_id"`
  6009. TypeName string `json:"type_name"`
  6010. RemindType int64 `json:"remind_type"`
  6011. PushDate int64 `json:"push_date"`
  6012. PushTime string `json:"push_time"`
  6013. IntervalTime int64 `json:"interval_time"`
  6014. PushLimit int64 `json:"push_limit"`
  6015. TemplateId string `json:"template_id"`
  6016. UsersId string `json:"users_id"`
  6017. DateType int64 `json:"date_type"`
  6018. CycleType int64 `json:"cycle_type"`
  6019. DelayTime int64 `json:"delay_time"`
  6020. Status int64 `json:"status"`
  6021. }
  6022. func UpdateRemind(c *gin.Context) {
  6023. appG := app.Gin{C: c}
  6024. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6025. parammaps := gofasion.NewFasion(string(dataByte))
  6026. // parammaps := fsion.Get("parammaps")
  6027. // user := parammaps.Get("user").ValueStr()
  6028. id := parammaps.Get("id").ValueInt64()
  6029. noticeMsgtype := new(NoticeMsgtype)
  6030. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  6031. noticeMsgtype.ServiceId = id
  6032. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  6033. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  6034. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  6035. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  6036. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  6037. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  6038. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  6039. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  6040. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  6041. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  6042. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  6043. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  6044. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  6045. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  6046. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  6047. //TODO
  6048. noticeMsgtype.SysName = "tmrWatch"
  6049. userList := parammaps.Get("user").Array()
  6050. var userstr []string
  6051. for _, user := range userList {
  6052. userstr = append(userstr, user.ValueStr())
  6053. }
  6054. tx := restful.Engine.NewSession()
  6055. defer tx.Close()
  6056. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  6057. if err != nil {
  6058. logs.Error(err)
  6059. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6060. return
  6061. }
  6062. // var jsonStr = []byte(noticeMsgtype
  6063. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  6064. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  6065. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  6066. req.Header.Set("Content-Type", "application/json")
  6067. client := &http.Client{}
  6068. resp, err := client.Do(req)
  6069. if err != nil {
  6070. logs.Error(err)
  6071. }
  6072. defer resp.Body.Close()
  6073. body, _ := ioutil.ReadAll(resp.Body)
  6074. fmt.Println("response Body:", string(body))
  6075. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  6076. if err != nil {
  6077. logs.Error(err)
  6078. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6079. return
  6080. }
  6081. defer getresp.Body.Close()
  6082. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6083. buf.ReadFrom(getresp.Body)
  6084. // fmt.Println(string(buf.Bytes()))
  6085. respMap := make(map[string]interface{}, 0)
  6086. err = json.Unmarshal(buf.Bytes(), &respMap)
  6087. if err != nil {
  6088. logs.Error(err)
  6089. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6090. return
  6091. }
  6092. for _, resp := range respMap["data"].([]interface{}) {
  6093. resp1 := resp.(map[string]interface{})
  6094. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6095. if err != nil {
  6096. logs.Error(err)
  6097. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6098. return
  6099. }
  6100. }
  6101. appG.Response(http.StatusOK, e.SUCCESS, true)
  6102. }
  6103. func GetSpillageallHistory(c *gin.Context) {
  6104. appG := app.Gin{C: c}
  6105. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6106. parammaps := gofasion.NewFasion(string(dataByte))
  6107. barname := parammaps.Get("barname").ValueStr()
  6108. pastureid := parammaps.Get("pastureid").ValueStr()
  6109. startdate := parammaps.Get("startDate").ValueStr()
  6110. enddate := parammaps.Get("endDate").ValueStr()
  6111. tx := restful.Engine.NewSession()
  6112. defer tx.Close()
  6113. 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
  6114. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6115. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6116. if err != nil {
  6117. logs.Error(err)
  6118. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6119. return
  6120. }
  6121. respMap := make([]map[string]interface{}, 0)
  6122. data := make(map[interface{}]interface{})
  6123. for _, history := range historyList {
  6124. data[history["createdate"]] = history["createdate"]
  6125. }
  6126. createList := []string{}
  6127. for _, v := range data {
  6128. createList = append(createList, v.(string))
  6129. }
  6130. // sort.Sort()
  6131. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6132. sort.Slice(createList, func(i, j int) bool {
  6133. return createList[i] > createList[j]
  6134. })
  6135. for _, v := range createList {
  6136. a := make(map[string]interface{})
  6137. a["createdate"] = data[v]
  6138. // createList = append(createList, v.(string))
  6139. respMap = append(respMap, a)
  6140. }
  6141. number := 0
  6142. dataMap := make([]interface{}, 0)
  6143. for k, resp := range respMap {
  6144. createdate := resp["createdate"].(string)
  6145. var nextcreatedate string
  6146. if len(respMap) > k+1 {
  6147. nextcreatedate = respMap[k+1]["createdate"].(string)
  6148. }
  6149. // dataList := make(map[string][]interface{})
  6150. // list := make(map[string]interface{})
  6151. times := make(map[interface{}]int)
  6152. for _, history := range historyList {
  6153. // List := make(map[interface{}][]interface{})
  6154. i := 0
  6155. if history["createdate"].(string) == createdate {
  6156. times[history["times"]]++
  6157. data := make(map[string]interface{})
  6158. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6159. // exist := false
  6160. if nextcreatedate != "" {
  6161. for _, history1 := range historyList {
  6162. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6163. history1["times"].(int64) == history["times"].(int64) {
  6164. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6165. break
  6166. // exist = true
  6167. }
  6168. }
  6169. }
  6170. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6171. i++
  6172. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6173. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6174. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6175. // resp["times"] = history["times"]
  6176. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6177. data1 := make(map[string]interface{})
  6178. data1["times"] = history["times"]
  6179. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6180. data1["createdate"] = resp["createdate"]
  6181. // fmt.Println(dataList)
  6182. dataMap = append(dataMap, data1)
  6183. }
  6184. if i > number {
  6185. number = i
  6186. }
  6187. // respMap = append(respMap, dataList)
  6188. }
  6189. // for k, data := range dataList {
  6190. // resp[k] = data
  6191. // }
  6192. // resp["data"] = dataList
  6193. }
  6194. // resp := make(map[string]interface{})
  6195. // sort.Strings(createList)
  6196. //
  6197. // for _, create := range createList {
  6198. // for _, r := range respMap {
  6199. // if create == r["createdate"].(string) {
  6200. // resp[create] = r
  6201. // break
  6202. // }
  6203. // }
  6204. // }
  6205. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6206. var trainsList []interface{}
  6207. for i := 0; i < number; i++ {
  6208. trains := make(map[string]interface{})
  6209. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6210. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6211. trainsList = append(trainsList, trains)
  6212. }
  6213. respdata := make(map[string]interface{})
  6214. respdata["data"] = dataMap
  6215. respdata["trains"] = trainsList
  6216. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6217. }
  6218. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6219. appG := app.Gin{C: c}
  6220. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6221. parammaps := gofasion.NewFasion(string(dataByte))
  6222. ftid := parammaps.Get("ftid").ValueInt64()
  6223. lastftid := parammaps.Get("lastftid").ValueInt64()
  6224. pastureid := parammaps.Get("pastureid").ValueInt64()
  6225. // createdate := parammaps.Get("createdate").ValueStr()
  6226. tx := restful.Engine.NewSession()
  6227. defer tx.Close()
  6228. data := make(map[string]interface{})
  6229. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6230. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6231. if err != nil {
  6232. logs.Error(err)
  6233. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6234. return
  6235. }
  6236. feedtemplet := make(map[string]interface{})
  6237. for _, f := range feedtempletList {
  6238. feedtemplet = f
  6239. }
  6240. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  6241. if err != nil {
  6242. logs.Error(err)
  6243. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6244. return
  6245. }
  6246. feedtemplet["fit"] = fitList
  6247. data["current"] = feedtemplet
  6248. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6249. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6250. if err != nil {
  6251. logs.Error(err)
  6252. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6253. return
  6254. }
  6255. lastfeedtemplet := make(map[string]interface{})
  6256. for _, f := range lastfeedtempletList {
  6257. lastfeedtemplet = f
  6258. }
  6259. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  6260. if err != nil {
  6261. logs.Error(err)
  6262. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6263. return
  6264. }
  6265. lastfeedtemplet["fit"] = lastfitList
  6266. data["last"] = lastfeedtemplet
  6267. appG.Response(http.StatusOK, e.SUCCESS, data)
  6268. }
  6269. func GetFeedtempletHistory(c *gin.Context) {
  6270. appG := app.Gin{C: c}
  6271. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6272. parammaps := gofasion.NewFasion(string(dataByte))
  6273. ftid := parammaps.Get("ftid").ValueStr()
  6274. pastureid := parammaps.Get("pastureid").ValueInt64()
  6275. start := parammaps.Get("startdate").ValueStr()
  6276. end := parammaps.Get("enddate").ValueStr()
  6277. tx := restful.Engine.NewSession()
  6278. defer tx.Close()
  6279. 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 ?
  6280. and id = ? and pastureid = ? order by createdate desc `,
  6281. start, end, ftid, pastureid).Query().List()
  6282. if err != nil {
  6283. logs.Error(err)
  6284. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6285. return
  6286. }
  6287. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6288. ftid, pastureid).Query().List()
  6289. if err != nil {
  6290. logs.Error(err)
  6291. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6292. return
  6293. }
  6294. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6295. for i, ft := range ftList {
  6296. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6297. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6298. (select empname from user where id = fit.userId) empname,
  6299. 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
  6300. where fit.fitid = ?
  6301. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6302. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6303. if err != nil {
  6304. logs.Error(err)
  6305. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6306. return
  6307. }
  6308. ft["createdate"] = ft["createdate1"]
  6309. // data["tname"] = ft["tname"]
  6310. // data["tcode"] = ft["tcode"]
  6311. // data["tcolor"] = ft["tcolor"]
  6312. // data["fttype"] = ft["fttype"]
  6313. // data["ccname"] = ft["ccname"]
  6314. // data["source"] = ft["source"]
  6315. // data["version"] = ft["version"]
  6316. // data["remark"] = ft["remark"]
  6317. for n, ft2 := range ftList {
  6318. if i < n {
  6319. if ft["tname"].(string) != ft2["tname"].(string) {
  6320. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6321. }
  6322. if _, ok := ft["tcode"]; ok {
  6323. if _, ok := ft2["tcode"]; ok {
  6324. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6325. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6326. }
  6327. }
  6328. }
  6329. if _, ok := ft["tcolor"]; ok {
  6330. if _, ok := ft2["tcolor"]; ok {
  6331. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6332. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6333. }
  6334. }
  6335. }
  6336. if _, ok := ft["fttype"]; ok {
  6337. if _, ok := ft2["fttype"]; ok {
  6338. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6339. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6340. }
  6341. }
  6342. }
  6343. if _, ok := ft["ccname"]; ok {
  6344. if _, ok := ft2["ccname"]; ok {
  6345. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6346. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6347. }
  6348. }
  6349. }
  6350. if _, ok := ft["source"]; ok {
  6351. if _, ok := ft2["source"]; ok {
  6352. if ft["source"].(string) != ft2["source"].(string) {
  6353. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6354. }
  6355. }
  6356. }
  6357. if _, ok := ft["version"]; ok {
  6358. if _, ok := ft2["version"]; ok {
  6359. if ft["version"].(int64) != ft2["version"].(int64) {
  6360. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6361. }
  6362. }
  6363. }
  6364. if _, ok := ft["remark"]; ok {
  6365. if _, ok := ft2["remark"]; ok {
  6366. if ft["remark"].(string) != ft2["remark"].(string) {
  6367. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6368. }
  6369. }
  6370. }
  6371. break
  6372. }
  6373. }
  6374. dataList := make([]map[string]interface{}, 0)
  6375. if len(fithisList) > 0 {
  6376. for _, fit := range fithisList {
  6377. data := make(map[string]interface{})
  6378. data["feedgroup"] = fit["feedgroup"]
  6379. data["fname"] = fit["fname"]
  6380. data["empname"] = fit["empname"]
  6381. if fit["Eweight"] != nil {
  6382. if fit["Eweight"].(string) != fit["weight"].(string) {
  6383. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6384. } else {
  6385. data["fweight"] = fit["Eweight"]
  6386. }
  6387. data["fweightstatus"] = 1
  6388. } else {
  6389. data["fweight"] = fit["weight"]
  6390. data["fweightstatus"] = 0
  6391. }
  6392. data["autosecond"] = fit["autosecond"]
  6393. // data["tname"] = ft["tname"]
  6394. // data["tcode"] = ft["tcode"]
  6395. // data["tcolor"] = ft["tcolor"]
  6396. // data["fttype"] = ft["fttype"]
  6397. // data["ccname"] = ft["ccname"]
  6398. // data["source"] = ft["source"]
  6399. // data["version"] = ft["version"]
  6400. // data["remark"] = ft["remark"]
  6401. // data["createdate"] = ft["createdate1"]
  6402. // ft["fit"] = data
  6403. dataList = append(dataList, data)
  6404. }
  6405. } else {
  6406. for _, fit := range ftdetailList {
  6407. data := make(map[string]interface{})
  6408. data["feedgroup"] = fit["feedgroup"]
  6409. data["fname"] = fit["fname"]
  6410. // if fit["Eweight"] != nil {
  6411. // data["weight"] = fit["Eweight"]
  6412. // } else {
  6413. data["fweight"] = fit["fweight"]
  6414. // }
  6415. data["autosecond"] = fit["autosecond"]
  6416. // ft["fit"] = data
  6417. dataList = append(dataList, data)
  6418. }
  6419. }
  6420. ft["fit"] = dataList
  6421. }
  6422. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6423. }
  6424. func UpdateMaterialTMR(c *gin.Context) {
  6425. appG := app.Gin{C: c}
  6426. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6427. parammaps := gofasion.NewFasion(string(dataByte))
  6428. tmrid := parammaps.Get("tmrid").ValueStr()
  6429. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6430. lppid := parammaps.Get("lppid").ValueStr()
  6431. times := parammaps.Get("times").ValueStr()
  6432. pastureid := parammaps.Get("pastureid").ValueStr()
  6433. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6434. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6435. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6436. tx := restful.Engine.NewSession()
  6437. defer tx.Close()
  6438. tx.Begin()
  6439. if tmrid != "1000" {
  6440. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6441. if err != nil {
  6442. logs.Error(err)
  6443. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6444. return
  6445. }
  6446. var maxstirfeed float64
  6447. for _, tmr := range tmrList {
  6448. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6449. }
  6450. if status == 0 {
  6451. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6452. if err != nil {
  6453. tx.Rollback()
  6454. logs.Error(err)
  6455. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6456. return
  6457. }
  6458. var lweight float64
  6459. for _, item := range lpplandtl1List {
  6460. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6461. lweight += fl
  6462. }
  6463. if lweight > maxstirfeed {
  6464. lweight = lweight - maxstirfeed
  6465. } else {
  6466. lweight = 0
  6467. }
  6468. if lweight > 0 {
  6469. lweight1 := lweight / float64(len(lpplandtl1List))
  6470. number := 0
  6471. for _, item := range lpplandtl1List {
  6472. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6473. if lweight1 >= fl {
  6474. number++
  6475. }
  6476. }
  6477. lweight := lweight / float64((len(lpplandtl1List) - number))
  6478. for _, item := range lpplandtl1List {
  6479. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6480. if lweight1 >= fl {
  6481. continue
  6482. }
  6483. if tmrtype == "1" {
  6484. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6485. if err != nil {
  6486. tx.Rollback()
  6487. logs.Error(err)
  6488. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6489. return
  6490. }
  6491. } else if tmrtype == "2" {
  6492. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6493. if err != nil {
  6494. tx.Rollback()
  6495. logs.Error(err)
  6496. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6497. return
  6498. }
  6499. }
  6500. if item["fttype"].(int64) == 0 {
  6501. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6502. if err != nil {
  6503. tx.Rollback()
  6504. logs.Error(err)
  6505. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6506. return
  6507. }
  6508. } else {
  6509. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6510. if err != nil {
  6511. tx.Rollback()
  6512. logs.Error(err)
  6513. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6514. return
  6515. }
  6516. }
  6517. }
  6518. } else {
  6519. for _, item := range lpplandtl1List {
  6520. // 自走式
  6521. if tmrtype == "1" {
  6522. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6523. if err != nil {
  6524. logs.Error(err)
  6525. tx.Rollback()
  6526. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6527. return
  6528. }
  6529. } else if tmrtype == "2" {
  6530. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6531. if err != nil {
  6532. logs.Error(err)
  6533. tx.Rollback()
  6534. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6535. return
  6536. }
  6537. }
  6538. }
  6539. }
  6540. } else if status == 1 {
  6541. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6542. if err != nil {
  6543. logs.Error(err)
  6544. tx.Rollback()
  6545. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6546. return
  6547. }
  6548. var lweight float64
  6549. for _, item := range lpplandtl1List {
  6550. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6551. lweight += fl
  6552. }
  6553. if lweight > maxstirfeed {
  6554. lweight = lweight - maxstirfeed
  6555. } else {
  6556. lweight = 0
  6557. }
  6558. for _, item := range lpplandtl1List {
  6559. if lweight > 0 {
  6560. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6561. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6562. if fl >= lweight {
  6563. item["lweight"] = fl - lweight
  6564. lweight = 0
  6565. if tmrtype == "1" {
  6566. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6567. if err != nil {
  6568. logs.Error(err)
  6569. tx.Rollback()
  6570. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6571. return
  6572. }
  6573. } else if tmrtype == "2" {
  6574. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6575. if err != nil {
  6576. logs.Error(err)
  6577. tx.Rollback()
  6578. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6579. return
  6580. }
  6581. }
  6582. if item["fttype"].(int64) == 0 {
  6583. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6584. if err != nil {
  6585. logs.Error(err)
  6586. tx.Rollback()
  6587. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6588. return
  6589. }
  6590. } else {
  6591. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6592. if err != nil {
  6593. logs.Error(err)
  6594. tx.Rollback()
  6595. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6596. return
  6597. }
  6598. }
  6599. } else {
  6600. lweight = lweight - fl
  6601. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6602. if err != nil {
  6603. logs.Error(err)
  6604. tx.Rollback()
  6605. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6606. return
  6607. }
  6608. if item["fttype"].(int64) == 0 {
  6609. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6610. if err != nil {
  6611. logs.Error(err)
  6612. tx.Rollback()
  6613. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6614. return
  6615. }
  6616. } else {
  6617. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6618. if err != nil {
  6619. logs.Error(err)
  6620. tx.Rollback()
  6621. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6622. return
  6623. }
  6624. }
  6625. }
  6626. } else {
  6627. // 自走式
  6628. if tmrtype == "1" {
  6629. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6630. if err != nil {
  6631. logs.Error(err)
  6632. tx.Rollback()
  6633. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6634. return
  6635. }
  6636. } else if tmrtype == "2" {
  6637. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6638. if err != nil {
  6639. logs.Error(err)
  6640. tx.Rollback()
  6641. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6642. return
  6643. }
  6644. }
  6645. }
  6646. }
  6647. } else {
  6648. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6649. if err != nil {
  6650. logs.Error(err)
  6651. tx.Rollback()
  6652. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6653. return
  6654. }
  6655. for _, item := range lpplandtl1List {
  6656. if item["fttype"].(int64) == 0 {
  6657. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6658. if err != nil {
  6659. logs.Error(err)
  6660. tx.Rollback()
  6661. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6662. return
  6663. }
  6664. } else {
  6665. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6666. if err != nil {
  6667. logs.Error(err)
  6668. tx.Rollback()
  6669. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6670. return
  6671. }
  6672. }
  6673. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6674. if err != nil {
  6675. logs.Error(err)
  6676. tx.Rollback()
  6677. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6678. return
  6679. }
  6680. }
  6681. }
  6682. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6683. if err != nil {
  6684. logs.Error(err)
  6685. tx.Rollback()
  6686. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6687. return
  6688. }
  6689. } else {
  6690. if status == 2 {
  6691. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6692. if err != nil {
  6693. logs.Error(err)
  6694. tx.Rollback()
  6695. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6696. return
  6697. }
  6698. for _, item := range lpplandtl1List {
  6699. if item["fttype"].(int64) == 0 {
  6700. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6701. if err != nil {
  6702. logs.Error(err)
  6703. tx.Rollback()
  6704. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6705. return
  6706. }
  6707. } else {
  6708. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6709. if err != nil {
  6710. logs.Error(err)
  6711. tx.Rollback()
  6712. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6713. return
  6714. }
  6715. }
  6716. }
  6717. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6718. if err != nil {
  6719. logs.Error(err)
  6720. tx.Rollback()
  6721. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6722. return
  6723. }
  6724. } else {
  6725. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6726. if err != nil {
  6727. logs.Error(err)
  6728. tx.Rollback()
  6729. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6730. return
  6731. }
  6732. }
  6733. }
  6734. err := tx.Commit()
  6735. if err != nil {
  6736. logs.Error(err)
  6737. tx.Rollback()
  6738. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6739. return
  6740. }
  6741. appG.Response(http.StatusOK, e.SUCCESS, true)
  6742. }
  6743. func UpdateMaterialTMRDate(c *gin.Context) {
  6744. appG := app.Gin{C: c}
  6745. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6746. parammaps := gofasion.NewFasion(string(dataByte))
  6747. tmrid := parammaps.Get("tmrid").ValueStr()
  6748. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6749. lppid := parammaps.Get("lppid").ValueStr()
  6750. times := parammaps.Get("times").ValueStr()
  6751. pastureid := parammaps.Get("pastureid").ValueStr()
  6752. date := parammaps.Get("date").ValueStr()
  6753. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6754. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6755. tx := restful.Engine.NewSession()
  6756. defer tx.Close()
  6757. tx.Begin()
  6758. if tmrid != "1000" {
  6759. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6760. if err != nil {
  6761. logs.Error(err)
  6762. tx.Rollback()
  6763. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6764. return
  6765. }
  6766. var maxstirfeed float64
  6767. for _, tmr := range tmrList {
  6768. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6769. }
  6770. if status == 0 {
  6771. 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()
  6772. if err != nil {
  6773. logs.Error(err)
  6774. tx.Rollback()
  6775. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6776. return
  6777. }
  6778. var lweight float64
  6779. for _, item := range lpplandtl1List {
  6780. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6781. lweight += fl
  6782. }
  6783. if lweight > maxstirfeed {
  6784. lweight = lweight - maxstirfeed
  6785. } else {
  6786. lweight = 0
  6787. }
  6788. if lweight > 0 {
  6789. lweight1 := lweight / float64(len(lpplandtl1List))
  6790. number := 0
  6791. for _, item := range lpplandtl1List {
  6792. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6793. if lweight1 >= fl {
  6794. number++
  6795. }
  6796. }
  6797. lweight := lweight / float64((len(lpplandtl1List) - number))
  6798. for _, item := range lpplandtl1List {
  6799. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6800. if lweight1 >= fl {
  6801. continue
  6802. }
  6803. if tmrtype == "1" {
  6804. _, 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()
  6805. if err != nil {
  6806. logs.Error(err)
  6807. tx.Rollback()
  6808. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6809. return
  6810. }
  6811. } else if tmrtype == "2" {
  6812. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6813. if err != nil {
  6814. logs.Error(err)
  6815. tx.Rollback()
  6816. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6817. return
  6818. }
  6819. }
  6820. if item["fttype"].(int64) == 0 {
  6821. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6822. if err != nil {
  6823. logs.Error(err)
  6824. tx.Rollback()
  6825. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6826. return
  6827. }
  6828. } else {
  6829. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6830. if err != nil {
  6831. logs.Error(err)
  6832. tx.Rollback()
  6833. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6834. return
  6835. }
  6836. }
  6837. }
  6838. } else {
  6839. for _, item := range lpplandtl1List {
  6840. // 自走式
  6841. if tmrtype == "1" {
  6842. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6843. if err != nil {
  6844. logs.Error(err)
  6845. tx.Rollback()
  6846. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6847. return
  6848. }
  6849. } else if tmrtype == "2" {
  6850. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6851. if err != nil {
  6852. logs.Error(err)
  6853. tx.Rollback()
  6854. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6855. return
  6856. }
  6857. }
  6858. }
  6859. }
  6860. } else if status == 1 {
  6861. 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()
  6862. if err != nil {
  6863. logs.Error(err)
  6864. tx.Rollback()
  6865. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6866. return
  6867. }
  6868. var lweight float64
  6869. for _, item := range lpplandtl1List {
  6870. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6871. lweight += fl
  6872. }
  6873. if lweight > maxstirfeed {
  6874. lweight = lweight - maxstirfeed
  6875. } else {
  6876. lweight = 0
  6877. }
  6878. for _, item := range lpplandtl1List {
  6879. if lweight > 0 {
  6880. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6881. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6882. if fl >= lweight {
  6883. item["lweight"] = fl - lweight
  6884. lweight = 0
  6885. if tmrtype == "1" {
  6886. _, 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()
  6887. if err != nil {
  6888. logs.Error(err)
  6889. tx.Rollback()
  6890. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6891. return
  6892. }
  6893. } else if tmrtype == "2" {
  6894. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6895. if err != nil {
  6896. logs.Error(err)
  6897. tx.Rollback()
  6898. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6899. return
  6900. }
  6901. }
  6902. if item["fttype"].(int64) == 0 {
  6903. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6904. if err != nil {
  6905. logs.Error(err)
  6906. tx.Rollback()
  6907. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6908. return
  6909. }
  6910. } else {
  6911. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6912. if err != nil {
  6913. logs.Error(err)
  6914. tx.Rollback()
  6915. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6916. return
  6917. }
  6918. }
  6919. } else {
  6920. lweight = lweight - fl
  6921. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6922. if err != nil {
  6923. logs.Error(err)
  6924. tx.Rollback()
  6925. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6926. return
  6927. }
  6928. if item["fttype"].(int64) == 0 {
  6929. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6930. if err != nil {
  6931. logs.Error(err)
  6932. tx.Rollback()
  6933. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6934. return
  6935. }
  6936. } else {
  6937. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6938. if err != nil {
  6939. logs.Error(err)
  6940. tx.Rollback()
  6941. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6942. return
  6943. }
  6944. }
  6945. }
  6946. } else {
  6947. // 自走式
  6948. if tmrtype == "1" {
  6949. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6950. if err != nil {
  6951. logs.Error(err)
  6952. tx.Rollback()
  6953. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6954. return
  6955. }
  6956. } else if tmrtype == "2" {
  6957. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6958. if err != nil {
  6959. logs.Error(err)
  6960. tx.Rollback()
  6961. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6962. return
  6963. }
  6964. }
  6965. }
  6966. }
  6967. } else {
  6968. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6969. if err != nil {
  6970. logs.Error(err)
  6971. tx.Rollback()
  6972. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6973. return
  6974. }
  6975. for _, item := range lpplandtl1List {
  6976. if item["fttype"].(int64) == 0 {
  6977. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6978. if err != nil {
  6979. logs.Error(err)
  6980. tx.Rollback()
  6981. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6982. return
  6983. }
  6984. } else {
  6985. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6986. if err != nil {
  6987. logs.Error(err)
  6988. tx.Rollback()
  6989. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6990. return
  6991. }
  6992. }
  6993. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6994. if err != nil {
  6995. logs.Error(err)
  6996. tx.Rollback()
  6997. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6998. return
  6999. }
  7000. }
  7001. }
  7002. _, 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()
  7003. if err != nil {
  7004. logs.Error(err)
  7005. tx.Rollback()
  7006. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7007. return
  7008. }
  7009. } else {
  7010. if status == 2 {
  7011. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  7012. if err != nil {
  7013. logs.Error(err)
  7014. tx.Rollback()
  7015. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7016. return
  7017. }
  7018. for _, item := range lpplandtl1List {
  7019. if item["fttype"].(int64) == 0 {
  7020. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7021. if err != nil {
  7022. logs.Error(err)
  7023. tx.Rollback()
  7024. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7025. return
  7026. }
  7027. } else {
  7028. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7029. if err != nil {
  7030. logs.Error(err)
  7031. tx.Rollback()
  7032. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7033. return
  7034. }
  7035. }
  7036. }
  7037. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  7038. if err != nil {
  7039. logs.Error(err)
  7040. tx.Rollback()
  7041. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7042. return
  7043. }
  7044. } else {
  7045. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  7046. if err != nil {
  7047. logs.Error(err)
  7048. tx.Rollback()
  7049. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7050. return
  7051. }
  7052. }
  7053. }
  7054. err := tx.Commit()
  7055. if err != nil {
  7056. logs.Error(err)
  7057. tx.Rollback()
  7058. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7059. return
  7060. }
  7061. appG.Response(http.StatusOK, e.SUCCESS, true)
  7062. }
  7063. func Decimal(value float64) float64 {
  7064. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  7065. return value
  7066. }
  7067. func UpdateDailyData(c *gin.Context) {
  7068. appG := app.Gin{C: c}
  7069. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7070. parammaps := gofasion.NewFasion(string(dataByte))
  7071. pid := parammaps.Get("pid").ValueDefaultStr("0")
  7072. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  7073. sort := parammaps.Get("sort").ValueDefaultStr("0")
  7074. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  7075. date := parammaps.Get("date").ValueStr()
  7076. tx := restful.Engine.NewSession()
  7077. defer tx.Close()
  7078. 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()
  7079. if err != nil {
  7080. logs.Error("UpdateDailyData-error-0:", err)
  7081. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7082. return
  7083. }
  7084. if count > 0 {
  7085. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7086. return
  7087. }
  7088. tx.Begin()
  7089. if location == 0 {
  7090. fid := parammaps.Get("fid").ValueStr()
  7091. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  7092. if err != nil {
  7093. logs.Error("UpdateDailyData-error-1:", err)
  7094. tx.Rollback()
  7095. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7096. return
  7097. }
  7098. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7099. if err != nil {
  7100. logs.Error("UpdateDailyData-error-1:", err)
  7101. tx.Rollback()
  7102. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7103. return
  7104. }
  7105. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7106. if err != nil {
  7107. fmt.Println("Error:", err)
  7108. return
  7109. }
  7110. actualWeight := weight - num
  7111. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7112. if err != nil {
  7113. logs.Error("UpdateDailyData-error-2:", err)
  7114. tx.Rollback()
  7115. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7116. return
  7117. }
  7118. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7119. if err != nil {
  7120. logs.Error("UpdateDailyData-error-3:", err)
  7121. tx.Rollback()
  7122. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7123. return
  7124. }
  7125. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7126. if err != nil {
  7127. logs.Error("UpdateDailyData-error-4:", err)
  7128. tx.Rollback()
  7129. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7130. return
  7131. }
  7132. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7133. if err != nil {
  7134. logs.Error("UpdateDailyData-error-5:", err)
  7135. tx.Rollback()
  7136. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7137. return
  7138. }
  7139. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7140. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7141. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7142. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7143. if err != nil {
  7144. fmt.Println("Error:", err)
  7145. return
  7146. }
  7147. // actual := actualWeight / float64(len(downloadedplanList))
  7148. for _, item := range downloadedplanList {
  7149. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7150. if err != nil {
  7151. fmt.Println("Error:", err)
  7152. return
  7153. }
  7154. actual := itemLweight / lweight * actualWeight
  7155. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7156. if err != nil {
  7157. logs.Error("UpdateDailyData-error-6:", err)
  7158. tx.Rollback()
  7159. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7160. return
  7161. }
  7162. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7163. if err != nil {
  7164. logs.Error("UpdateDailyData-error-7:", err)
  7165. tx.Rollback()
  7166. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7167. return
  7168. }
  7169. _, 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()
  7170. if err != nil {
  7171. logs.Error("UpdateDailyData-error-8:", err)
  7172. tx.Rollback()
  7173. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7174. return
  7175. }
  7176. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7177. if err != nil {
  7178. logs.Error("UpdateDailyData-error-9:", err)
  7179. tx.Rollback()
  7180. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7181. return
  7182. }
  7183. }
  7184. } else {
  7185. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7186. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7187. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7188. // if err != nil {
  7189. // fmt.Println("Error:", err)
  7190. // return
  7191. // }
  7192. for _, item := range downloadedplanList {
  7193. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7194. if err != nil {
  7195. logs.Error("UpdateDailyData-error-6:", err)
  7196. tx.Rollback()
  7197. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7198. return
  7199. }
  7200. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7201. item["lweight"], actualWeight, item["id"]).Execute()
  7202. if err != nil {
  7203. logs.Error("UpdateDailyData-error-7:", err)
  7204. tx.Rollback()
  7205. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7206. return
  7207. }
  7208. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7209. where pid = ?`, item["id"]).Execute()
  7210. if err != nil {
  7211. logs.Error("UpdateDailyData-error-8:", err)
  7212. tx.Rollback()
  7213. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7214. return
  7215. }
  7216. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7217. if err != nil {
  7218. logs.Error("UpdateDailyData-error-9:", err)
  7219. tx.Rollback()
  7220. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7221. return
  7222. }
  7223. }
  7224. }
  7225. } else {
  7226. fbarid := parammaps.Get("fbarid").ValueStr()
  7227. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7228. if err != nil {
  7229. logs.Error("UpdateDailyData-error-10:", err)
  7230. tx.Rollback()
  7231. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7232. return
  7233. }
  7234. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7235. if err != nil {
  7236. logs.Error("UpdateDailyData-error-1:", err)
  7237. tx.Rollback()
  7238. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7239. return
  7240. }
  7241. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7242. if err != nil {
  7243. fmt.Println("Error:", err)
  7244. return
  7245. }
  7246. actualWeight := weight - num
  7247. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7248. if err != nil {
  7249. logs.Error("UpdateDailyData-error-11:", err)
  7250. tx.Rollback()
  7251. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7252. return
  7253. }
  7254. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  7255. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7256. if err != nil {
  7257. logs.Error("UpdateDailyData-error-12:", err)
  7258. tx.Rollback()
  7259. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7260. return
  7261. }
  7262. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7263. where pid = ? `, pid).Execute()
  7264. if err != nil {
  7265. logs.Error("UpdateDailyData-error-13:", err)
  7266. tx.Rollback()
  7267. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7268. return
  7269. }
  7270. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7271. if err != nil {
  7272. logs.Error("UpdateDailyData-error-14:", err)
  7273. tx.Rollback()
  7274. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7275. return
  7276. }
  7277. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7278. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7279. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7280. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7281. if err != nil {
  7282. fmt.Println("Error:", err)
  7283. return
  7284. }
  7285. for _, item := range downloadedplanList {
  7286. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7287. if err != nil {
  7288. fmt.Println("Error:", err)
  7289. return
  7290. }
  7291. actual := itemLweight / lweight * actualWeight
  7292. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7293. if err != nil {
  7294. logs.Error("UpdateDailyData-error-6:", err)
  7295. tx.Rollback()
  7296. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7297. return
  7298. }
  7299. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7300. if err != nil {
  7301. logs.Error("UpdateDailyData-error-7:", err)
  7302. tx.Rollback()
  7303. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7304. return
  7305. }
  7306. _, 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()
  7307. if err != nil {
  7308. logs.Error("UpdateDailyData-error-8:", err)
  7309. tx.Rollback()
  7310. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7311. return
  7312. }
  7313. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7314. if err != nil {
  7315. logs.Error("UpdateDailyData-error-9:", err)
  7316. tx.Rollback()
  7317. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7318. return
  7319. }
  7320. }
  7321. } else {
  7322. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7323. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7324. for _, item := range downloadedplanList {
  7325. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7326. // if err != nil {
  7327. // fmt.Println("Error:", err)
  7328. // return
  7329. // }
  7330. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7331. if err != nil {
  7332. logs.Error("UpdateDailyData-error-6:", err)
  7333. tx.Rollback()
  7334. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7335. return
  7336. }
  7337. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7338. item["lweight"], actualWeight, item["id"]).Execute()
  7339. if err != nil {
  7340. logs.Error("UpdateDailyData-error-7:", err)
  7341. tx.Rollback()
  7342. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7343. return
  7344. }
  7345. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7346. where pid = ?`, item["id"]).Execute()
  7347. if err != nil {
  7348. logs.Error("UpdateDailyData-error-8:", err)
  7349. tx.Rollback()
  7350. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7351. return
  7352. }
  7353. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7354. if err != nil {
  7355. logs.Error("UpdateDailyData-error-9:", err)
  7356. tx.Rollback()
  7357. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7358. return
  7359. }
  7360. }
  7361. }
  7362. }
  7363. err = tx.Commit()
  7364. if err != nil {
  7365. logs.Error("UpdateDailyData-error-20:", err)
  7366. tx.Rollback()
  7367. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7368. return
  7369. }
  7370. appG.Response(http.StatusOK, e.SUCCESS, true)
  7371. }
  7372. func GetFormulaStatistics(c *gin.Context) {
  7373. appG := app.Gin{C: c}
  7374. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7375. parammaps := gofasion.NewFasion(string(dataByte))
  7376. startTime := parammaps.Get("startTime").ValueStr()
  7377. endTime := parammaps.Get("endTime").ValueStr()
  7378. pastureId := parammaps.Get("pastureId").ValueStr()
  7379. tx := restful.Engine.NewSession()
  7380. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7381. if err != nil {
  7382. logs.Error("GetFormulaStatistics-error-1:", err)
  7383. tx.Rollback()
  7384. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7385. return
  7386. }
  7387. var feedtemplet, dateList []string
  7388. for _, f := range feedtempletList {
  7389. feedtemplet = append(feedtemplet, f["tname"].(string))
  7390. }
  7391. layout := "2006-01-02"
  7392. // s := "2023-05-01"
  7393. // e := "2023-05-23"
  7394. start, err := time.Parse(layout, startTime)
  7395. if err != nil {
  7396. fmt.Println(err)
  7397. return
  7398. }
  7399. end, err := time.Parse(layout, endTime)
  7400. if err != nil {
  7401. fmt.Println(err)
  7402. return
  7403. }
  7404. end = end.AddDate(0, 0, 1)
  7405. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7406. dateList = append(dateList, d.Format("2006-01-02"))
  7407. }
  7408. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7409. 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= ?
  7410. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7411. if err != nil {
  7412. logs.Error("GetFormulaStatistics-error-2:", err)
  7413. tx.Rollback()
  7414. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7415. return
  7416. }
  7417. var data2 [][]interface{}
  7418. for _, f := range feedtemplet {
  7419. var data1 []interface{}
  7420. for _, date := range dateList {
  7421. exist := false
  7422. for _, item := range downloadedplanList {
  7423. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7424. data1 = append(data1, item["total"])
  7425. exist = true
  7426. break
  7427. }
  7428. }
  7429. if !exist {
  7430. data1 = append(data1, 0)
  7431. }
  7432. }
  7433. data2 = append(data2, data1)
  7434. }
  7435. //前端让加的
  7436. feedtemplet = append(feedtemplet, "")
  7437. {
  7438. var data1 []interface{}
  7439. for _, f := range dateList {
  7440. // f = f + "\n"
  7441. fmt.Println(f)
  7442. data1 = append(data1, 0)
  7443. }
  7444. data2 = append(data2, data1)
  7445. }
  7446. resp := make(map[string]interface{}, 0)
  7447. resp["xdata"] = dateList
  7448. resp["data1"] = feedtemplet
  7449. resp["data2"] = data2
  7450. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7451. }
  7452. func GetPlanData(c *gin.Context) {
  7453. appG := app.Gin{C: c}
  7454. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7455. fsion := gofasion.NewFasion(string(dataByte))
  7456. sqlnamestr := fsion.Get("name").ValueStr()
  7457. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7458. offset := fsion.Get("offset").ValueDefaultInt(0)
  7459. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7460. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7461. month := fsion.Get("month").ValueDefaultStr("map")
  7462. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7463. tx := restful.Engine.NewSession()
  7464. err := tx.Begin()
  7465. defer func() {
  7466. switch {
  7467. case err != nil:
  7468. if tx != nil {
  7469. tx.Rollback()
  7470. }
  7471. default:
  7472. if tx != nil {
  7473. err = tx.Commit()
  7474. }
  7475. }
  7476. if tx != nil {
  7477. tx.Close()
  7478. }
  7479. }()
  7480. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7481. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7482. if sql != "" {
  7483. s_params := make([]interface{}, 0)
  7484. if fsion.HasKey("parammaps") {
  7485. parammaps := fsion.Get("parammaps")
  7486. paramslist := strings.Split(p, ",")
  7487. if len(paramslist) > 0 && p != "" {
  7488. for _, value := range paramslist {
  7489. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7490. if tempv, exists := c.Get("jwt_username"); exists {
  7491. s_params = append(s_params, tempv.(string))
  7492. } else {
  7493. s_params = append(s_params, "")
  7494. }
  7495. } else {
  7496. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7497. }
  7498. }
  7499. }
  7500. }
  7501. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7502. if err != nil {
  7503. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7504. } else {
  7505. paramslist1 := strings.Split(p1, ",")
  7506. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7507. s_params1 := make([]interface{}, 0)
  7508. if len(paramslist1) > 0 && p1 != "" {
  7509. for _, v := range paramslist1 {
  7510. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7511. }
  7512. }
  7513. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7514. for _, item := range arr {
  7515. trgaddressList := []string{}
  7516. if _, ok := item["trgaddress"]; ok {
  7517. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7518. for _, str := range trgaddressList1 {
  7519. if str != "" {
  7520. trgaddressList = append(trgaddressList, str)
  7521. }
  7522. }
  7523. }
  7524. item["trgaddressList"] = trgaddressList
  7525. }
  7526. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7527. }
  7528. // var wg sync.WaitGroup
  7529. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7530. // wg.Add(1)
  7531. // go func(value map[string]interface{}) {
  7532. // defer wg.Done()
  7533. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7534. // }(value)
  7535. // }
  7536. // wg.Wait()
  7537. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7538. }
  7539. } else {
  7540. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7541. }
  7542. }
  7543. func PostPlanData(c *gin.Context) {
  7544. appG := app.Gin{C: c}
  7545. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7546. fsion := gofasion.NewFasion(string(dataByte))
  7547. logging.Info("PostRJSBData err: ", string(dataByte))
  7548. s_params := make([]interface{}, 0)
  7549. tx := restful.Engine.NewSession()
  7550. err := tx.Begin()
  7551. defer func() {
  7552. switch {
  7553. case err != nil:
  7554. if tx != nil {
  7555. tx.Rollback()
  7556. }
  7557. default:
  7558. if tx != nil {
  7559. err = tx.Commit()
  7560. }
  7561. }
  7562. if tx != nil {
  7563. tx.Close()
  7564. }
  7565. }()
  7566. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7567. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7568. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7569. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7570. if !fsion.HasKey("parammaps") {
  7571. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7572. return
  7573. }
  7574. parammaps := fsion.Get("parammaps")
  7575. // paramslist := strings.Split(p, ",")
  7576. // if len(paramslist) > 0 && p != "" {
  7577. // for _, value := range paramslist {
  7578. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7579. // }
  7580. // }
  7581. // _, err = tx.SQL(sql, s_params...).Execute()
  7582. // if err != nil {
  7583. // logging.Error("PostRJSBData err: ", err)
  7584. // msg := geterrmsg(err.Error())
  7585. // appG.Response(http.StatusOK, e.ERROR, msg)
  7586. // return
  7587. // }
  7588. s_params = make([]interface{}, 0)
  7589. paramslist := strings.Split(p1, ",")
  7590. if len(paramslist) > 0 && p1 != "" {
  7591. for _, value := range paramslist {
  7592. // if value == "ID" {
  7593. // id := parammaps.Get("ID").ValueStr()
  7594. // pastureid := parammaps.Get("pastureid").ValueStr()
  7595. // 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
  7596. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7597. // if err != nil {
  7598. // logging.Error("PostRJSBData err: ", err)
  7599. // msg := geterrmsg(err.Error())
  7600. // appG.Response(http.StatusOK, e.ERROR, msg)
  7601. // return
  7602. // }
  7603. // for _, item := range datalist {
  7604. // id = item["id"]
  7605. // }
  7606. // s_params = append(s_params, id)
  7607. // } else {
  7608. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7609. // }
  7610. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7611. }
  7612. }
  7613. _, err = tx.SQL(sql1, s_params...).Execute()
  7614. if err != nil {
  7615. logging.Error("PostRJSBData1 err: ", err)
  7616. msg := geterrmsg(err.Error())
  7617. appG.Response(http.StatusOK, e.ERROR, msg)
  7618. return
  7619. }
  7620. s_params = make([]interface{}, 0)
  7621. paramslist = strings.Split(p2, ",")
  7622. if len(paramslist) > 0 && p2 != "" {
  7623. for _, value := range paramslist {
  7624. if value == "ID" {
  7625. id := parammaps.Get("ID").ValueStr()
  7626. pastureid := parammaps.Get("pastureid").ValueStr()
  7627. 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
  7628. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7629. if err != nil {
  7630. logging.Error("PostRJSBData err: ", err)
  7631. msg := geterrmsg(err.Error())
  7632. appG.Response(http.StatusOK, e.ERROR, msg)
  7633. return
  7634. }
  7635. for _, item := range datalist {
  7636. id = item["id"]
  7637. }
  7638. s_params = append(s_params, id)
  7639. } else {
  7640. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7641. }
  7642. }
  7643. }
  7644. _, err = tx.SQL(sql2, s_params...).Execute()
  7645. if err != nil {
  7646. logging.Error("PostRJSBData2 err: ", err)
  7647. msg := geterrmsg(err.Error())
  7648. appG.Response(http.StatusOK, e.ERROR, msg)
  7649. return
  7650. }
  7651. s_params = make([]interface{}, 0)
  7652. paramslist = strings.Split(p3, ",")
  7653. if len(paramslist) > 0 && p3 != "" {
  7654. for _, value := range paramslist {
  7655. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7656. }
  7657. }
  7658. _, err = tx.SQL(sql3, s_params...).Execute()
  7659. if err != nil {
  7660. logging.Error("PostRJSBData3 err: ", err)
  7661. msg := geterrmsg(err.Error())
  7662. appG.Response(http.StatusOK, e.ERROR, msg)
  7663. return
  7664. }
  7665. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7666. }
  7667. func CheckFeedTrgaddress(c *gin.Context) {
  7668. appG := app.Gin{C: c}
  7669. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7670. fsion := gofasion.NewFasion(string(dataByte))
  7671. fclassid := fsion.Get("fclassid").ValueStr()
  7672. feedId := fsion.Get("feedId").ValueStr()
  7673. backup1 := fsion.Get("backup1").ValueStr()
  7674. backup1List := strings.Split(backup1, ",")
  7675. tx := restful.Engine.NewSession()
  7676. defer tx.Close()
  7677. // if backup1 != "" {
  7678. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7679. for _, feed := range feedList {
  7680. if feed["backup1"] == "" {
  7681. continue
  7682. }
  7683. feedbackupList := strings.Split(feed["backup1"], ",")
  7684. for _, feedbackup := range feedbackupList {
  7685. for _, backup := range backup1List {
  7686. if feedbackup == backup {
  7687. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7688. return
  7689. }
  7690. }
  7691. }
  7692. }
  7693. // }
  7694. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7695. }
  7696. func ThiGetDataByName(c *gin.Context) {
  7697. appG := app.Gin{C: c}
  7698. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7699. fsion := gofasion.NewFasion(string(dataByte))
  7700. sqlnamestr := fsion.Get("name").ValueStr()
  7701. offset := fsion.Get("offset").ValueDefaultInt(0)
  7702. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7703. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7704. tx := restful.Engine.NewSession()
  7705. err := tx.Begin()
  7706. defer func() {
  7707. switch {
  7708. case err != nil:
  7709. logging.Error("tx.Begin 事务启动失败__error:", err)
  7710. if tx != nil {
  7711. tx.Rollback()
  7712. }
  7713. default:
  7714. if tx != nil {
  7715. err = tx.Commit()
  7716. }
  7717. }
  7718. if tx != nil {
  7719. tx.Close()
  7720. }
  7721. }()
  7722. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7723. if sql != "" {
  7724. s_params := make([]interface{}, 0)
  7725. if fsion.HasKey("parammaps") {
  7726. parammaps := fsion.Get("parammaps")
  7727. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7728. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7729. }
  7730. paramslist := strings.Split(p, ",")
  7731. if len(paramslist) > 0 && p != "" {
  7732. for _, value := range paramslist {
  7733. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7734. if tempv, exists := c.Get("jwt_username"); exists {
  7735. s_params = append(s_params, tempv.(string))
  7736. } else {
  7737. s_params = append(s_params, "")
  7738. }
  7739. } else {
  7740. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7741. }
  7742. }
  7743. }
  7744. } else if fsion.HasKey("params") {
  7745. params := fsion.Get("params").Array()
  7746. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7747. for _, v_params := range params {
  7748. s_params = append(s_params, v_params.ValueStr())
  7749. }
  7750. }
  7751. if returntype == "xlsx" {
  7752. var xlsxfile *xlsx.File
  7753. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7754. //c.File("c:/dd.xlsx")
  7755. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7756. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7757. c.Header("Content-Transfer-Encoding", "binary")
  7758. _ = xlsxfile.Write(c.Writer)
  7759. } else {
  7760. if sqlnamestr == "getHomepageStr" {
  7761. parammaps := fsion.Get("parammaps")
  7762. pastureid := parammaps.Get("pastureid").ValueStr()
  7763. var montimeList []float64
  7764. var montime float64
  7765. var wg sync.WaitGroup
  7766. now := time.Now()
  7767. for i := 0; i < 30; i++ {
  7768. wg.Add(1)
  7769. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7770. go func(nowstr string) {
  7771. defer wg.Done()
  7772. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7773. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7774. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7775. montimeList = append(montimeList, m)
  7776. }(nowstr)
  7777. }
  7778. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7779. if err != nil {
  7780. logging.Error("GetDataByName err: ", err)
  7781. msg := geterrmsg(err.Error())
  7782. appG.Response(http.StatusOK, e.ERROR, msg)
  7783. }
  7784. wg.Wait()
  7785. for _, m := range montimeList {
  7786. montime += m
  7787. }
  7788. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7789. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7790. return
  7791. }
  7792. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7793. if err != nil {
  7794. logging.Error("GetDataByName err: ", err)
  7795. msg := geterrmsg(err.Error())
  7796. appG.Response(http.StatusOK, e.ERROR, msg)
  7797. } else {
  7798. if sqlnamestr == "getFeedTrgaddressList" {
  7799. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7800. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7801. trgaddressList := []string{}
  7802. for _, str := range trgaddressList1 {
  7803. if str != "" {
  7804. trgaddressList = append(trgaddressList, str)
  7805. }
  7806. }
  7807. item["trgaddressList"] = trgaddressList
  7808. }
  7809. }
  7810. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7811. }
  7812. }
  7813. } else {
  7814. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7815. }
  7816. }
  7817. // func ToggleCcount(c *gin.Context) {
  7818. // appG := app.Gin{C: c}
  7819. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7820. // fsion := gofasion.NewFasion(string(dataByte))
  7821. // // 0 实际 1 软件
  7822. // status := fsion.Get("status").ValueDefaultInt64(0)
  7823. // pastureId := fsion.Get("pastureId").ValueStr()
  7824. // tx := restful.Engine.NewSession()
  7825. // err := tx.Begin()
  7826. // defer func() {
  7827. // switch {
  7828. // case err != nil:
  7829. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7830. // if tx != nil {
  7831. // tx.Rollback()
  7832. // }
  7833. // default:
  7834. // if tx != nil {
  7835. // err = tx.Commit()
  7836. // }
  7837. // }
  7838. // if tx != nil {
  7839. // tx.Close()
  7840. // }
  7841. // }()
  7842. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7843. // if err != nil {
  7844. // logs.Error(err)
  7845. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7846. // return
  7847. // }
  7848. // for _, bar := range barList {
  7849. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7850. // if err != nil {
  7851. // logs.Error(err)
  7852. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7853. // return
  7854. // }
  7855. // if !exist {
  7856. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7857. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7858. // if err != nil {
  7859. // logs.Error(err)
  7860. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7861. // return
  7862. // }
  7863. // }
  7864. // }
  7865. // if status == 0 {
  7866. // tx.Exec(`update feedp set ccount = actualcount `)
  7867. // }else{
  7868. // tx.Exec(`update feedp set ccount = softccount `)
  7869. // }
  7870. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7871. // if err != nil {
  7872. // logs.Error(err)
  7873. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7874. // return
  7875. // }
  7876. // for _, feedpData :=range feedpList{
  7877. // var feedpargs []interface{}
  7878. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7879. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7880. // if _, ok := feedpData["ftname"]; ok {
  7881. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7882. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7883. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7884. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7885. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7886. // } else {
  7887. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7888. // }
  7889. // if _, ok := feedpData["ptsfname"]; ok {
  7890. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7891. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7892. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7893. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7894. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7895. // } else {
  7896. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7897. // }
  7898. // upFeedpSql += " where barname = ? and pastureid = ? "
  7899. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7900. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7901. // if err != nil {
  7902. // logs.Error(err)
  7903. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7904. // return
  7905. // }
  7906. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7907. // if err != nil {
  7908. // logs.Error(err)
  7909. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7910. // return
  7911. // }
  7912. // if !exist1 {
  7913. // _, 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) `,
  7914. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7915. // if err != nil {
  7916. // logs.Error(err)
  7917. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7918. // return
  7919. // }
  7920. // }
  7921. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7922. // if err != nil {
  7923. // logs.Error(err)
  7924. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7925. // return
  7926. // }
  7927. // if !exist2 {
  7928. // _, 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) `,
  7929. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7930. // if err != nil {
  7931. // logs.Error(err)
  7932. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7933. // return
  7934. // }
  7935. // }
  7936. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7937. // if err != nil {
  7938. // logs.Error(err)
  7939. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7940. // return
  7941. // }
  7942. // if !exist3 {
  7943. // _, 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) `,
  7944. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7945. // if err != nil {
  7946. // logs.Error(err)
  7947. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7948. // return
  7949. // }
  7950. // }
  7951. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7952. // if err != nil {
  7953. // logs.Error(err)
  7954. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7955. // return
  7956. // }
  7957. // if !exist4 {
  7958. // _, 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) `,
  7959. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7960. // if err != nil {
  7961. // logs.Error(err)
  7962. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7963. // return
  7964. // }
  7965. // }
  7966. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7967. // if err != nil {
  7968. // logs.Error(err)
  7969. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7970. // return
  7971. // }
  7972. // if !exist5 {
  7973. // _, 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) `,
  7974. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7975. // if err != nil {
  7976. // logs.Error(err)
  7977. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7978. // return
  7979. // }
  7980. // }
  7981. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7982. // if err != nil {
  7983. // logs.Error(err)
  7984. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7985. // return
  7986. // }
  7987. // if !exist6 {
  7988. // _, 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) `,
  7989. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7990. // if err != nil {
  7991. // logs.Error(err)
  7992. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7993. // return
  7994. // }
  7995. // }
  7996. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7997. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7998. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7999. // and pastureid = ? and times = ?`
  8000. // var fpdargs1 []interface{}
  8001. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8002. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8003. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8004. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8005. // if err != nil {
  8006. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8007. // return
  8008. // }
  8009. // var fpdargs2 []interface{}
  8010. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8011. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8012. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8013. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8014. // if err != nil {
  8015. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8016. // return
  8017. // }
  8018. // var fpdargs3 []interface{}
  8019. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8020. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8021. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8022. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8023. // if err != nil {
  8024. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8025. // return
  8026. // }
  8027. // var fpdargs4 []interface{}
  8028. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8029. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8030. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8031. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8032. // if err != nil {
  8033. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8034. // return
  8035. // }
  8036. // var fpdargs5 []interface{}
  8037. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8038. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8039. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8040. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8041. // if err != nil {
  8042. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8043. // return
  8044. // }
  8045. // var fpdargs6 []interface{}
  8046. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8047. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8048. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8049. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8050. // if err != nil {
  8051. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8052. // return
  8053. // }
  8054. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8055. // 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()
  8056. // if err != nil {
  8057. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8058. // return
  8059. // }
  8060. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8061. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8062. // upFpdetailList := make([]*upFpdetail, 0)
  8063. // for _, newfpd := range newList {
  8064. // for _, oldfpd := range oldFpdList {
  8065. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8066. // var oldweight, newweight float64
  8067. // if oldfpd["weight"] != nil {
  8068. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8069. // }
  8070. // if newfpd["weight"] != nil {
  8071. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8072. // }
  8073. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8074. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  8075. // Old: oldweight,
  8076. // New: newweight,
  8077. // Times: newfpd["times"].(int64),
  8078. // Ptid: newfpd["ptid"].(int64),
  8079. // Fweight: fweight,
  8080. // Id: oldfpd["id"].(int64),
  8081. // })
  8082. // break
  8083. // }
  8084. // }
  8085. // }
  8086. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8087. // }
  8088. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8089. // }
  8090. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8091. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8092. if err != nil {
  8093. return err
  8094. }
  8095. for _, item := range feedpList {
  8096. // if item["ftid"].(string) != data["ftid"].(string) {
  8097. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8098. if err != nil {
  8099. return err
  8100. }
  8101. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8102. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8103. if err != nil {
  8104. return err
  8105. }
  8106. // }
  8107. }
  8108. return nil
  8109. }
  8110. func PostPlanDatas(c *gin.Context) {
  8111. appG := app.Gin{C: c}
  8112. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8113. fsions := gofasion.NewFasion(string(dataByte))
  8114. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8115. tx := restful.Engine.NewSession()
  8116. err := tx.Begin()
  8117. defer func() {
  8118. switch {
  8119. case err != nil:
  8120. if tx != nil {
  8121. tx.Rollback()
  8122. }
  8123. default:
  8124. if tx != nil {
  8125. err = tx.Commit()
  8126. }
  8127. }
  8128. if tx != nil {
  8129. tx.Close()
  8130. }
  8131. }()
  8132. pastureId := fsions.Get("pastureid").ValueStr()
  8133. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8134. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8135. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8136. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8137. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8138. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8139. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8140. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8141. for _, parammaps := range fsions.Get("arrList").Array() {
  8142. fmt.Println(parammaps.Json())
  8143. if parammaps.Json() == "null" {
  8144. continue
  8145. }
  8146. // if !fsion.HasKey("arrList") {
  8147. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8148. // return
  8149. // continue
  8150. // }
  8151. // parammaps := fsion.Get("arrList")
  8152. s_params := make([]interface{}, 0)
  8153. // paramslist := strings.Split(p, ",")
  8154. // if len(paramslist) > 0 && p != "" {
  8155. // for _, value := range paramslist {
  8156. // if value == "pastureid" {
  8157. // s_params = append(s_params, pastureId)
  8158. // } else {
  8159. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8160. // }
  8161. // }
  8162. // }
  8163. // _, err = tx.SQL(sql, s_params...).Execute()
  8164. // if err != nil {
  8165. // logging.Error("PostRJSBData err: ", err)
  8166. // msg := geterrmsg(err.Error())
  8167. // appG.Response(http.StatusOK, e.ERROR, msg)
  8168. // return
  8169. // }
  8170. s_params = make([]interface{}, 0)
  8171. paramslist := strings.Split(p1, ",")
  8172. if len(paramslist) > 0 && p1 != "" {
  8173. for _, value := range paramslist {
  8174. // if value == "ID" {
  8175. // id := parammaps.Get("ID").ValueStr()
  8176. // pastureid := parammaps.Get("pastureid").ValueStr()
  8177. // 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
  8178. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8179. // if err != nil {
  8180. // logging.Error("PostRJSBData err: ", err)
  8181. // msg := geterrmsg(err.Error())
  8182. // appG.Response(http.StatusOK, e.ERROR, msg)
  8183. // return
  8184. // }
  8185. // for _, item := range datalist {
  8186. // id = item["id"]
  8187. // }
  8188. // s_params = append(s_params, id)
  8189. // } else {
  8190. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8191. // }
  8192. if value == "pastureid" {
  8193. s_params = append(s_params, pastureId)
  8194. } else {
  8195. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8196. }
  8197. }
  8198. }
  8199. _, err = tx.SQL(sql1, s_params...).Execute()
  8200. if err != nil {
  8201. logging.Error("PostRJSBData1 err: ", err)
  8202. msg := geterrmsg(err.Error())
  8203. appG.Response(http.StatusOK, e.ERROR, msg)
  8204. return
  8205. }
  8206. s_params = make([]interface{}, 0)
  8207. paramslist = strings.Split(p2, ",")
  8208. if len(paramslist) > 0 && p2 != "" {
  8209. for _, value := range paramslist {
  8210. if value == "ID" {
  8211. id := parammaps.Get("ID").ValueStr()
  8212. pastureid := parammaps.Get("pastureid").ValueStr()
  8213. 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
  8214. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8215. if err != nil {
  8216. logging.Error("PostRJSBData err: ", err)
  8217. msg := geterrmsg(err.Error())
  8218. appG.Response(http.StatusOK, e.ERROR, msg)
  8219. return
  8220. }
  8221. for _, item := range datalist {
  8222. id = item["id"]
  8223. }
  8224. s_params = append(s_params, id)
  8225. } else if value == "pastureid" {
  8226. s_params = append(s_params, pastureId)
  8227. } else {
  8228. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8229. }
  8230. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8231. }
  8232. }
  8233. _, err = tx.SQL(sql2, s_params...).Execute()
  8234. if err != nil {
  8235. logging.Error("PostRJSBData2 err: ", err)
  8236. msg := geterrmsg(err.Error())
  8237. appG.Response(http.StatusOK, e.ERROR, msg)
  8238. return
  8239. }
  8240. s_params = make([]interface{}, 0)
  8241. paramslist = strings.Split(p3, ",")
  8242. if len(paramslist) > 0 && p3 != "" {
  8243. for _, value := range paramslist {
  8244. if value == "pastureid" {
  8245. s_params = append(s_params, pastureId)
  8246. } else {
  8247. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8248. }
  8249. }
  8250. }
  8251. _, err = tx.SQL(sql3, s_params...).Execute()
  8252. if err != nil {
  8253. logging.Error("PostRJSBData3 err: ", err)
  8254. msg := geterrmsg(err.Error())
  8255. appG.Response(http.StatusOK, e.ERROR, msg)
  8256. return
  8257. }
  8258. }
  8259. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8260. }
  8261. func FpdBatchEdit(c *gin.Context) {
  8262. appG := app.Gin{C: c}
  8263. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8264. fsions := gofasion.NewFasion(string(dataByte))
  8265. barList := fsions.Get("barList").Array()
  8266. pastureid := fsions.Get("pastureId").ValueStr()
  8267. tx := restful.Engine.NewSession()
  8268. defer tx.Close()
  8269. 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
  8270. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8271. if err != nil {
  8272. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8273. return
  8274. }
  8275. for _, barFsions := range barList {
  8276. dataexcel := make(map[string]interface{}, 0)
  8277. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8278. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8279. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8280. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8281. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8282. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8283. continue
  8284. }
  8285. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8286. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8287. // if err != nil {
  8288. // logs.Error(err)
  8289. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8290. // return
  8291. // }
  8292. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8293. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8294. // if err != nil {
  8295. // logs.Error(err)
  8296. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8297. // return
  8298. // }
  8299. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8300. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8301. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8302. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8303. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8304. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8305. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8306. if err != nil {
  8307. logs.Error(err)
  8308. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8309. return
  8310. }
  8311. if !ftexist {
  8312. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8313. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8314. if err != nil {
  8315. logs.Error(err)
  8316. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8317. return
  8318. }
  8319. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8320. if err != nil {
  8321. logs.Error(err)
  8322. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8323. return
  8324. }
  8325. }
  8326. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8327. if err != nil {
  8328. logs.Error(err)
  8329. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8330. return
  8331. }
  8332. if !exist {
  8333. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8334. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8335. if err != nil {
  8336. logs.Error(err)
  8337. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8338. return
  8339. }
  8340. }
  8341. var feedpargs []interface{}
  8342. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8343. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8344. if _, ok := dataexcel["ftname"]; ok {
  8345. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8346. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8347. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8348. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8349. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8350. } else {
  8351. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8352. }
  8353. if _, ok := dataexcel["ptsfname"]; ok {
  8354. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8355. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8356. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8357. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8358. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8359. } else {
  8360. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8361. }
  8362. upFeedpSql += " where barname = ? and pastureid = ? "
  8363. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8364. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8365. if err != nil {
  8366. logs.Error(err)
  8367. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8368. return
  8369. }
  8370. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8371. if err != nil {
  8372. logs.Error(err)
  8373. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8374. return
  8375. }
  8376. if !exist1 {
  8377. _, 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) `,
  8378. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8379. if err != nil {
  8380. logs.Error(err)
  8381. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8382. return
  8383. }
  8384. }
  8385. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8386. if err != nil {
  8387. logs.Error(err)
  8388. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8389. return
  8390. }
  8391. if !exist2 {
  8392. _, 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) `,
  8393. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8394. if err != nil {
  8395. logs.Error(err)
  8396. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8397. return
  8398. }
  8399. }
  8400. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8401. if err != nil {
  8402. logs.Error(err)
  8403. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8404. return
  8405. }
  8406. if !exist3 {
  8407. _, 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) `,
  8408. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8409. if err != nil {
  8410. logs.Error(err)
  8411. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8412. return
  8413. }
  8414. }
  8415. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8416. if err != nil {
  8417. logs.Error(err)
  8418. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8419. return
  8420. }
  8421. if !exist4 {
  8422. _, 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) `,
  8423. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8424. if err != nil {
  8425. logs.Error(err)
  8426. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8427. return
  8428. }
  8429. }
  8430. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8431. if err != nil {
  8432. logs.Error(err)
  8433. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8434. return
  8435. }
  8436. if !exist5 {
  8437. _, 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) `,
  8438. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8439. if err != nil {
  8440. logs.Error(err)
  8441. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8442. return
  8443. }
  8444. }
  8445. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8446. if err != nil {
  8447. logs.Error(err)
  8448. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8449. return
  8450. }
  8451. if !exist6 {
  8452. _, 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) `,
  8453. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8454. if err != nil {
  8455. logs.Error(err)
  8456. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8457. return
  8458. }
  8459. }
  8460. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8461. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8462. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8463. and pastureid = ? and times = ?`
  8464. var fpdargs1 []interface{}
  8465. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8466. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8467. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8468. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8469. if err != nil {
  8470. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8471. return
  8472. }
  8473. var fpdargs2 []interface{}
  8474. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8475. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8476. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8477. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8478. if err != nil {
  8479. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8480. return
  8481. }
  8482. var fpdargs3 []interface{}
  8483. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8484. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8485. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8486. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8487. if err != nil {
  8488. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8489. return
  8490. }
  8491. var fpdargs4 []interface{}
  8492. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8493. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8494. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8495. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8496. if err != nil {
  8497. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8498. return
  8499. }
  8500. var fpdargs5 []interface{}
  8501. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8502. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8503. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8504. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8505. if err != nil {
  8506. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8507. return
  8508. }
  8509. var fpdargs6 []interface{}
  8510. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8511. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8512. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8513. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8514. if err != nil {
  8515. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8516. return
  8517. }
  8518. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8519. 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()
  8520. if err != nil {
  8521. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8522. return
  8523. }
  8524. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8525. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8526. upFpdetailList := make([]*upFpdetail, 0)
  8527. for _, newfpd := range newList {
  8528. for _, oldfpd := range oldFpdList {
  8529. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8530. var oldweight, newweight float64
  8531. if oldfpd["weight"] != nil {
  8532. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8533. }
  8534. if newfpd["weight"] != nil {
  8535. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8536. }
  8537. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8538. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8539. Old: oldweight,
  8540. New: newweight,
  8541. Times: newfpd["times"].(int64),
  8542. Ptid: newfpd["ptid"].(int64),
  8543. Fweight: fweight,
  8544. Id: oldfpd["id"].(int64),
  8545. })
  8546. break
  8547. }
  8548. }
  8549. }
  8550. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8551. }
  8552. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8553. }
  8554. func UdBarSync(c *gin.Context) {
  8555. appG := app.Gin{C: c}
  8556. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8557. fsions := gofasion.NewFasion(string(dataByte))
  8558. pastureid := fsions.Get("pastureId").ValueStr()
  8559. tx := restful.Engine.NewSession()
  8560. defer tx.Close()
  8561. pastureinfo := new(udPastureInfo)
  8562. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8563. if err != nil {
  8564. logs.Error(err)
  8565. return
  8566. }
  8567. gm.UdBarSync(pastureid, pastureinfo.Werks)
  8568. // jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8569. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8570. }
  8571. func UdFeedSync(c *gin.Context) {
  8572. appG := app.Gin{C: c}
  8573. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8574. fsions := gofasion.NewFasion(string(dataByte))
  8575. pastureid := fsions.Get("pastureId").ValueStr()
  8576. tx := restful.Engine.NewSession()
  8577. defer tx.Close()
  8578. pastureinfo := new(udPastureInfo)
  8579. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8580. if err != nil {
  8581. logs.Error(err)
  8582. return
  8583. }
  8584. gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8585. // jpud.UdFeedSync(pastureid, pastureinfo.Werks)
  8586. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8587. }
  8588. func UdFeedtempletPush(c *gin.Context) {
  8589. appG := app.Gin{C: c}
  8590. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8591. fsions := gofasion.NewFasion(string(dataByte))
  8592. pastureid := fsions.Get("pastureId").ValueStr()
  8593. date := fsions.Get("date").ValueStr()
  8594. tx := restful.Engine.NewSession()
  8595. defer tx.Close()
  8596. pastureinfo := new(udPastureInfo)
  8597. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8598. if err != nil {
  8599. logs.Error(err)
  8600. return
  8601. }
  8602. gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8603. // jpud.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8604. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8605. }
  8606. func UdUtirPush(c *gin.Context) {
  8607. appG := app.Gin{C: c}
  8608. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8609. fsions := gofasion.NewFasion(string(dataByte))
  8610. pastureid := fsions.Get("pastureId").ValueStr()
  8611. date := fsions.Get("date").ValueStr()
  8612. tx := restful.Engine.NewSession()
  8613. defer tx.Close()
  8614. pastureinfo := new(udPastureInfo)
  8615. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8616. if err != nil {
  8617. logs.Error(err)
  8618. return
  8619. }
  8620. gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8621. // jpud.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8622. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8623. }
  8624. func UdBarFeedRemainPush(c *gin.Context) {
  8625. appG := app.Gin{C: c}
  8626. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8627. fsions := gofasion.NewFasion(string(dataByte))
  8628. pastureid := fsions.Get("pastureId").ValueStr()
  8629. date := fsions.Get("date").ValueStr()
  8630. tx := restful.Engine.NewSession()
  8631. defer tx.Close()
  8632. pastureinfo := new(udPastureInfo)
  8633. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8634. if err != nil {
  8635. logs.Error(err)
  8636. return
  8637. }
  8638. gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8639. // jpud.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8640. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8641. }
  8642. func UdMaterialIssuePush(c *gin.Context) {
  8643. appG := app.Gin{C: c}
  8644. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8645. fsions := gofasion.NewFasion(string(dataByte))
  8646. pastureid := fsions.Get("pastureId").ValueStr()
  8647. date := fsions.Get("date").ValueStr()
  8648. tx := restful.Engine.NewSession()
  8649. defer tx.Close()
  8650. pastureinfo := new(udPastureInfo)
  8651. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8652. if err != nil {
  8653. logs.Error(err)
  8654. return
  8655. }
  8656. gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8657. // jpud.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8658. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8659. }
  8660. //搅拌
  8661. func YmyUtirPush(c *gin.Context) {
  8662. appG := app.Gin{C: c}
  8663. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8664. fsions := gofasion.NewFasion(string(dataByte))
  8665. pastureid := fsions.Get("pastureId").ValueStr()
  8666. date := fsions.Get("date").ValueStr()
  8667. tx := restful.Engine.NewSession()
  8668. defer tx.Close()
  8669. pastureinfo := new(udPastureInfo)
  8670. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8671. if err != nil {
  8672. logs.Error(err)
  8673. return
  8674. }
  8675. ymy.YmyUtirPush(pastureid, pastureinfo.Werks, date)
  8676. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8677. }
  8678. //撒料
  8679. func YmyMaterialIssuePush(c *gin.Context) {
  8680. appG := app.Gin{C: c}
  8681. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8682. fsions := gofasion.NewFasion(string(dataByte))
  8683. pastureid := fsions.Get("pastureId").ValueStr()
  8684. date := fsions.Get("date").ValueStr()
  8685. tx := restful.Engine.NewSession()
  8686. defer tx.Close()
  8687. pastureinfo := new(udPastureInfo)
  8688. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8689. if err != nil {
  8690. logs.Error(err)
  8691. return
  8692. }
  8693. ymy.YmyMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8694. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8695. }
  8696. func YmyFeedtempletPush(c *gin.Context) {
  8697. appG := app.Gin{C: c}
  8698. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8699. fsions := gofasion.NewFasion(string(dataByte))
  8700. pastureid := fsions.Get("pastureId").ValueStr()
  8701. date := fsions.Get("date").ValueStr()
  8702. tx := restful.Engine.NewSession()
  8703. defer tx.Close()
  8704. pastureinfo := new(udPastureInfo)
  8705. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8706. if err != nil {
  8707. logs.Error(err)
  8708. return
  8709. }
  8710. ymy.YmyFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8711. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8712. }
  8713. //饲料
  8714. func YmySyncFeed(c *gin.Context) {
  8715. appG := app.Gin{C: c}
  8716. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8717. fsions := gofasion.NewFasion(string(dataByte))
  8718. pastureid := fsions.Get("pastureId").ValueStr()
  8719. // date := fsions.Get("date").ValueStr()
  8720. tx := restful.Engine.NewSession()
  8721. defer tx.Close()
  8722. ymy.YmySyncFeed(pastureid)
  8723. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8724. }
  8725. // 栏舍
  8726. func YmySyncBar(c *gin.Context) {
  8727. appG := app.Gin{C: c}
  8728. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8729. fsions := gofasion.NewFasion(string(dataByte))
  8730. pastureid := fsions.Get("pastureId").ValueStr()
  8731. // date := fsions.Get("date").ValueStr()
  8732. tx := restful.Engine.NewSession()
  8733. defer tx.Close()
  8734. pastureinfo := new(udPastureInfo)
  8735. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8736. if err != nil {
  8737. logs.Error(err)
  8738. return
  8739. }
  8740. ymy.YmySyncBar(pastureinfo.Werks, pastureid)
  8741. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8742. }
  8743. func DelFeedTemplet(c *gin.Context) {
  8744. appG := app.Gin{C: c}
  8745. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8746. fsions := gofasion.NewFasion(string(dataByte))
  8747. ftId := fsions.Get("ftId").ValueStr()
  8748. // userId := fsions.Get("userId").ValueStr()
  8749. tx := restful.Engine.NewSession()
  8750. defer tx.Close()
  8751. _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
  8752. if err != nil {
  8753. logs.Error(err)
  8754. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8755. return
  8756. }
  8757. /*
  8758. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8759. if err != nil {
  8760. logs.Error(err)
  8761. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8762. return
  8763. }
  8764. */
  8765. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8766. if err != nil {
  8767. logs.Error(err)
  8768. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8769. return
  8770. }
  8771. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8772. if err != nil {
  8773. logs.Error(err)
  8774. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8775. return
  8776. }
  8777. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8778. if count > 0 {
  8779. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8780. if err != nil {
  8781. logs.Error(err)
  8782. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8783. return
  8784. }
  8785. }
  8786. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8787. if err != nil {
  8788. logs.Error(err)
  8789. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8790. return
  8791. }
  8792. // var barIdStr []string
  8793. // for _, bar := range barIdList {
  8794. // barIdStr = append(barIdStr, bar["barid"])
  8795. // }
  8796. // if len(barIdStr) > 0 {
  8797. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8798. // if err != nil {
  8799. // logs.Error(err)
  8800. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8801. // return
  8802. // }
  8803. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8804. // if err != nil {
  8805. // logs.Error(err)
  8806. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8807. // return
  8808. // }
  8809. // now := time.Now()
  8810. // for _, newFpd := range newFpdDataList {
  8811. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8812. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8813. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8814. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8815. // if err != nil {
  8816. // logs.Error(err)
  8817. // appG.Response(http.StatusOK, e.ERROR, false)
  8818. // return
  8819. // }
  8820. // }
  8821. // for _, newFeedp := range newFeedpList {
  8822. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8823. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8824. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8825. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8826. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8827. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8828. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8829. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8830. // if err != nil {
  8831. // logs.Error(err)
  8832. // appG.Response(http.StatusOK, e.ERROR, false)
  8833. // return
  8834. // }
  8835. // }
  8836. // }
  8837. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8838. }
  8839. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8840. data := fasion["parammaps"].(map[string]interface{})
  8841. plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(0,1,2) ").Count()
  8842. fmt.Println(err)
  8843. plancount1, err := tx.SQL(`SELECT
  8844. count( 1 )
  8845. FROM
  8846. (
  8847. SELECT
  8848. d.id
  8849. FROM
  8850. downloadedplan d
  8851. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  8852. JOIN downloadplandtl1_exec d1e ON d1e.pid = d.id
  8853. JOIN downloadplandtl2 d2 ON d2.pid = d.id
  8854. WHERE
  8855. d.mydate = ?
  8856. AND d.havebutton = 0
  8857. AND lpplantype IN ( 0, 1, 2 )
  8858. AND ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id and dd2.fname = d2.fname) =
  8859. ( 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 )
  8860. GROUP BY
  8861. d.id
  8862. ) d
  8863. `,
  8864. data["startTime"]).Count()
  8865. fmt.Println(err)
  8866. if plancount != plancount1 && number < 10 {
  8867. number++
  8868. ExecDataParam(fasion, CommonParamMap, ParamMap, nil, nil, tx)
  8869. checkPlan(tx, fasion, CommonParamMap, ParamMap, number)
  8870. }
  8871. }
  8872. func EditPlanSort(c *gin.Context) {
  8873. appG := app.Gin{C: c}
  8874. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8875. fsions := gofasion.NewFasion(string(dataByte))
  8876. planIdStr := fsions.Get("planId").ValueStr()
  8877. mydate := fsions.Get("mydate").ValueStr()
  8878. sort := fsions.Get("sort").ValueStr()
  8879. tx := restful.Engine.NewSession()
  8880. defer tx.Close()
  8881. tx.Begin()
  8882. type downloadedplan struct {
  8883. Id int64 `xorm:"id"`
  8884. Sort int `xorm:"sort"`
  8885. Pid int64 `xorm:"pid"`
  8886. }
  8887. planInfo := new(downloadedplan)
  8888. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  8889. if err != nil {
  8890. logs.Error(err)
  8891. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8892. tx.Rollback()
  8893. return
  8894. }
  8895. sort1, _ := strconv.Atoi(sort)
  8896. if sort1 == planInfo.Sort {
  8897. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  8898. tx.Rollback()
  8899. return
  8900. }
  8901. 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()
  8902. if err != nil {
  8903. logs.Error(err)
  8904. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8905. tx.Rollback()
  8906. return
  8907. }
  8908. if count1 == 0 {
  8909. tx.Rollback()
  8910. logs.Error(err)
  8911. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  8912. return
  8913. }
  8914. 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()
  8915. if err != nil {
  8916. logs.Error(err)
  8917. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8918. tx.Rollback()
  8919. return
  8920. }
  8921. if count > 0 {
  8922. tx.Rollback()
  8923. logs.Error(err)
  8924. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  8925. return
  8926. }
  8927. if planInfo.Sort > sort1 {
  8928. 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()
  8929. if err != nil {
  8930. logs.Error(err)
  8931. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8932. tx.Rollback()
  8933. return
  8934. }
  8935. var minSort, pidCount int
  8936. for _, sort := range minSortList {
  8937. minSort, _ = strconv.Atoi(sort["sort"])
  8938. }
  8939. planList := make([]*downloadedplan, 0)
  8940. 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)
  8941. if err != nil {
  8942. logs.Error(err)
  8943. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8944. tx.Rollback()
  8945. return
  8946. }
  8947. planPid := planInfo.Pid
  8948. planList1 := make([]*downloadedplan, 0)
  8949. planList2 := make([]*downloadedplan, 0)
  8950. for _, plan := range planList {
  8951. if plan.Pid == planPid {
  8952. pidCount++
  8953. planList1 = append(planList1, plan)
  8954. } else {
  8955. planList2 = append(planList2, plan)
  8956. }
  8957. }
  8958. planList1 = append(planList1, planList2...)
  8959. for i, plan := range planList1 {
  8960. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  8961. if err != nil {
  8962. logs.Error(err)
  8963. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8964. tx.Rollback()
  8965. return
  8966. }
  8967. }
  8968. } else {
  8969. 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()
  8970. if err != nil {
  8971. logs.Error(err)
  8972. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8973. tx.Rollback()
  8974. return
  8975. }
  8976. var maxSort int
  8977. for _, sort := range maxSortList {
  8978. maxSort, _ = strconv.Atoi(sort["sort"])
  8979. }
  8980. planList := make([]*downloadedplan, 0)
  8981. 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)
  8982. if err != nil {
  8983. logs.Error(err)
  8984. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8985. tx.Rollback()
  8986. return
  8987. }
  8988. planPid := planInfo.Pid
  8989. planList1 := make([]*downloadedplan, 0)
  8990. planList2 := make([]*downloadedplan, 0)
  8991. for _, plan := range planList {
  8992. if plan.Pid == planPid {
  8993. // pidCount++
  8994. planList1 = append(planList1, plan)
  8995. } else {
  8996. planList2 = append(planList2, plan)
  8997. }
  8998. }
  8999. planList2 = append(planList2, planList1...)
  9000. for i, plan := range planList2 {
  9001. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  9002. if err != nil {
  9003. logs.Error(err)
  9004. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9005. tx.Rollback()
  9006. return
  9007. }
  9008. }
  9009. }
  9010. err = tx.Commit()
  9011. if err != nil {
  9012. logs.Error(err)
  9013. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9014. tx.Rollback()
  9015. return
  9016. }
  9017. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9018. }
  9019. func EditDownloadedplanArtificial(c *gin.Context) {
  9020. appG := app.Gin{C: c}
  9021. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9022. fsions := gofasion.NewFasion(string(dataByte))
  9023. planIdStr := fsions.Get("planId").ValueStr()
  9024. tx := restful.Engine.NewSession()
  9025. defer tx.Close()
  9026. tx.Begin()
  9027. planIdList := strings.Split(planIdStr, ",")
  9028. for _, planId := range planIdList {
  9029. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? `, planId)
  9030. if err != nil {
  9031. logs.Error(err)
  9032. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9033. tx.Rollback()
  9034. return
  9035. }
  9036. }
  9037. err := tx.Commit()
  9038. if err != nil {
  9039. logs.Error(err)
  9040. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9041. tx.Rollback()
  9042. return
  9043. }
  9044. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9045. }
  9046. type PlanRFID struct {
  9047. RFID string `json:"RFID"`
  9048. Lweight string `json:"lweight"`
  9049. Gear string `json:"gear"`
  9050. Speed string `json:"speed"`
  9051. }
  9052. func GetPlanRFID(c *gin.Context) {
  9053. appG := app.Gin{C: c}
  9054. RFIDStr := c.Query("RFID")
  9055. planRFIDList := make([]*PlanRFID, 0)
  9056. planRFIDList = append(planRFIDList, &PlanRFID{
  9057. RFID: RFIDStr,
  9058. Lweight: "1411.1",
  9059. Gear: "1",
  9060. Speed: "10",
  9061. })
  9062. planRFIDList = append(planRFIDList, &PlanRFID{
  9063. RFID: RFIDStr,
  9064. Lweight: "1322.1",
  9065. Gear: "1",
  9066. Speed: "10",
  9067. })
  9068. planRFIDList = append(planRFIDList, &PlanRFID{
  9069. RFID: RFIDStr,
  9070. Lweight: "1904.1",
  9071. Gear: "1",
  9072. Speed: "10",
  9073. })
  9074. planRFIDList = append(planRFIDList, &PlanRFID{
  9075. RFID: RFIDStr,
  9076. Lweight: "1870.1",
  9077. Gear: "1",
  9078. Speed: "10",
  9079. })
  9080. planRFIDList = append(planRFIDList, &PlanRFID{
  9081. RFID: RFIDStr,
  9082. Lweight: "2041.1",
  9083. Gear: "1",
  9084. Speed: "10",
  9085. })
  9086. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  9087. }
  9088. type tmrEquipmentMuster struct {
  9089. A string
  9090. N string
  9091. }
  9092. func GetTmrEquipmentMuster(c *gin.Context) {
  9093. appG := app.Gin{C: c}
  9094. id := c.Query("id")
  9095. tx := restful.Engine.NewSession()
  9096. defer tx.Close()
  9097. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  9098. if err != nil {
  9099. logs.Error(err)
  9100. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9101. return
  9102. }
  9103. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  9104. for _, data := range dataList {
  9105. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  9106. for _, g := range tmrEquipmentMusterList {
  9107. a, _ := strconv.ParseFloat(g.A, 64)
  9108. n, _ := strconv.ParseFloat(g.N, 64)
  9109. a1, n1 := ddmmtoddd(a, n)
  9110. g.A = fmt.Sprintf("%f", n1)
  9111. g.N = fmt.Sprintf("%f", a1)
  9112. }
  9113. }
  9114. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  9115. }
  9116. func ddmmtoddd(lng, lat float64) (float64, float64) {
  9117. lngDegree := fmt.Sprintf("%f", lng/100)
  9118. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  9119. lngDegreeInt := int(lngDegreefloat * 1000000)
  9120. dd := lngDegreeInt / 100 * 100 / 60
  9121. fmt.Println(dd)
  9122. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  9123. latDegree := fmt.Sprintf("%f", lat/100)
  9124. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  9125. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  9126. latDegreeInt := int(latDegreefloat * 1000000)
  9127. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  9128. a, _ := strconv.ParseFloat(lngStr, 64)
  9129. b, _ := strconv.ParseFloat(latStr, 64)
  9130. return coordtransform.WGS84toGCJ02(b, a)
  9131. }
  9132. func EditDownloadedplanExecWeight(c *gin.Context) {
  9133. appG := app.Gin{C: c}
  9134. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9135. fsions := gofasion.NewFasion(string(dataByte))
  9136. pid := fsions.Get("pid").ValueStr()
  9137. sort := fsions.Get("sort").ValueStr()
  9138. weight := fsions.Get("weight").ValueStr()
  9139. userId := fsions.Get("userId").ValueStr()
  9140. tx := restful.Engine.NewSession()
  9141. defer tx.Close()
  9142. tx.Begin()
  9143. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  9144. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  9145. pid, sort, pid, sort, weight, userId)
  9146. if err != nil {
  9147. logs.Error(err)
  9148. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9149. tx.Rollback()
  9150. return
  9151. }
  9152. _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9153. if err != nil {
  9154. logs.Error(err)
  9155. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9156. tx.Rollback()
  9157. return
  9158. }
  9159. _, 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)
  9160. if err != nil {
  9161. logs.Error(err)
  9162. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9163. tx.Rollback()
  9164. return
  9165. }
  9166. err = tx.Commit()
  9167. if err != nil {
  9168. logs.Error(err)
  9169. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9170. tx.Rollback()
  9171. return
  9172. }
  9173. appG.Response(http.StatusOK, e.SUCCESS, true)
  9174. }
  9175. func EditDownloadplandtl2Weight(c *gin.Context) {
  9176. appG := app.Gin{C: c}
  9177. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9178. fsions := gofasion.NewFasion(string(dataByte))
  9179. pid := fsions.Get("pid").ValueStr()
  9180. sort := fsions.Get("sort").ValueStr()
  9181. weight := fsions.Get("weight").ValueStr()
  9182. userId := fsions.Get("userId").ValueStr()
  9183. tx := restful.Engine.NewSession()
  9184. defer tx.Close()
  9185. tx.Begin()
  9186. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9187. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9188. pid, sort, pid, sort, weight, userId)
  9189. if err != nil {
  9190. logs.Error(err)
  9191. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9192. tx.Rollback()
  9193. return
  9194. }
  9195. _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9196. if err != nil {
  9197. logs.Error(err)
  9198. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9199. tx.Rollback()
  9200. return
  9201. }
  9202. err = tx.Commit()
  9203. if err != nil {
  9204. logs.Error(err)
  9205. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9206. tx.Rollback()
  9207. return
  9208. }
  9209. appG.Response(http.StatusOK, e.SUCCESS, true)
  9210. }
  9211. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9212. params := fasion.Get("parammaps")
  9213. surplus := params.Get("surplus").ValueStr()
  9214. surplusId := params.Get("surplusId").ValueStr()
  9215. tx := restful.Engine.NewSession()
  9216. defer tx.Close()
  9217. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9218. if surplusId != "0" {
  9219. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9220. if err != nil {
  9221. log.Println("PostDataByName-error-1: ", err)
  9222. return errors.New("配方修改失败!")
  9223. }
  9224. type ftdetail struct {
  9225. Id string
  9226. Fname string
  9227. Sort int64
  9228. }
  9229. ftList := make([]*ftdetail, 0)
  9230. for _, data := range dataList {
  9231. ft := new(ftdetail)
  9232. ft.Fname = data["fname"]
  9233. ft.Id = data["id"]
  9234. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9235. if err != nil {
  9236. log.Println("PostDataByName-error-2: ", err)
  9237. return err
  9238. }
  9239. ft.Sort = sort
  9240. ftList = append(ftList, ft)
  9241. }
  9242. if surplus == "日粮" {
  9243. for _, ft := range ftList {
  9244. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9245. }
  9246. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9247. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9248. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9249. fmt.Println(err)
  9250. } else {
  9251. var sort int64
  9252. for _, ft := range ftList {
  9253. if ft.Fname == surplus {
  9254. sort = ft.Sort
  9255. break
  9256. }
  9257. }
  9258. if sort == 0 {
  9259. for _, ft := range ftList {
  9260. ft.Sort = ft.Sort + 1
  9261. }
  9262. } else {
  9263. for _, ft := range ftList {
  9264. if ft.Sort >= sort {
  9265. ft.Sort = ft.Sort + 1
  9266. }
  9267. }
  9268. }
  9269. for _, ft := range ftList {
  9270. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9271. }
  9272. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9273. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9274. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9275. if err != nil {
  9276. log.Println("PostDataByName-error-1: ", err)
  9277. fmt.Println(err)
  9278. return errors.New("配方修改失败!")
  9279. }
  9280. }
  9281. }
  9282. return nil
  9283. }
  9284. func FeedSurplus(fasion *gofasion.Fasion) {
  9285. tx := restful.Engine.NewSession()
  9286. defer tx.Close()
  9287. params := fasion.Get("parammaps")
  9288. feedId := params.Get("id").ValueStr()
  9289. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9290. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9291. }
  9292. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9293. // params := fasion.Get("parammaps")
  9294. // surplus := params.Get("surplus").ValueStr()
  9295. // surplusId := params.Get("surplusId").ValueStr()
  9296. tx := restful.Engine.NewSession()
  9297. defer tx.Close()
  9298. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9299. if surplusId != "0" {
  9300. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9301. if err != nil {
  9302. log.Println("PostDataByName-error-1: ", err)
  9303. return errors.New("配方修改失败!")
  9304. }
  9305. type ftdetail struct {
  9306. Id string
  9307. Fname string
  9308. Sort int64
  9309. }
  9310. ftList := make([]*ftdetail, 0)
  9311. for _, data := range dataList {
  9312. ft := new(ftdetail)
  9313. ft.Fname = data["fname"]
  9314. ft.Id = data["id"]
  9315. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9316. if err != nil {
  9317. log.Println("PostDataByName-error-2: ", err)
  9318. return err
  9319. }
  9320. ft.Sort = sort
  9321. ftList = append(ftList, ft)
  9322. }
  9323. if surplus == "日粮" {
  9324. for _, ft := range ftList {
  9325. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9326. }
  9327. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9328. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9329. pastureId, id, surplusId, surplusId, surplusId)
  9330. fmt.Println(err)
  9331. } else {
  9332. var sort int64
  9333. for _, ft := range ftList {
  9334. if ft.Fname == surplus {
  9335. sort = ft.Sort
  9336. break
  9337. }
  9338. }
  9339. if sort == 0 {
  9340. for _, ft := range ftList {
  9341. ft.Sort = ft.Sort + 1
  9342. }
  9343. } else {
  9344. for _, ft := range ftList {
  9345. if ft.Sort >= sort {
  9346. ft.Sort = ft.Sort + 1
  9347. }
  9348. }
  9349. }
  9350. for _, ft := range ftList {
  9351. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9352. }
  9353. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9354. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9355. id, surplusId, surplusId, sort, surplusId, pastureId)
  9356. if err != nil {
  9357. log.Println("PostDataByName-error-1: ", err)
  9358. fmt.Println(err)
  9359. return errors.New("配方修改失败!")
  9360. }
  9361. }
  9362. }
  9363. return nil
  9364. }
  9365. func GetLanguageStatus() string {
  9366. tx := restful.Engine.NewSession()
  9367. defer tx.Close()
  9368. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9369. if err != nil {
  9370. log.Println(err)
  9371. return "0"
  9372. }
  9373. return dataList[0]["inforvalue"]
  9374. }
  9375. func EditLanguage(c *gin.Context) {
  9376. appG := app.Gin{C: c}
  9377. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9378. fsions := gofasion.NewFasion(string(dataByte))
  9379. language := fsions.Get("language").ValueStr()
  9380. tx := restful.Engine.NewSession()
  9381. defer tx.Close()
  9382. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9383. if err != nil {
  9384. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9385. return
  9386. }
  9387. if language == "0" {
  9388. _, err := tx.Exec(`delete from dictlist `)
  9389. if err != nil {
  9390. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9391. return
  9392. }
  9393. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9394. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9395. if err != nil {
  9396. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9397. return
  9398. }
  9399. } else {
  9400. _, err := tx.Exec(`delete from dictlist `)
  9401. if err != nil {
  9402. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9403. return
  9404. }
  9405. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9406. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9407. if err != nil {
  9408. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9409. return
  9410. }
  9411. }
  9412. appG.Response(http.StatusOK, e.SUCCESS, true)
  9413. }
  9414. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9415. tx := restful.Engine.NewSession()
  9416. defer tx.Close()
  9417. 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
  9418. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9419. if err != nil {
  9420. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9421. return
  9422. }
  9423. for _, dataexcel := range barList {
  9424. // dataexcel := make(map[string]interface{}, 0)
  9425. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9426. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9427. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9428. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9429. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9430. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9431. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9432. // if err != nil {
  9433. // logs.Error(err)
  9434. // return
  9435. // }
  9436. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9437. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9438. // if err != nil {
  9439. // logs.Error(err)
  9440. // return
  9441. // }
  9442. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9443. continue
  9444. }
  9445. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9446. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9447. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9448. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9449. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9450. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9451. // /*
  9452. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  9453. if err != nil {
  9454. logs.Error(err)
  9455. return
  9456. }
  9457. if !ftexist {
  9458. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  9459. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9460. if err != nil {
  9461. logs.Error(err)
  9462. return
  9463. }
  9464. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9465. if err != nil {
  9466. logs.Error(err)
  9467. return
  9468. }
  9469. }
  9470. // */
  9471. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9472. if err != nil {
  9473. logs.Error(err)
  9474. return
  9475. }
  9476. if !exist {
  9477. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9478. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9479. if err != nil {
  9480. logs.Error(err)
  9481. return
  9482. }
  9483. }
  9484. var feedpargs []interface{}
  9485. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9486. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9487. if _, ok := dataexcel["ftname"]; ok {
  9488. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9489. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9490. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9491. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9492. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9493. } else {
  9494. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9495. }
  9496. if _, ok := dataexcel["ptsfname"]; ok {
  9497. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9498. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9499. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9500. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9501. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9502. } else {
  9503. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9504. }
  9505. upFeedpSql += " where barname = ? and pastureid = ? "
  9506. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9507. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9508. if err != nil {
  9509. logs.Error(err)
  9510. return
  9511. }
  9512. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9513. if err != nil {
  9514. logs.Error(err)
  9515. return
  9516. }
  9517. if !exist1 {
  9518. _, 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) `,
  9519. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9520. if err != nil {
  9521. logs.Error(err)
  9522. return
  9523. }
  9524. }
  9525. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9526. if err != nil {
  9527. logs.Error(err)
  9528. return
  9529. }
  9530. if !exist2 {
  9531. _, 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) `,
  9532. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9533. if err != nil {
  9534. logs.Error(err)
  9535. return
  9536. }
  9537. }
  9538. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9539. if err != nil {
  9540. logs.Error(err)
  9541. return
  9542. }
  9543. if !exist3 {
  9544. _, 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) `,
  9545. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9546. if err != nil {
  9547. logs.Error(err)
  9548. return
  9549. }
  9550. }
  9551. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9552. if err != nil {
  9553. logs.Error(err)
  9554. return
  9555. }
  9556. if !exist4 {
  9557. _, 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) `,
  9558. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9559. if err != nil {
  9560. logs.Error(err)
  9561. return
  9562. }
  9563. }
  9564. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9565. if err != nil {
  9566. logs.Error(err)
  9567. return
  9568. }
  9569. if !exist5 {
  9570. _, 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) `,
  9571. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9572. if err != nil {
  9573. logs.Error(err)
  9574. return
  9575. }
  9576. }
  9577. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9578. if err != nil {
  9579. logs.Error(err)
  9580. return
  9581. }
  9582. if !exist6 {
  9583. _, 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) `,
  9584. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9585. if err != nil {
  9586. logs.Error(err)
  9587. return
  9588. }
  9589. }
  9590. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9591. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9592. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9593. and pastureid = ? and times = ?`
  9594. var fpdargs1 []interface{}
  9595. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9596. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9597. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9598. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9599. if err != nil {
  9600. fmt.Println(err)
  9601. return
  9602. }
  9603. var fpdargs2 []interface{}
  9604. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9605. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9606. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9607. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9608. if err != nil {
  9609. fmt.Println(err)
  9610. return
  9611. }
  9612. var fpdargs3 []interface{}
  9613. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9614. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9615. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9616. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9617. if err != nil {
  9618. fmt.Println(err)
  9619. return
  9620. }
  9621. var fpdargs4 []interface{}
  9622. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9623. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9624. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9625. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9626. if err != nil {
  9627. fmt.Println(err)
  9628. return
  9629. }
  9630. var fpdargs5 []interface{}
  9631. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9632. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9633. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9634. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9635. if err != nil {
  9636. fmt.Println(err)
  9637. return
  9638. }
  9639. var fpdargs6 []interface{}
  9640. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  9641. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9642. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  9643. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  9644. if err != nil {
  9645. fmt.Println(err)
  9646. return
  9647. }
  9648. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  9649. 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()
  9650. if err != nil {
  9651. return
  9652. }
  9653. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9654. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9655. upFpdetailList := make([]*upFpdetail, 0)
  9656. for _, newfpd := range newList {
  9657. for _, oldfpd := range oldFpdList {
  9658. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  9659. var oldweight, newweight float64
  9660. if oldfpd["weight"] != nil {
  9661. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  9662. }
  9663. if newfpd["weight"] != nil {
  9664. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  9665. }
  9666. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  9667. upFpdetailList = append(upFpdetailList, &upFpdetail{
  9668. Old: oldweight,
  9669. New: newweight,
  9670. Times: newfpd["times"].(int64),
  9671. Ptid: newfpd["ptid"].(int64),
  9672. Fweight: fweight,
  9673. Id: oldfpd["id"].(int64),
  9674. })
  9675. break
  9676. }
  9677. }
  9678. }
  9679. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  9680. }
  9681. }
  9682. func AddXxwFtdetail(c *gin.Context) {
  9683. appG := app.Gin{C: c}
  9684. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  9685. c.Bind(&xxwFtdetailList)
  9686. tx := restful.Engine.NewSession()
  9687. defer tx.Close()
  9688. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  9689. if err != nil {
  9690. logs.Error(err)
  9691. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9692. }
  9693. _, err = tx.Insert(xxwFtdetailList)
  9694. if err != nil {
  9695. logs.Error(err)
  9696. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9697. }
  9698. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  9699. appG.Response(http.StatusOK, e.SUCCESS, true)
  9700. }
  9701. func AddXxwFeedtemplet(c *gin.Context) {
  9702. appG := app.Gin{C: c}
  9703. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  9704. c.Bind(&xxwFeedtempletList)
  9705. tx := restful.Engine.NewSession()
  9706. defer tx.Close()
  9707. pastureinfo := new(udPastureInfo)
  9708. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  9709. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  9710. if err != nil {
  9711. logs.Error(err)
  9712. return
  9713. }
  9714. for _, ft := range xxwFeedtempletList {
  9715. ids, err := setting.SnowIds.NextId()
  9716. if err != nil {
  9717. ids = time.Now().UnixNano()
  9718. logging.Info("create SnowIds err", err)
  9719. }
  9720. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  9721. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  9722. ft.RecipeobjName, ft.RecipeobjName)
  9723. if err != nil {
  9724. logs.Error(err)
  9725. return
  9726. }
  9727. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  9728. _, 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')),
  9729. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  9730. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  9731. if err != nil {
  9732. logs.Error(err)
  9733. return
  9734. }
  9735. }
  9736. appG.Response(http.StatusOK, e.SUCCESS, true)
  9737. }
  9738. func ProcessExcel(c *gin.Context) {
  9739. appG := app.Gin{C: c}
  9740. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9741. fasion := gofasion.NewFasion(string(dataByte))
  9742. params := fasion.Get("parammaps")
  9743. pastureid := params.Get("pastureid").ValueStr()
  9744. startTime := params.Get("startTime").ValueStr()
  9745. stopTime := params.Get("stopTime").ValueStr()
  9746. iscompleted := params.Get("iscompleted").ValueStr()
  9747. lpplantype := params.Get("lpplantype").ValueStr()
  9748. error := params.Get("error").ValueStr()
  9749. hlwc1 := params.Get("hlwc1").ValueStr()
  9750. hlwc2 := params.Get("hlwc2").ValueStr()
  9751. slwc1 := params.Get("slwc1").ValueStr()
  9752. slwc2 := params.Get("slwc2").ValueStr()
  9753. hlzq1 := params.Get("hlzq1").ValueStr()
  9754. hlzq2 := params.Get("hlzq2").ValueStr()
  9755. slzq1 := params.Get("slzq1").ValueStr()
  9756. slzq2 := params.Get("slzq2").ValueStr()
  9757. fclassid := params.Get("fclassid").ValueStr()
  9758. minproesstime := params.Get("minproesstime").ValueStr()
  9759. maxproesstime := params.Get("maxproesstime").ValueStr()
  9760. tx := restful.Engine.NewSession()
  9761. defer tx.Close()
  9762. planList, err := tx.SQL(`SELECT
  9763. 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
  9764. FROM downloadedplan d
  9765. join pasture p on p.pastureid = d.pastureid
  9766. WHERE d.pastureid= ? and d.intime IS NOT NULL
  9767. AND mydate >= ? AND mydate <= ?
  9768. AND (iscompleted=? or ?='')
  9769. AND (lpplantype = ? or ? = '')
  9770. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  9771. 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
  9772. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  9773. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  9774. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  9775. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  9776. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  9777. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  9778. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  9779. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  9780. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  9781. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  9782. 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,
  9783. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  9784. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  9785. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  9786. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9787. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  9788. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  9789. or (?= '' and ? = '' ))
  9790. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  9791. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  9792. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  9793. maxproesstime, minproesstime, maxproesstime).QueryString()
  9794. if err != nil {
  9795. logs.Error(err)
  9796. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9797. return
  9798. }
  9799. planExecList, err := tx.SQL(`SELECT
  9800. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9801. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  9802. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  9803. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  9804. ) proesstime,
  9805. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9806. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  9807. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  9808. sumproesstime, d1.pid,
  9809. d1.sort,
  9810. d1.fname,
  9811. d1.lweight,
  9812. d1.actualweightminus,
  9813. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  9814. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  9815. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  9816. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  9817. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  9818. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  9819. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  9820. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  9821. d1.begintime stoptime,
  9822. d1.lastactualweight,
  9823. d1.actualweight,
  9824. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  9825. case d1.buttontype
  9826. when 1 then '自动'
  9827. when 2 then '手动'
  9828. when 3 then '手动'
  9829. end,
  9830. case d1.buttontype
  9831. when 1 then 'Automatic'
  9832. when 2 then 'Manual'
  9833. when 3 then 'Manual'
  9834. end
  9835. ) buttontype
  9836. FROM
  9837. downloadplandtl1_exec d1
  9838. WHERE d1.date between ? and ?
  9839. ORDER BY sort
  9840. `, startTime, stopTime).QueryString()
  9841. if err != nil {
  9842. logs.Error(err)
  9843. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9844. return
  9845. }
  9846. planExec2, err := tx.SQL(`SELECT
  9847. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  9848. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  9849. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9850. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  9851. ) proesstime,
  9852. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  9853. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9854. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  9855. d1.sort,
  9856. d1.fname,
  9857. d1.lweight,
  9858. d1.actualweightminus,
  9859. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  9860. ABS(d1.lweight- d1.actualweightminus) diff,
  9861. 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,
  9862. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  9863. d1.begintime stoptime,
  9864. d1.lastactualweight,
  9865. d1.actualweight,d1.pid
  9866. FROM
  9867. downloadplandtl2 d1
  9868. WHERE d1.date between ? and ?
  9869. ORDER BY sort`, startTime, stopTime).QueryString()
  9870. if err != nil {
  9871. logs.Error(err)
  9872. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9873. return
  9874. }
  9875. // 创建一个新的 Excel 文件
  9876. f := excelizexuri.NewFile()
  9877. // 创建工作表名称
  9878. sheetName := "Sheet1"
  9879. // border := []excelizexuri.Border{
  9880. // {Type: "left", Color: "000000", Style: 1},
  9881. // {Type: "right", Color: "000000", Style: 1},
  9882. // {Type: "top", Color: "000000", Style: 1},
  9883. // {Type: "bottom", Color: "000000", Style: 1},
  9884. // }
  9885. // 创建新的样式
  9886. style := &excelizexuri.Style{
  9887. // Border: border,
  9888. Alignment: &excelizexuri.Alignment{
  9889. Vertical: "center",
  9890. Horizontal: "center",
  9891. ShrinkToFit: true,
  9892. WrapText: true,
  9893. },
  9894. }
  9895. styleTitle := &excelizexuri.Style{
  9896. Fill: excelizexuri.Fill{
  9897. Color: []string{"FFFF0000"}, // 尝试使用完整的ARGB格式
  9898. },
  9899. // Border: border,
  9900. Font: &excelizexuri.Font{
  9901. Bold: true, // 加粗
  9902. Size: 24, // 字体大小
  9903. // Name: "宋体", // 字体名称
  9904. // WrapText :true,
  9905. Color: "000000", // 字体颜色(黑色)
  9906. },
  9907. Alignment: &excelizexuri.Alignment{
  9908. Vertical: "center", // 垂直居中
  9909. Horizontal: "center", // 水平居中
  9910. ShrinkToFit: true,
  9911. WrapText: true,
  9912. },
  9913. }
  9914. // 创建样式 ID
  9915. styleTitleId, err := f.NewStyle(styleTitle)
  9916. if err != nil {
  9917. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  9918. return
  9919. }
  9920. // 创建样式 ID
  9921. styleID, err := f.NewStyle(style)
  9922. if err != nil {
  9923. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  9924. return
  9925. }
  9926. // 合并单元格并设置内容
  9927. f.MergeCell(sheetName, "A1", "K1")
  9928. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  9929. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  9930. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  9931. planExecMap := make(map[string][]map[string]string, 0)
  9932. for _, planExec := range planExecList {
  9933. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  9934. }
  9935. plan2Map := make(map[string][]map[string]string, 0)
  9936. for _, plan2 := range planExec2 {
  9937. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  9938. }
  9939. num := 2
  9940. var notBorder []int
  9941. for _, plan := range planList {
  9942. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  9943. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  9944. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  9945. for i, header := range headers {
  9946. // 从 A2 开始
  9947. if header == "开始日期" {
  9948. cell := "%" + fmt.Sprintf("c%d", num)
  9949. cell = fmt.Sprintf(cell, 'A'+i+1)
  9950. f.SetCellValue(sheetName, cell, header)
  9951. f.SetCellStyle(sheetName, cell, cell, styleID)
  9952. continue
  9953. }
  9954. cell := "%" + fmt.Sprintf("c%d", num)
  9955. cell = fmt.Sprintf(cell, 'A'+i)
  9956. f.SetCellValue(sheetName, cell, header)
  9957. f.SetCellStyle(sheetName, cell, cell, styleID)
  9958. }
  9959. num += 1
  9960. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  9961. cell := "%" + fmt.Sprintf("c%d", num)
  9962. cell = fmt.Sprintf(cell, 'A'+0)
  9963. f.SetCellValue(sheetName, cell, plan["pastureName"])
  9964. f.SetCellStyle(sheetName, cell, cell, styleID)
  9965. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  9966. cell = "%" + fmt.Sprintf("c%d", num)
  9967. cell = fmt.Sprintf(cell, 'A'+1)
  9968. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  9969. f.SetCellStyle(sheetName, cell, cell, styleID)
  9970. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  9971. cell = "%" + fmt.Sprintf("c%d", num)
  9972. cell = fmt.Sprintf(cell, 'A'+2)
  9973. f.SetCellValue(sheetName, cell, plan["projname"])
  9974. f.SetCellStyle(sheetName, cell, cell, styleID)
  9975. cell = "%" + fmt.Sprintf("c%d", num)
  9976. cell = fmt.Sprintf(cell, 'A'+3)
  9977. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  9978. f.SetCellValue(sheetName, cell, plan["mydate"])
  9979. f.SetCellStyle(sheetName, cell, cell, styleID)
  9980. cell = "%" + fmt.Sprintf("c%d", num)
  9981. cell = fmt.Sprintf(cell, 'A'+6)
  9982. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  9983. f.SetCellValue(sheetName, cell, plan["intime"])
  9984. f.SetCellStyle(sheetName, cell, cell, styleID)
  9985. num += 1
  9986. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  9987. for i, header := range headers1 {
  9988. cell = "%" + fmt.Sprintf("c%d", num)
  9989. cell = fmt.Sprintf(cell, 'C'+i)
  9990. f.SetCellValue(sheetName, cell, header)
  9991. f.SetCellStyle(sheetName, cell, cell, styleID)
  9992. // maxWidth := len(header)
  9993. // colName := string('C' + i)
  9994. // f.SetColWidth(sheetName, colName, colName, 20)
  9995. f.SetColWidth(sheetName, header, header, 40)
  9996. }
  9997. num += 1
  9998. // 在循环外部创建红色样式(只创建一次)
  9999. redStyle := &excelizexuri.Style{
  10000. Fill: excelizexuri.Fill{
  10001. Type: "pattern",
  10002. Color: []string{"FF0000"},
  10003. Pattern: 1,
  10004. },
  10005. // Font: &excelizexuri.Font{
  10006. // Bold: true, // 加粗
  10007. // Size: 24, // 字体大小
  10008. // // Name: "宋体", // 字体名称
  10009. // // WrapText :true,
  10010. // Color: "FFFF0000", // 字体颜色(黑色)
  10011. // },
  10012. Alignment: &excelizexuri.Alignment{
  10013. Vertical: "center",
  10014. Horizontal: "center",
  10015. ShrinkToFit: true,
  10016. WrapText: true,
  10017. },
  10018. }
  10019. redStyleID, err := f.NewStyle(redStyle)
  10020. if err != nil {
  10021. c.String(http.StatusInternalServerError, "Failed to create red style: "+err.Error())
  10022. return
  10023. }
  10024. // 在循环内部正确使用条件判断
  10025. for _, planExec := range planExecMap[plan["id"]] {
  10026. var currentStyleID int
  10027. if planExec["abnormal"] == "1" {
  10028. currentStyleID = redStyleID
  10029. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, planExec["abnormal"]) // 调试
  10030. } else {
  10031. currentStyleID = styleID
  10032. }
  10033. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10034. sort, _ := strconv.Atoi(planExec["sort"])
  10035. f.SetCellValue(sheetName, cell, sort)
  10036. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10037. cell = fmt.Sprintf("D%d", num)
  10038. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  10039. f.SetCellValue(sheetName, cell, lweight)
  10040. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10041. cell = fmt.Sprintf("E%d", num)
  10042. if _, ok := planExec["actualweightminus"]; ok {
  10043. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  10044. f.SetCellValue(sheetName, cell, actualweightminus)
  10045. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10046. } else {
  10047. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  10048. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10049. }
  10050. cell = fmt.Sprintf("F%d", num)
  10051. f.SetCellValue(sheetName, cell, planExec["fname"])
  10052. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10053. cell = fmt.Sprintf("G%d", num)
  10054. if _, ok := planExec["diff"]; ok {
  10055. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  10056. f.SetCellValue(sheetName, cell, diff)
  10057. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10058. } else {
  10059. f.SetCellValue(sheetName, cell, planExec["diff"])
  10060. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10061. }
  10062. cell = fmt.Sprintf("H%d", num)
  10063. if _, ok := planExec["diffRate"]; ok {
  10064. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  10065. f.SetCellValue(sheetName, cell, diffRate)
  10066. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10067. } else {
  10068. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  10069. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10070. }
  10071. cell = fmt.Sprintf("I%d", num)
  10072. f.SetCellValue(sheetName, cell, planExec["intime"])
  10073. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10074. cell = fmt.Sprintf("J%d", num)
  10075. if _, ok := planExec["lastactualweight"]; ok {
  10076. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  10077. f.SetCellValue(sheetName, cell, lastactualweight)
  10078. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10079. } else {
  10080. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  10081. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10082. }
  10083. cell = fmt.Sprintf("K%d", num)
  10084. if _, ok := planExec["actualweight"]; ok {
  10085. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  10086. f.SetCellValue(sheetName, cell, actualweight)
  10087. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10088. } else {
  10089. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  10090. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10091. }
  10092. num += 1
  10093. }
  10094. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10095. for i, header := range headers2 {
  10096. cell := "%" + fmt.Sprintf("c%d", num)
  10097. cell = fmt.Sprintf(cell, 'C'+i)
  10098. f.SetCellValue(sheetName, cell, header)
  10099. f.SetCellStyle(sheetName, cell, cell, styleID)
  10100. maxWidth := len(header)
  10101. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  10102. }
  10103. num += 1
  10104. for _, plan2 := range plan2Map[plan["id"]] {
  10105. var currentStyleID int
  10106. if plan2["abnormal"] == "1" {
  10107. currentStyleID = redStyleID
  10108. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, plan2["abnormal"]) // 调试
  10109. } else {
  10110. currentStyleID = styleID
  10111. }
  10112. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10113. sort, _ := strconv.Atoi(plan2["sort"])
  10114. f.SetCellValue(sheetName, cell, sort)
  10115. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10116. cell = fmt.Sprintf("D%d", num)
  10117. f.SetCellValue(sheetName, cell, plan2["fname"])
  10118. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10119. cell = fmt.Sprintf("E%d", num)
  10120. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  10121. f.SetCellValue(sheetName, cell, lweight)
  10122. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10123. cell = fmt.Sprintf("F%d", num)
  10124. if _, ok := plan2["actualweightminus"]; ok {
  10125. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  10126. f.SetCellValue(sheetName, cell, actualweightminus)
  10127. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10128. } else {
  10129. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  10130. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10131. }
  10132. cell = fmt.Sprintf("G%d", num)
  10133. if _, ok := plan2["diff"]; ok {
  10134. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  10135. f.SetCellValue(sheetName, cell, diff)
  10136. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10137. } else {
  10138. f.SetCellValue(sheetName, cell, plan2["diff"])
  10139. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10140. }
  10141. cell = fmt.Sprintf("H%d", num)
  10142. if _, ok := plan2["diffRate"]; ok {
  10143. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  10144. f.SetCellValue(sheetName, cell, diffRate)
  10145. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10146. } else {
  10147. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  10148. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10149. }
  10150. cell = fmt.Sprintf("I%d", num)
  10151. f.SetCellValue(sheetName, cell, plan2["intime"])
  10152. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10153. cell = fmt.Sprintf("J%d", num)
  10154. if _, ok := plan2["lastactualweight"]; ok {
  10155. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  10156. f.SetCellValue(sheetName, cell, lastactualweight)
  10157. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10158. } else {
  10159. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  10160. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10161. }
  10162. cell = fmt.Sprintf("K%d", num)
  10163. if _, ok := plan2["lastactualweight"]; ok {
  10164. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  10165. f.SetCellValue(sheetName, cell, actualweight)
  10166. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10167. } else {
  10168. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  10169. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10170. }
  10171. num += 1
  10172. }
  10173. num += 1
  10174. notBorder = append(notBorder, num)
  10175. }
  10176. // for i := 2; i < num; i++ {
  10177. // exist := false
  10178. // for _, n := range notBorder {
  10179. // if i+1 == n {
  10180. // exist = true
  10181. // break
  10182. // }
  10183. // }
  10184. // if !exist {
  10185. // // 为 A-K 列设置边框
  10186. // for col := 'A'; col <= 'K'; col++ {
  10187. // cellName := fmt.Sprintf("%c%d", col, i)
  10188. // style, _ := f.NewStyle(&excelizexuri.Style{
  10189. // // Border: border,
  10190. // Alignment: &excelizexuri.Alignment{
  10191. // Vertical: "center",
  10192. // Horizontal: "center",
  10193. // ShrinkToFit: true,
  10194. // WrapText: true,
  10195. // },
  10196. // })
  10197. // f.SetCellStyle(sheetName, cellName, cellName, style)
  10198. // }
  10199. // }
  10200. // }
  10201. for col := 'A'; col <= 'K'; col++ {
  10202. colName := string(col)
  10203. switch colName {
  10204. case "A", "B": // 牧场名称、TMR列
  10205. f.SetColWidth(sheetName, colName, colName, 10)
  10206. case "C": // 操作编号列
  10207. f.SetColWidth(sheetName, colName, colName, 10)
  10208. case "D", "E": // 计划重量、实际重量列
  10209. f.SetColWidth(sheetName, colName, colName, 12)
  10210. case "F": // 代表成分/投料位置列
  10211. f.SetColWidth(sheetName, colName, colName, 20)
  10212. case "G", "H": // 误差数、准确率列
  10213. f.SetColWidth(sheetName, colName, colName, 12)
  10214. case "I": // 完成时间列
  10215. f.SetColWidth(sheetName, colName, colName, 15)
  10216. case "J", "K": // 起始读数重量、完成读数重量列
  10217. f.SetColWidth(sheetName, colName, colName, 15)
  10218. }
  10219. }
  10220. // 设置响应头
  10221. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10222. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10223. c.Header("Content-Transfer-Encoding", "binary")
  10224. // 写入 Excel 文件到响应
  10225. if err := f.Write(c.Writer); err != nil {
  10226. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10227. return
  10228. }
  10229. }
  10230. func RestartMqtt(c *gin.Context) {
  10231. appG := app.Gin{C: c}
  10232. // 发送 GET 请求到 MQTT 重启接口
  10233. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10234. if err != nil {
  10235. logging.Error("RestartMqtt request failed:", err)
  10236. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10237. return
  10238. }
  10239. defer resp.Body.Close()
  10240. // 读取响应内容f
  10241. body, err := ioutil.ReadAll(resp.Body)
  10242. if err != nil {
  10243. logging.Error("RestartMqtt read response failed:", err)
  10244. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10245. return
  10246. }
  10247. // 检查响应状态码
  10248. if resp.StatusCode != http.StatusOK {
  10249. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10250. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10251. return
  10252. }
  10253. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10254. }
  10255. func FpdBatchEditByWeight(c *gin.Context) {
  10256. appG := app.Gin{C: c}
  10257. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10258. fsions := gofasion.NewFasion(string(dataByte))
  10259. barList := fsions.Get("barList").Array()
  10260. pastureid := fsions.Get("pastureId").ValueStr()
  10261. tx := restful.Engine.NewSession()
  10262. defer tx.Close()
  10263. 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
  10264. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10265. if err != nil {
  10266. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10267. return
  10268. }
  10269. for _, barFsions := range barList {
  10270. dataexcel := make(map[string]interface{}, 0)
  10271. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10272. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10273. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10274. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10275. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10276. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10277. continue
  10278. }
  10279. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10280. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10281. // if err != nil {
  10282. // logs.Error(err)
  10283. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10284. // return
  10285. // }
  10286. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10287. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10288. // if err != nil {
  10289. // logs.Error(err)
  10290. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10291. // return
  10292. // }
  10293. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10294. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10295. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10296. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10297. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10298. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10299. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10300. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10301. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10302. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10303. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10304. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10305. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10306. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10307. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10308. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10309. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10310. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10311. if err != nil {
  10312. logs.Error(err)
  10313. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10314. return
  10315. }
  10316. if !ftexist {
  10317. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10318. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10319. if err != nil {
  10320. logs.Error(err)
  10321. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10322. return
  10323. }
  10324. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10325. if err != nil {
  10326. logs.Error(err)
  10327. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10328. return
  10329. }
  10330. }
  10331. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10332. if err != nil {
  10333. logs.Error(err)
  10334. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10335. return
  10336. }
  10337. if !exist {
  10338. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10339. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10340. if err != nil {
  10341. logs.Error(err)
  10342. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10343. return
  10344. }
  10345. }
  10346. var feedpargs []interface{}
  10347. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10348. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10349. if _, ok := dataexcel["ftname"]; ok {
  10350. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10351. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10352. // upFeedpSql += `,ftweight = ? `
  10353. // feedpargs = append(feedpargs, weight)
  10354. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10355. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10356. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10357. } else {
  10358. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10359. }
  10360. // if _, ok := dataexcel["ptsfname"]; ok {
  10361. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10362. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10363. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10364. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10365. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10366. // } else {
  10367. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10368. // }
  10369. upFeedpSql += " where barname = ? and pastureid = ? "
  10370. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10371. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10372. if err != nil {
  10373. logs.Error(err)
  10374. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10375. return
  10376. }
  10377. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10378. if err != nil {
  10379. logs.Error(err)
  10380. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10381. return
  10382. }
  10383. if !exist1 {
  10384. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10385. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10386. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10387. if err != nil {
  10388. logs.Error(err)
  10389. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10390. return
  10391. }
  10392. }
  10393. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10394. if err != nil {
  10395. logs.Error(err)
  10396. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10397. return
  10398. }
  10399. if !exist2 {
  10400. _, 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) `,
  10401. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10402. if err != nil {
  10403. logs.Error(err)
  10404. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10405. return
  10406. }
  10407. }
  10408. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10409. if err != nil {
  10410. logs.Error(err)
  10411. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10412. return
  10413. }
  10414. if !exist3 {
  10415. _, 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) `,
  10416. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10417. if err != nil {
  10418. logs.Error(err)
  10419. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10420. return
  10421. }
  10422. }
  10423. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10424. if err != nil {
  10425. logs.Error(err)
  10426. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10427. return
  10428. }
  10429. if !exist4 {
  10430. _, 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) `,
  10431. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10432. if err != nil {
  10433. logs.Error(err)
  10434. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10435. return
  10436. }
  10437. }
  10438. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  10439. if err != nil {
  10440. logs.Error(err)
  10441. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10442. return
  10443. }
  10444. if !exist5 {
  10445. _, 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) `,
  10446. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10447. if err != nil {
  10448. logs.Error(err)
  10449. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10450. return
  10451. }
  10452. }
  10453. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  10454. if err != nil {
  10455. logs.Error(err)
  10456. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10457. return
  10458. }
  10459. if !exist6 {
  10460. _, 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) `,
  10461. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10462. if err != nil {
  10463. logs.Error(err)
  10464. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10465. return
  10466. }
  10467. }
  10468. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10469. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10470. and pastureid = ? and times = ?`
  10471. var fpdargs1 []interface{}
  10472. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10473. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10474. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10475. if err != nil {
  10476. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10477. return
  10478. }
  10479. var fpdargs2 []interface{}
  10480. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10481. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10482. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10483. if err != nil {
  10484. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10485. return
  10486. }
  10487. var fpdargs3 []interface{}
  10488. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10489. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10490. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10491. if err != nil {
  10492. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10493. return
  10494. }
  10495. var fpdargs4 []interface{}
  10496. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10497. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10498. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10499. if err != nil {
  10500. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10501. return
  10502. }
  10503. var fpdargs5 []interface{}
  10504. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10505. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10506. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10507. if err != nil {
  10508. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10509. return
  10510. }
  10511. var fpdargs6 []interface{}
  10512. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10513. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10514. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10515. if err != nil {
  10516. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10517. return
  10518. }
  10519. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10520. 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()
  10521. if err != nil {
  10522. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10523. return
  10524. }
  10525. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10526. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10527. upFpdetailList := make([]*upFpdetail, 0)
  10528. for _, newfpd := range newList {
  10529. for _, oldfpd := range oldFpdList {
  10530. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10531. var oldweight, newweight float64
  10532. if oldfpd["weight"] != nil {
  10533. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10534. }
  10535. if newfpd["weight"] != nil {
  10536. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10537. }
  10538. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10539. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10540. Old: oldweight,
  10541. New: newweight,
  10542. Times: newfpd["times"].(int64),
  10543. Ptid: newfpd["ptid"].(int64),
  10544. Fweight: fweight,
  10545. Id: oldfpd["id"].(int64),
  10546. })
  10547. break
  10548. }
  10549. }
  10550. }
  10551. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10552. }
  10553. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10554. }
  10555. func FtImportExcel(c *gin.Context) {
  10556. appG := app.Gin{C: c}
  10557. inputdata := ""
  10558. c.Request.ParseForm()
  10559. params := c.Request.Form
  10560. file, _, err := c.Request.FormFile("file")
  10561. if err != nil {
  10562. appG.Response(http.StatusOK, e.ERROR, err)
  10563. return
  10564. }
  10565. sqlnamestrs := params.Get("name")
  10566. sheetname := params.Get("sheetname")
  10567. pastureid := params.Get("pastureid")
  10568. //importParams := params.Get("importParams")
  10569. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10570. // 必输项参数 (字符串格式 "field1,field2,field3")
  10571. requiredParams := params.Get("requiredParams")
  10572. // 日期参数
  10573. dateParams := params.Get("dateParams")
  10574. // 数字参数
  10575. numParams := params.Get("numParams")
  10576. //将字符串分割开
  10577. dateParamslist := strings.Split(dateParams, ",")
  10578. requiredParamslist := strings.Split(requiredParams, ",")
  10579. numParamslist := strings.Split(numParams, ",")
  10580. queryData := make([]interface{}, 0)
  10581. sqlslist := strings.Split(sqlnamestrs, ",")
  10582. xlsx1, err := excelize.OpenReader(file)
  10583. if err != nil {
  10584. fmt.Println(err)
  10585. return
  10586. }
  10587. ok := 0
  10588. error := 0
  10589. isdone := true
  10590. rows := xlsx1.GetRows(sheetname)
  10591. // 限制10000条,多余的截取掉
  10592. if len(rows) > 10000 {
  10593. rows = rows[:10000]
  10594. }
  10595. tx := restful.Engine.NewSession()
  10596. ftNameList := make(map[string]interface{})
  10597. var ftNames []interface{}
  10598. for i, row := range rows {
  10599. if i > 0 {
  10600. entry := make(map[string]interface{})
  10601. outentry := make(map[string]interface{})
  10602. for j, colCell := range rows[0] {
  10603. for k, colCell1 := range row {
  10604. if j == k {
  10605. outentry[colCell] = colCell1
  10606. entry[colCell] = colCell1
  10607. }
  10608. }
  10609. }
  10610. inputdata = ""
  10611. a := ""
  10612. fmt.Println(outentry, entry)
  10613. //校验日期格式
  10614. for _, v := range dateParamslist {
  10615. if v == "" {
  10616. continue
  10617. }
  10618. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10619. dtime, err := TransfTime(d.(string))
  10620. if err != nil {
  10621. a = strings.Trim(v, " ")
  10622. break
  10623. }
  10624. outentry[strings.Trim(v, " ")] = dtime
  10625. }
  10626. }
  10627. if a != "" {
  10628. outentry["error_msg"] = a + " 格式错误"
  10629. error++
  10630. queryData = append(queryData, outentry)
  10631. continue
  10632. }
  10633. a = ""
  10634. //校验必填格式
  10635. for _, v := range requiredParamslist {
  10636. if v == "" {
  10637. continue
  10638. }
  10639. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  10640. a = strings.Trim(v, " ")
  10641. break
  10642. }
  10643. }
  10644. if a != "" {
  10645. outentry["error_msg"] = a + " 未填或格式错误"
  10646. error++
  10647. queryData = append(queryData, outentry)
  10648. continue
  10649. }
  10650. a = ""
  10651. //校验数字格式
  10652. for _, v := range numParamslist {
  10653. if v == "" {
  10654. continue
  10655. }
  10656. d, ok := outentry[strings.Trim(v, " ")]
  10657. if !ok || d == "" {
  10658. outentry[strings.Trim(v, " ")] = 0
  10659. } else {
  10660. var fl float64
  10661. switch d.(type) {
  10662. case string:
  10663. fl, err = strconv.ParseFloat(d.(string), 64)
  10664. }
  10665. if err != nil || fl < 0 {
  10666. a = strings.Trim(v, " ")
  10667. break
  10668. }
  10669. }
  10670. }
  10671. if a != "" {
  10672. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  10673. error++
  10674. queryData = append(queryData, outentry)
  10675. continue
  10676. }
  10677. err := tx.Begin()
  10678. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  10679. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  10680. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  10681. }
  10682. for _, sqlnamestr := range sqlslist {
  10683. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  10684. paramslist := strings.Split(paramslists, ",")
  10685. if len(paramslist) > 0 {
  10686. s_params := make([]interface{}, 0)
  10687. for _, value := range paramslist {
  10688. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  10689. if tempv, exists := c.Get("jwt_username"); exists {
  10690. s_params = append(s_params, tempv.(string))
  10691. } else {
  10692. s_params = append(s_params, "")
  10693. }
  10694. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  10695. s_params = append(s_params, pastureid)
  10696. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  10697. ids, err := setting.SnowIds.NextId()
  10698. if err != nil {
  10699. ids = time.Now().UnixNano()
  10700. logging.Info("create SnowIds err", err)
  10701. }
  10702. s_params = append(s_params, ids)
  10703. } else {
  10704. if outentry[strings.Trim(value, " ")] == nil {
  10705. s_params = append(s_params, "")
  10706. } else {
  10707. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  10708. }
  10709. }
  10710. }
  10711. outentry["input"] = inputdata
  10712. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  10713. if err != nil {
  10714. if tx != nil {
  10715. tx.Rollback()
  10716. }
  10717. if tx != nil {
  10718. tx.Close()
  10719. }
  10720. msg := geterrmsg(err.Error())
  10721. outentry["error_msg"] = msg
  10722. error++
  10723. queryData = append(queryData, outentry)
  10724. isdone = true
  10725. break
  10726. } else {
  10727. if len(returnmsgmap1) > 0 {
  10728. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  10729. if tx != nil {
  10730. tx.Rollback()
  10731. }
  10732. if tx != nil {
  10733. tx.Close()
  10734. }
  10735. msg := geterrmsg(va.(string))
  10736. outentry["error_msg"] = msg
  10737. error++
  10738. queryData = append(queryData, outentry)
  10739. isdone = true
  10740. break
  10741. }
  10742. }
  10743. isdone = false
  10744. }
  10745. }
  10746. }
  10747. ftNames = append(ftNames, outentry["配方名称"])
  10748. switch {
  10749. case err != nil:
  10750. if tx != nil {
  10751. tx.Rollback()
  10752. }
  10753. default:
  10754. if tx != nil {
  10755. err = tx.Commit()
  10756. }
  10757. }
  10758. if tx != nil {
  10759. tx.Close()
  10760. }
  10761. }
  10762. if !isdone {
  10763. ok++
  10764. isdone = true
  10765. }
  10766. }
  10767. go ftSync(ftNames, pastureid)
  10768. data := make(map[string]interface{})
  10769. data["result"] = queryData
  10770. data["success"] = ok
  10771. data["err_count"] = error
  10772. appG.Response(http.StatusOK, e.SUCCESS, data)
  10773. }
  10774. func ftSync(ftNameList []interface{}, pastureId string) {
  10775. tx := restful.Engine.NewSession()
  10776. defer tx.Close()
  10777. for _, ftName := range ftNameList {
  10778. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  10779. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  10780. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  10781. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  10782. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  10783. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  10784. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  10785. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  10786. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, ftName).QueryString()
  10787. FpdBatchEditGrfd(pastureId, values1)
  10788. }
  10789. }
  10790. func CopyFeedtemplet(c *gin.Context) {
  10791. appG := app.Gin{C: c}
  10792. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10793. fsion := gofasion.NewFasion(string(dataByte))
  10794. pastureid := fsion.Get("pastureid").ValueStr()
  10795. newName := fsion.Get("newName").ValueStr()
  10796. id := fsion.Get("id").ValueStr()
  10797. tx := restful.Engine.NewSession()
  10798. defer tx.Close()
  10799. count, err := tx.SQL(` select count(1) from feedtemplet where tname = ? `, newName).Count()
  10800. if err != nil {
  10801. appG.Response(http.StatusOK, e.ERROR, err)
  10802. return
  10803. }
  10804. if count > 0 {
  10805. appG.Response(http.StatusOK, e.ERROR, "配方名称重复!")
  10806. return
  10807. }
  10808. type ftCode struct {
  10809. Tcode string `xorm:"tcode"`
  10810. }
  10811. code := new(ftCode)
  10812. err = tx.SQL(`select if(left((select max(tcode) from feedtemplet where pastureid = ?),8) =
  10813. (select DATE_FORMAT(now(),"%Y%m%d")),(select max(tcode)+1 from feedtemplet where pastureid = ?),
  10814. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))) tcode`, pastureid, pastureid).GetFirst(code).Error
  10815. if err != nil {
  10816. appG.Response(http.StatusOK, e.ERROR, err)
  10817. return
  10818. }
  10819. if code.Tcode == "" {
  10820. appG.Response(http.StatusOK, e.ERROR, "配方编码生产失败!")
  10821. return
  10822. }
  10823. _, err = tx.Exec(`INSERT INTO feedtemplet(pastureid,tname,tcode,tcolor,ccid,ccname,fttype,fttypeid,source,
  10824. remark,enable,sort,volume,autozone)
  10825. select pastureid,?,?,tcolor,ccid,ccname,fttype,fttypeid,source,
  10826. remark,enable,sort,volume,autozone from feedtemplet where id = ? `, newName, code.Tcode, id)
  10827. if err != nil {
  10828. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  10829. return
  10830. }
  10831. _, err = tx.Exec(`insert into ftdetail(pastureid,ftid,fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  10832. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry)
  10833. select pastureid,(select id from feedtemplet where tcode = ? ),fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  10834. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry
  10835. from ftdetail where ftid = ? `, code.Tcode, id)
  10836. if err != nil {
  10837. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  10838. return
  10839. }
  10840. appG.Response(http.StatusOK, e.SUCCESS, true)
  10841. }
  10842. func Test(c *gin.Context) {
  10843. appG := app.Gin{C: c}
  10844. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10845. appG.Response(http.StatusOK, e.SUCCESS, string(dataByte))
  10846. }
  10847. func GetPlanDry(c *gin.Context) {
  10848. appG := app.Gin{C: c}
  10849. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10850. fsion := gofasion.NewFasion(string(dataByte))
  10851. date := fsion.Get("date").ValueStr()
  10852. tx := restful.Engine.NewSession()
  10853. defer tx.Close()
  10854. dataList, err := tx.SQL(`SELECT
  10855. t.feedtempletName,
  10856. ifnull(t.feedtempletPrice,0)feedtempletPrice,
  10857. ifnull(t.feedtempletWeight,0)feedtempletWeight,
  10858. ifnull(t.feedtempletDryWeight,0)feedtempletDryWeight,
  10859. t.tmrno,
  10860. t.bname,
  10861. t.barid,
  10862. t.dry,
  10863. t.actualweightminus,
  10864. t.mydate,
  10865. t.pasturename,
  10866. t.endDate,
  10867. t.startDate,
  10868. t.times,
  10869. -- 计算startDate和endDate的中间时间
  10870. ifnull(DATE_FORMAT(
  10871. DATE_ADD(
  10872. t.startDate,
  10873. INTERVAL TIMESTAMPDIFF(SECOND, t.startDate, t.endDate)/2 SECOND
  10874. ),
  10875. '%Y-%m-%d %H:%i:%s'
  10876. ),'') AS midTime
  10877. FROM (
  10878. SELECT
  10879. (SELECT sort FROM downloadedplan WHERE pid = d.pid AND mydate = d.mydate AND lpplantype IN (0,1)) tmrno,
  10880. b.bname,
  10881. b.id barid,
  10882. 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
  10883. JOIN downloadplandtl1 dd1 ON dd.id = dd1.pid
  10884. JOIN feednur fn ON fn.fid = dd1.fid
  10885. WHERE dd.pid = d.pid AND dd.mydate = d.mydate AND lpplantype IN (0,1,4))/100),2) dry,
  10886. 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,
  10887. DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate,
  10888. p.pasture_name pastureName,
  10889. DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endDate,
  10890. DATE_FORMAT(IFNULL(
  10891. (SELECT MAX(intime) FROM downloadplandtl2 d1
  10892. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d1.intime<d2.intime),
  10893. (SELECT MAX(intime) FROM downloadplandtl1_exec de
  10894. WHERE de.date=d2.date AND de.pastureid = d2.pastureid AND de.pid=d2.pid)
  10895. ), '%Y-%m-%d %H:%i:%s') startDate,
  10896. d.times ,
  10897. ( SELECT
  10898. round(SUM(
  10899. IF(ftd.preftid<>0,
  10900. ftd.fweight*IFNULL((SELECT SUM(ftd1.fweight*f1.dry/100)/SUM(ftd1.fweight) FROM ftdetaildate ftd1
  10901. JOIN feednur f1 ON f1.fid= ftd1.fid AND f1.pastureid = ftd1.pastureid
  10902. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  10903. ftd.fweight*f.dry/100)) ,2)
  10904. dryweight
  10905. FROM ftdetaildate ftd
  10906. LEFT JOIN feednur f ON f.fid= ftd.fid AND f.pastureid = ftd.pastureid
  10907. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletDryWeight,(
  10908. select
  10909. sum(ftd.fweight)
  10910. FROM ftdetaildate ftd
  10911. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletWeight,
  10912. ( SELECT
  10913. round(SUM(
  10914. IF(ftd.preftid<>0,
  10915. IFNULL((SELECT SUM(ftd1.fweight*f1.uprice) FROM ftdetaildate ftd1
  10916. JOIN feed f1 ON f1.id= ftd1.fid AND f1.pastureid = ftd1.pastureid
  10917. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  10918. ftd.fweight*f.uprice)) ,2)
  10919. dryweight
  10920. FROM ftdetaildate ftd
  10921. LEFT JOIN feed f ON f.id= ftd.fid AND f.pastureid = ftd.pastureid
  10922. WHERE ftd.ftid = d.tempid and ftd.date = d2.date )
  10923. feedtempletPrice,d.templetname feedtempletName
  10924. FROM downloadedplan d
  10925. JOIN downloadplandtl2 d2 ON d.id=d2.PID
  10926. JOIN bar b ON b.id = d2.fbarid
  10927. JOIN pasture p ON p.pastureid = d.pastureid
  10928. WHERE d.mydate = DATE_FORMAT(?,'%Y-%m-%d')
  10929. AND d2.type = 0
  10930. AND d.havebutton = 1
  10931. ) t
  10932. WHERE 1=1 `, date).QueryString()
  10933. if err != nil {
  10934. logs.Error(err)
  10935. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  10936. return
  10937. }
  10938. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  10939. }
  10940. func GetBar(c *gin.Context) {
  10941. appG := app.Gin{C: c}
  10942. tx := restful.Engine.NewSession()
  10943. defer tx.Close()
  10944. pastureinfo := new(udPastureInfo)
  10945. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  10946. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  10947. if err != nil {
  10948. logs.Error(err)
  10949. return
  10950. }
  10951. dataList, err := tx.SQL(` select id,bname from bar where pastureid = ?`, pastureinfo.Pastureid).QueryString()
  10952. if err != nil {
  10953. logs.Error(err)
  10954. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  10955. return
  10956. }
  10957. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  10958. }
  10959. func GetHomepage(c *gin.Context) {
  10960. appG := app.Gin{C: c}
  10961. tx := restful.Engine.NewSession()
  10962. defer tx.Close()
  10963. dataList, err := tx.SQL(` SELECT
  10964. ifnull((SELECT CONCAT(ROUND(if(SUM(lweight) <= SUM(iweight),SUM(lweight)/SUM(iweight),SUM(iweight)/SUM(lweight))*100,2),'%') yesRateHL
  10965. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  10966. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) ),'0.00%')yesRateHL, -- 昨日混料准确率
  10967. (SELECT CONCAT(ROUND(SUM(iweight)/SUM(lweight)*100,2),'%') yesRateHL
  10968. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  10969. 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日混料准确率
  10970. ifnull((SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  10971. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  10972. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) ),'0.00%')yesRateSL, -- 昨日撒料准确率
  10973. (SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  10974. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  10975. 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日撒料准确率
  10976. 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),'%') -- 正确率
  10977. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  10978. WHERE dt.pastureid = d.pastureid AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')),'0.00%') yesRateSLR, -- 昨日正确率
  10979. (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),'%') -- 正确率
  10980. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  10981. WHERE dt.pastureid = d.pastureid
  10982. 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日正确率
  10983. (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,
  10984. (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,
  10985. 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,
  10986. 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,
  10987. ifnull(round(getSLtimeDiffSINGEL(d.pastureid,d.mydate),2),0.00) temtime,
  10988. ifnull(round(getSLtimeDiffMonth(d.pastureid) ,2),0.00) montime
  10989. FROM
  10990. (SELECT (select column_default as pastureid from information_schema.COLUMNS
  10991. 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()
  10992. if err != nil {
  10993. logs.Error(err)
  10994. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  10995. return
  10996. }
  10997. dataList1, err := tx.SQL(`select
  10998. 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
  10999. LEFT JOIN ftdetail ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1'
  11000. join feed f on f.id = ifnull(ftd.fid,d1.fid) where d1.date = date_format(now(),'%Y-%m-%d') `).QueryString()
  11001. if err != nil {
  11002. logs.Error(err)
  11003. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11004. return
  11005. }
  11006. for _, data := range dataList {
  11007. for _, data1 := range dataList1 {
  11008. data["totalCost"] = data1["totalCost"]
  11009. data["cost"] = data1["cost"]
  11010. }
  11011. }
  11012. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11013. }
  11014. func GetFeedingManagement(c *gin.Context) {
  11015. appG := app.Gin{C: c}
  11016. typea := c.Query("typea") // 0 栏舍 1 日期
  11017. startDate := c.Query("startdate")
  11018. endDate := c.Query("enddate")
  11019. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11020. // fsion := gofasion.NewFasion(string(dataByte))
  11021. tx := restful.Engine.NewSession()
  11022. defer tx.Close()
  11023. if typea == "0" {
  11024. 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
  11025. SUM(
  11026. 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 ,
  11027. 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)*
  11028. 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 )),
  11029. 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)*
  11030. 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 ))
  11031. )
  11032. )actualweightminus ,
  11033. SUM(
  11034. 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 ,
  11035. 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)*
  11036. 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 )),
  11037. 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)*
  11038. 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 ))
  11039. ) * ifnull(fn.dry,0)
  11040. ) dryweight , SUM(
  11041. 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 ,
  11042. 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)*
  11043. 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 )),
  11044. 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)*
  11045. 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 ))
  11046. ) * ifnull(f.uprice,0)
  11047. ) priceweight
  11048. ,(select ccount from feedpdate where date = d1.date and barid = d2.fbarid) ccount,b.bname
  11049. FROM
  11050. downloadedplan d
  11051. JOIN downloadplandtl2 d2
  11052. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11053. JOIN downloadplandtl1 d1
  11054. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11055. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11056. 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
  11057. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11058. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11059. left join feednur fn on fn.fid = f.id
  11060. WHERE d.mydate BETWEEN ? AND ? GROUP BY d2.fbarid ) t `, startDate, endDate).QueryString()
  11061. if err != nil {
  11062. logs.Error(err)
  11063. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11064. return
  11065. }
  11066. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11067. } else {
  11068. 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
  11069. SUM(
  11070. 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 ,
  11071. 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)*
  11072. 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 )),
  11073. 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)*
  11074. 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 ))
  11075. )
  11076. )actualweightminus ,
  11077. SUM(
  11078. 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 ,
  11079. 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)*
  11080. 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 )),
  11081. 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)*
  11082. 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 ))
  11083. ) * ifnull(fn.dry,0)
  11084. ) dryweight , SUM(
  11085. 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 ,
  11086. 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)*
  11087. 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 )),
  11088. 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)*
  11089. 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 ))
  11090. ) * ifnull(f.uprice,0)
  11091. ) priceweight
  11092. ,(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
  11093. FROM
  11094. downloadedplan d
  11095. JOIN downloadplandtl2 d2
  11096. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11097. JOIN downloadplandtl1 d1
  11098. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11099. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11100. 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
  11101. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11102. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11103. left join feednur fn on fn.fid = f.id
  11104. WHERE d.mydate BETWEEN ? AND ?
  11105. GROUP BY d.mydate) t `, startDate, endDate).QueryString()
  11106. if err != nil {
  11107. logs.Error(err)
  11108. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11109. return
  11110. }
  11111. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11112. }
  11113. }
  11114. func GetFpdetailFname(c *gin.Context) {
  11115. appG := app.Gin{C: c}
  11116. // id := c.Query("id")
  11117. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11118. fsion := gofasion.NewFasion(string(dataByte))
  11119. id := fsion.Get("id").ValueDefaultStr("")
  11120. tx := restful.Engine.NewSession()
  11121. defer tx.Close()
  11122. fpdetailFnameList := make([]*models.FpdetailFname, 0)
  11123. err := tx.SQL(` SELECT
  11124. TRIM(ftid)ftid,TRIM(fid)fid,
  11125. IFNULL((SELECT fname FROM feed WHERE pastureid =ftdetail.pastureid AND id = ftdetail.fid),ftdetail. fname) fname,
  11126. fweight,sort,
  11127. TRIM(ftdetail.id) id, fweight /(select sum(fweight) from ftdetail where ftid = (select ftid from feedp where barid = ? ) ) sumFweight
  11128. FROM
  11129. ftdetail
  11130. WHERE ( ftid=(select ftid from feedp where barid = ? )) AND is_show = 1
  11131. ORDER BY ftdetail.sort,ftdetail.id `, id, id).Find(&fpdetailFnameList)
  11132. if err != nil {
  11133. logs.Error(err)
  11134. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11135. return
  11136. }
  11137. fpdetailList := make([]*models.Fpdetail, 0)
  11138. err = tx.SQL(`select id,barid,barname,times,weight from fpdetail where barid = ?`, id).Find(&fpdetailList)
  11139. if err != nil {
  11140. logs.Error(err)
  11141. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11142. return
  11143. }
  11144. for _, f := range fpdetailFnameList {
  11145. f.FWeight = 0
  11146. for _, fpd := range fpdetailList {
  11147. value := f.SumFWeight * fpd.Weight
  11148. // 将其四舍五入到小数点后两位
  11149. roundedValue := math.Round(value*100) / 100
  11150. if fpd.Times == 1 {
  11151. f.TimesOne = roundedValue
  11152. } else if fpd.Times == 2 {
  11153. f.TimesTwo = roundedValue
  11154. } else if fpd.Times == 3 {
  11155. f.TimesThree = roundedValue
  11156. } else if fpd.Times == 4 {
  11157. f.TimesFour = roundedValue
  11158. } else if fpd.Times == 5 {
  11159. f.TimesFive = roundedValue
  11160. } else if fpd.Times == 6 {
  11161. f.TimesSix = roundedValue
  11162. }
  11163. f.FWeight += value
  11164. }
  11165. }
  11166. fpdetailFname := new(models.FpdetailFname)
  11167. fpdetailFname.FName = "合计"
  11168. for _, f := range fpdetailFnameList {
  11169. fpdetailFname.TimesOne += f.TimesOne
  11170. fpdetailFname.TimesTwo += f.TimesTwo
  11171. fpdetailFname.TimesThree += f.TimesThree
  11172. fpdetailFname.TimesFour += f.TimesFour
  11173. fpdetailFname.TimesFive += f.TimesFive
  11174. fpdetailFname.TimesSix += f.TimesSix
  11175. fpdetailFname.FWeight += f.FWeight
  11176. f.FWeight = RoundFloat(f.FWeight, 2)
  11177. }
  11178. // 在处理代码中
  11179. fpdetailFname.TimesOne = RoundFloat(fpdetailFname.TimesOne, 2)
  11180. fpdetailFname.TimesTwo = RoundFloat(fpdetailFname.TimesTwo, 2)
  11181. fpdetailFname.TimesThree = RoundFloat(fpdetailFname.TimesThree, 2)
  11182. fpdetailFname.TimesFour = RoundFloat(fpdetailFname.TimesFour, 2)
  11183. fpdetailFname.TimesFive = RoundFloat(fpdetailFname.TimesFive, 2)
  11184. fpdetailFname.TimesSix = RoundFloat(fpdetailFname.TimesSix, 2)
  11185. fpdetailFname.FWeight = RoundFloat(fpdetailFname.FWeight, 2)
  11186. fpdetailFnameList = append(fpdetailFnameList, fpdetailFname)
  11187. appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11188. }
  11189. func RoundFloat(x float64, prec int) float64 {
  11190. output := math.Pow(10, float64(prec))
  11191. return math.Round(x*output) / output
  11192. }
  11193. func GetLyUdData(c *gin.Context) {
  11194. appG := app.Gin{C: c}
  11195. // id := c.Query("id")
  11196. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11197. fsion := gofasion.NewFasion(string(dataByte))
  11198. myDate := fsion.Get("myDate").ValueDefaultStr("")
  11199. times := fsion.Get("Times").ValueDefaultStr("")
  11200. name := fsion.Get("name").ValueDefaultStr("")
  11201. tx := restful.Engine.NewSession()
  11202. defer tx.Close()
  11203. if name == "dateplanlist"{
  11204. data ,err := tx.SQL(`select dl.id as did,if(dl.HaveButton=1,1,0) isDo, dl.id as id,dl.ProjName,dl.tmrtname TNAME, '' DNAME,DATE_FORMAT(dl.Mydate,'%Y-%m-%d') Mydate,d2.xxwTempletCode fId,dl.templetName fName, DATE_FORMAT(dl.InTime,'%Y-%m-%d %H:%i:%s') benginTime,DATE_FORMAT(max(d2.Intime),'%Y-%m-%d %H:%i:%s') endDate, dl.Times as Times, dl.Sort ,'是' Status, p.pasturecode kptCattleId from downloadedplan dl
  11205. join pasture p on dl.pastureId=p.pastureid JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId
  11206. where dl.Mydate = ? AND dl.lpplanType =0 and dl.Times= ? GROUP BY dl.id union all
  11207. select dd.id as did,if(dd.HaveButton=1,1,0) isDo, dd.id as id,dd.ProjName,dd.tmrtname TNAME, '' DNAME,DATE_FORMAT(dd.Mydate,'%Y-%m-%d') Mydate,d2.xxwTempletCode fId,dd.templetName fName, DATE_FORMAT(dd.InTime,'%Y-%m-%d %H:%i:%s') benginTime,DATE_FORMAT(max(d2.Intime),'%Y-%m-%d %H:%i:%s') endDate, dd.Times as Times, dd.Sort ,'是' Status, p.pasturecode kptCattleId
  11208. from downloadedplan dl join pasture p on dl.pastureId=p.pastureid
  11209. JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId inner join downloadedplan dd on dd.pid=dl.pid and dd.mydate=dl.mydate and dd.lpplanType=1 and dl.pastureId=dd.pastureId
  11210. where dl.Mydate = ? AND dl.lpplanType =2 and dl.Times= ?
  11211. GROUP BY dl.id order by ProjName `,myDate,times,myDate,times).Query().List()
  11212. fmt.Println(err )
  11213. appG.Response(http.StatusOK, e.SUCCESS, data)
  11214. return
  11215. }else if name == "getAddFeed"{
  11216. data ,_:= tx.SQL(`SELECT IF(d.HaveButton=1,1,0) isDo,d.id did,d.ProjName ProjName,date_format(d.mydate,'%Y-%m-%d') loadDate,d.Sort tmrNo,d.Times Times,ftd.xxwTempletCode fId,ftd.tname fName,d.tmrtname TNAME,f.fname FNAME, f.xxwFeedCode feedId,d1.SORT SORT,d1.feedallowratio allowableError,(select round(sum(if(ActualWeightMinus>0,ActualWeightMinus,0)),2) from downloadplandtl1 where PID = d.id and pastureId = d.pastureId ) LWEIGHT,
  11217. round(d1.lweight,2) expWeight,round(if(d1.actualweightminus>0,d1.actualweightminus,0),2) actualWeight,'' DNAME,if((select count(1) from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc) >0 ,(select DATE_FORMAT(InTime,'%Y-%m-%d %H:%i:%s') from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc limit 1),DATE_FORMAT(d.InTime,'%Y-%m-%d %H:%i:%s') ) startTime,
  11218. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM downloadedplan dd
  11219. JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11220. inner join downloadedplan d on dd.pid=d.pid and dd.mydate=d.mydate and d.lpplanType in (0,1) AND d.pastureId = dd.pastureId
  11221. join feedtemplet ftd on ftd.id = d.tempid and ftd.pastureId = d.pastureId
  11222. JOIN feed f ON f.id = d1.fid AND f.pastureId = d.pastureId
  11223. WHERE DATE_FORMAT(dd.Mydate ,'%Y-%m-%d' ) = ? and dd.Times =? and d1.type = 0
  11224. UNION ALL SELECT IF(d.HaveButton=1,1,0) isDo,d.id did,d.ProjName ProjName,date_format(d.mydate,'%Y-%m-%d') loadDate,d.Sort tmrNo,d.Times Times,ftd.xxwTempletCode fId,ftd.tname fName,d.tmrtname TNAME,f.fname FNAME, f.xxwFeedCode feedId,d1.SORT SORT,d1.feedallowratio allowableError,(select round(sum(if(ActualWeightMinus>0,ActualWeightMinus,0)),2) from downloadplandtl1 where PID = d.id and pastureId = d.pastureId and type = 0) LWEIGHT,
  11225. round(d1.LWEIGHT *(ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and ftid = ftdd.ftid and pastureId = d.pastureId )),2) expWeight,
  11226. round((if(d1.ActualWeightMinus>0,d1.ActualWeightMinus,0)) * (ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and pastureId = d.pastureId and ftid = ftdd.ftid )),2) actualWeight,
  11227. '' DNAME ,if((select count(1) from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc) >0 ,(select DATE_FORMAT(InTime,'%Y-%m-%d %H:%i:%s') from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc limit 1),DATE_FORMAT(d.InTime,'%Y-%m-%d %H:%i:%s') ) startTime,
  11228. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM
  11229. downloadedplan dd JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11230. inner join downloadedplan d on dd.pid=d.pid and dd.mydate=d.mydate and d.lpplanType in (0,1) AND d.pastureId = dd.pastureId
  11231. join feedtemplet ftd on ftd.id = d1.fid and ftd.pastureId = d.pastureId
  11232. join ftdetaildate ftdd on ftdd.ftid = ftd.id and ftdd.date = d.Mydate and ftdd.pastureId = d.pastureId
  11233. join feed f on f.id = ftdd.fid and f.pastureId = d.pastureId
  11234. WHERE DATE_FORMAT( dd.Mydate ,'%Y-%m-%d' ) = ? AND dd.Times = ? and d1.type = 0 and d1.feedcode = -1 `,myDate,times,myDate,times).Query().List()
  11235. appG.Response(http.StatusOK, e.SUCCESS, data)
  11236. return
  11237. }else if name == "getDeleteFeed"{
  11238. data ,_:= tx.SQL(`SELECT if(d.HaveButton=1,1,0) isDo,date_format(d.mydate,'%Y-%m-%d') as dropDate,d.SORT as tmrNo,d.Times as Times, d2.Fname as penName,d2.cowcount as cowCount,d.tmrtname TNAME, d2.SORT as SORT, d2.LWEIGHT as expWeight,if(d2.ActualWeightMinus>0,d2.ActualWeightMinus,0) as actualWeight,
  11239. date_format(timestamp(d2.InTime,CONCAT('-',d2.processTime)),'%Y-%m-%d %H:%i:%s') as startTime, date_format(d2.InTime,'%Y-%m-%d %H:%i:%s') as endTime,'' as DNAME ,
  11240. (select ProjName from downloadedplan dd where dd.pid=d.pid and dd.mydate=d.mydate and dd.lpplanType in (0,1) AND d.pastureId = dd.pastureId) ProjName
  11241. ,d2.xxwBarCode as penId,if(d.lpplanType=2,(select id from downloadedplan p where p.pid=d.pid and p.mydate=? and p.Times=?
  11242. and p.lpplanType=1 limit 1),d2.pid) Id from downloadedplan d LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID
  11243. and d.pastureId=d2.pastureId where d.mydate=? AND d.lpplanType in (0,2) and d.Times=?`,myDate,times,myDate,times).Query().List()
  11244. appG.Response(http.StatusOK, e.SUCCESS, data)
  11245. return
  11246. }
  11247. // appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11248. }