ops.go 432 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "os"
  12. "path"
  13. "regexp"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. "tmr-watch/conf/setting"
  20. "tmr-watch/http/handle/jpud"
  21. "tmr-watch/http/handle/restful"
  22. "tmr-watch/http/handle/ymy"
  23. "tmr-watch/models"
  24. "tmr-watch/module"
  25. "tmr-watch/pkg/app"
  26. "tmr-watch/pkg/e"
  27. "tmr-watch/pkg/logging"
  28. "github.com/360EntSecGroup-Skylar/excelize"
  29. "github.com/Anderson-Lu/gofasion/gofasion"
  30. "github.com/astaxie/beego/logs"
  31. "github.com/gin-gonic/gin"
  32. "github.com/qichengzx/coordtransform"
  33. "github.com/tealeg/xlsx"
  34. "github.com/xormplus/xorm"
  35. excelizexuri "github.com/xuri/excelize/v2"
  36. )
  37. // @Summary 根据SQL执行得到数据集
  38. // @Tags getData
  39. // @Accept json
  40. // @Produce json
  41. // @Param sql query string true "sql"
  42. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  43. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  44. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  45. // @Router /data/getdata [POST]
  46. func GetData(c *gin.Context) {
  47. appG := app.Gin{C: c}
  48. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  49. fsion := gofasion.NewFasion(string(dataByte))
  50. sqlstr := fsion.Get("sql").ValueStr()
  51. offset := fsion.Get("offset").ValueDefaultInt(0)
  52. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  53. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  54. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  55. if err != nil {
  56. appG.Response(http.StatusOK, e.ERROR, err.Error())
  57. } else {
  58. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  59. }
  60. }
  61. func Testpartitions(c *gin.Context) {
  62. appG := app.Gin{C: c}
  63. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  64. fsion := gofasion.NewFasion(string(dataByte))
  65. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  66. user := fsion.Get("user").ValueStr() //获取新数据库用户
  67. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  68. host := fsion.Get("host").ValueStr() //获取新数据库名称
  69. port := fsion.Get("port").ValueStr() //获取新数据库名称
  70. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  71. if sqls == nil || err1 != nil {
  72. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  73. }
  74. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  75. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  76. mydb, err := sql.Open("mysql", connecting) //连接新连接
  77. if err != nil {
  78. println("err1", err.Error())
  79. }
  80. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  81. if err != nil {
  82. println("err2", err.Error())
  83. }
  84. mydb.Close()
  85. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  86. mydb, err = sql.Open("mysql", connecting)
  87. if err != nil {
  88. println("err3", err.Error())
  89. }
  90. defer mydb.Close()
  91. if err == nil {
  92. mydb.SetMaxOpenConns(10)
  93. mydb.SetMaxIdleConns(10)
  94. }
  95. errmsg := ""
  96. if err == nil {
  97. //tx ,_ :=mydb.Begin()
  98. for _, sqlstr := range sqlstrs {
  99. //println("sqlstr---",sqlstr)
  100. if sqlstr == "" {
  101. continue
  102. }
  103. _, err = mydb.Exec(sqlstr)
  104. if err != nil {
  105. println("err4", err.Error())
  106. errmsg = err.Error()
  107. //err1 :=tx.Rollback()
  108. }
  109. }
  110. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  111. //err =tx.Commit()
  112. }
  113. if errmsg == "" {
  114. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  115. } else {
  116. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  117. }
  118. }
  119. func TestData(c *gin.Context) {
  120. appG := app.Gin{C: c}
  121. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  122. fsion := gofasion.NewFasion(string(dataByte))
  123. sqlstr := fsion.Get("sql").ValueStr()
  124. token := ""
  125. if tempv, exists := c.Get("jwt_username"); exists {
  126. token = tempv.(string)
  127. }
  128. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  129. }
  130. // @Summary 根据APISQL表中SQL执行得到数据集
  131. // @Tags GetDataByName
  132. // @Accept json
  133. // @Produce json
  134. // @Param sqlname body string true "sqlname"
  135. // @Param offset body int true "offset"
  136. // @Param pagecount body int true "pagecount"
  137. // @Param returntype body string true "returntype"
  138. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  139. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  140. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  141. // @Router /data/GetDataByName [POST]
  142. func GetDataByName(c *gin.Context) {
  143. appG := app.Gin{C: c}
  144. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  145. fsion := gofasion.NewFasion(string(dataByte))
  146. sqlnamestr := fsion.Get("name").ValueStr()
  147. offset := fsion.Get("offset").ValueDefaultInt(0)
  148. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  149. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  150. tx := restful.Engine.NewSession()
  151. err := tx.Begin()
  152. defer func() {
  153. switch {
  154. case err != nil:
  155. logging.Error("tx.Begin 事务启动失败__error:", err)
  156. if tx != nil {
  157. tx.Rollback()
  158. }
  159. default:
  160. if tx != nil {
  161. err = tx.Commit()
  162. }
  163. }
  164. if tx != nil {
  165. tx.Close()
  166. }
  167. }()
  168. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  169. if sql != "" {
  170. s_params := make([]interface{}, 0)
  171. if fsion.HasKey("parammaps") {
  172. parammaps := fsion.Get("parammaps")
  173. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  174. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  175. }
  176. paramslist := strings.Split(p, ",")
  177. if len(paramslist) > 0 && p != "" {
  178. for _, value := range paramslist {
  179. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  180. if tempv, exists := c.Get("jwt_username"); exists {
  181. s_params = append(s_params, tempv.(string))
  182. } else {
  183. s_params = append(s_params, "")
  184. }
  185. } else {
  186. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  187. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  188. // tmrNameList := []string{}
  189. // for _, tmr := range tmrArray {
  190. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  191. // }
  192. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  193. // } else {
  194. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  195. // }
  196. }
  197. }
  198. }
  199. } else if fsion.HasKey("params") {
  200. params := fsion.Get("params").Array()
  201. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  202. for _, v_params := range params {
  203. s_params = append(s_params, v_params.ValueStr())
  204. }
  205. }
  206. if returntype == "xlsx" {
  207. var xlsxfile *xlsx.File
  208. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  209. //c.File("c:/dd.xlsx")
  210. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  211. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  212. c.Header("Content-Transfer-Encoding", "binary")
  213. _ = xlsxfile.Write(c.Writer)
  214. } else {
  215. if sqlnamestr == "getHomepageStr" {
  216. parammaps := fsion.Get("parammaps")
  217. pastureid := parammaps.Get("pastureid").ValueStr()
  218. var montimeList []float64
  219. var montime float64
  220. var wg sync.WaitGroup
  221. now := time.Now()
  222. for i := 0; i < 30; i++ {
  223. wg.Add(1)
  224. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  225. go func(nowstr string) {
  226. defer wg.Done()
  227. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  228. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  229. if len(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})) > 0 {
  230. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  231. montimeList = append(montimeList, m)
  232. }
  233. }(nowstr)
  234. }
  235. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  236. if err != nil {
  237. logging.Error("GetDataByName err: ", err)
  238. msg := geterrmsg(err.Error())
  239. appG.Response(http.StatusOK, e.ERROR, msg)
  240. }
  241. wg.Wait()
  242. for _, m := range montimeList {
  243. montime += m
  244. }
  245. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  246. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  247. return
  248. }
  249. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  250. if err != nil {
  251. logging.Error("GetDataByName err: ", err)
  252. msg := geterrmsg(err.Error())
  253. appG.Response(http.StatusOK, e.ERROR, msg)
  254. } else {
  255. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  256. }
  257. }
  258. } else {
  259. appG.Response(http.StatusOK, e.SUCCESS, nil)
  260. }
  261. }
  262. // @Summary 根据APISQL表中SQL执行得到数据集
  263. // @Tags GetDataByName
  264. // @Accept json
  265. // @Produce json
  266. // @Param sqlname body string true "sqlname"
  267. // @Param offset body int true "offset"
  268. // @Param pagecount body int true "pagecount"
  269. // @Param returntype body string true "returntype"
  270. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  271. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  272. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  273. // @Router /data/GetDataByName [POST]
  274. func GetDataBySqlIN(c *gin.Context) {
  275. appG := app.Gin{C: c}
  276. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  277. fsion := gofasion.NewFasion(string(dataByte))
  278. sqlnamestr := fsion.Get("name").ValueStr()
  279. offset := fsion.Get("offset").ValueDefaultInt(0)
  280. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  281. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  282. tx := restful.Engine.NewSession()
  283. err := tx.Begin()
  284. defer func() {
  285. switch {
  286. case err != nil:
  287. logging.Error("tx.Begin 事务启动失败__error:", err)
  288. if tx != nil {
  289. tx.Rollback()
  290. }
  291. default:
  292. if tx != nil {
  293. err = tx.Commit()
  294. }
  295. }
  296. if tx != nil {
  297. tx.Close()
  298. }
  299. }()
  300. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  301. if sql != "" {
  302. s_params := make([]interface{}, 0)
  303. if fsion.HasKey("parammaps") {
  304. parammaps := fsion.Get("parammaps")
  305. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  306. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  307. }
  308. paramslist := strings.Split(p, ",")
  309. if len(paramslist) > 0 && p != "" {
  310. for _, value := range paramslist {
  311. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  312. if tempv, exists := c.Get("jwt_username"); exists {
  313. s_params = append(s_params, tempv.(string))
  314. } else {
  315. s_params = append(s_params, "")
  316. }
  317. } else {
  318. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  319. }
  320. }
  321. }
  322. } else if fsion.HasKey("params") {
  323. params := fsion.Get("params").Array()
  324. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  325. for _, v_params := range params {
  326. s_params = append(s_params, v_params.ValueStr())
  327. }
  328. }
  329. if returntype == "xlsx" {
  330. var xlsxfile *xlsx.File
  331. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  332. //c.File("c:/dd.xlsx")
  333. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  334. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  335. c.Header("Content-Transfer-Encoding", "binary")
  336. _ = xlsxfile.Write(c.Writer)
  337. } else {
  338. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  339. if err != nil {
  340. logging.Error("GetDataByName err: ", err)
  341. msg := geterrmsg(err.Error())
  342. appG.Response(http.StatusOK, e.ERROR, msg)
  343. } else {
  344. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  345. }
  346. }
  347. } else {
  348. appG.Response(http.StatusOK, e.SUCCESS, nil)
  349. }
  350. }
  351. // 错误处理
  352. // 将报错信息处理成汉字
  353. func geterrmsg(errstr string) (msgstr string) {
  354. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  355. rs := []rune(errstr)
  356. if hzRegexp.MatchString(string(rs[0])) {
  357. msgstr = errstr
  358. return
  359. }
  360. if strings.Contains(errstr, "Duplicate entry") {
  361. strs := strings.Split(errstr, ` key '`)
  362. if len(strs) > 1 {
  363. if len(strs[len(strs)-1]) > 1 {
  364. errstr = "Duplicate entry :" + strs[len(strs)-1]
  365. }
  366. }
  367. }
  368. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  369. if err != nil {
  370. msgstr = errstr
  371. return
  372. }
  373. if msg == nil || len(msg) == 0 {
  374. var param []interface{}
  375. param = append(param, errstr, errstr)
  376. go func() {
  377. tx := restful.Engine.NewSession()
  378. err := tx.Begin()
  379. defer func() {
  380. switch {
  381. case err != nil:
  382. logging.Error("tx.Begin 事务启动失败__error:", err)
  383. if tx != nil {
  384. tx.Rollback()
  385. }
  386. default:
  387. if tx != nil {
  388. err = tx.Commit()
  389. }
  390. }
  391. if tx != nil {
  392. tx.Close()
  393. }
  394. }()
  395. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  396. if err != nil {
  397. logging.Error("insert into err_msg(err,msg) err", err)
  398. }
  399. }()
  400. msgstr = errstr
  401. } else {
  402. msgstr = msg[0]["msg"]
  403. }
  404. return
  405. }
  406. // @Summary 根据APISQL表中SQL执行得到数据集
  407. // @Tags GetDataByNameForm
  408. // @Accept json
  409. // @Produce json
  410. // @Param sqlname body json true "sqlname"
  411. // @Param offset query int true "offset"
  412. // @Param pagecount query int true "pagecount"
  413. // @Param returntype query string true "returntype"
  414. // @Param s formData json true "ss"
  415. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  416. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  417. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  418. // @Router /data/GetDataByNameForm [POST]
  419. func GetDataByNameForm(c *gin.Context) {
  420. appG := app.Gin{C: c}
  421. //sqlnamestr := c.PostForm("measureNumber")
  422. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  423. //fsion := gofasion.NewFasion(string(dataByte))
  424. //sqlnamestr := fsion.Get("name").ValueStr()
  425. //offset := fsion.Get("offset").ValueInt()
  426. //pagecount := fsion.Get("pagecount").ValueInt()
  427. //returntype := fsion.Get("returntype").ValueStr()
  428. //params := fsion.Get("params").Array()
  429. c.Request.ParseForm()
  430. params := c.Request.Form
  431. offset := 0
  432. pageSize_ := 0
  433. returntype := params.Get("page")
  434. if returntype == "" {
  435. returntype = "0"
  436. }
  437. if tempv, exists := c.Get("jwt_username"); exists {
  438. params.Set("JwtUserName", tempv.(string))
  439. } else {
  440. params.Set("JwtUserName", "")
  441. }
  442. sqlnamestr := params.Get("name")
  443. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  444. s_params := make([]interface{}, 0)
  445. if returntype == "1" {
  446. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  447. if error != nil {
  448. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  449. }
  450. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  451. if error != nil {
  452. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  453. }
  454. pageSize_ = pageSize
  455. offset = pageNum
  456. }
  457. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  458. paramslist := strings.Split(p, ",")
  459. if len(paramslist) > 0 && p != "" {
  460. for _, value := range paramslist {
  461. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  462. }
  463. }
  464. if sql != "" {
  465. if returntype == "xlsx" {
  466. var xlsxfile *xlsx.File
  467. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  468. c.Header("Content-Type", "application/octet-stream")
  469. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  470. c.Header("Content-Transfer-Encoding", "binary")
  471. _ = xlsxfile.Write(c.Writer)
  472. } else {
  473. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  474. if err != nil {
  475. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  476. } else {
  477. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  478. }
  479. }
  480. } else {
  481. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  482. }
  483. }
  484. // @Summary 递归获取所有
  485. // @Tags menu
  486. // @Accept json
  487. // @Produce json
  488. // @Param Ton query string true "Ton"
  489. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  490. // @Router /authdata/GetRoleMenus [GET]
  491. func GetRecuDataByName(c *gin.Context) {
  492. appG := app.Gin{C: c}
  493. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  494. fsion := gofasion.NewFasion(string(dataByte))
  495. sqlnamestr := fsion.Get("name").ValueStr()
  496. parentidname := fsion.Get("idname").ValueStr()
  497. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  498. params := make(map[string]interface{})
  499. s_params := make([]interface{}, 0)
  500. if fsion.HasKey("params") {
  501. for _, v_params := range fsion.Get("params").Array() {
  502. s_params = append(s_params, v_params.ValueStr())
  503. }
  504. params["params"] = s_params
  505. } else {
  506. jparams := fsion.Get("parammaps")
  507. paramslist := strings.Split(p, ",")
  508. if len(paramslist) > 0 && p != "" {
  509. for _, value := range paramslist {
  510. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  511. if tempv, exists := c.Get("jwt_username"); exists {
  512. params[value] = tempv.(string)
  513. } else {
  514. params[value] = ""
  515. }
  516. } else {
  517. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  518. }
  519. }
  520. }
  521. }
  522. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  523. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  524. if err != nil {
  525. appG.Response(http.StatusOK, e.ERROR, err.Error())
  526. }
  527. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  528. }
  529. // @Summary 根据APISQL表中SQL执行得到数据集
  530. // @Tags GetDataByNames
  531. // @Accept json
  532. // @Produce json
  533. // @RequestBody sqlname query string true "sqlname"
  534. // @Param offset query int true "offset"
  535. // @Param pagecount query int true "pagecount"
  536. // @Param returntype query string true "returntype"
  537. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  538. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  539. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  540. // @Router /data/GetDataByNames [POST]
  541. func GetDataByNames(c *gin.Context) {
  542. appG := app.Gin{C: c}
  543. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  544. fsion := gofasion.NewFasion(string(dataByte))
  545. sqlParams := fsion.Array()
  546. queryData := make(map[string]interface{})
  547. for _, v := range sqlParams {
  548. fsion2 := gofasion.NewFasion(v.Json())
  549. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  550. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  551. if sql == "" {
  552. errorm := make(map[string]interface{})
  553. errorm["code"] = e.ERROR
  554. errorm["message"] = "sql没找到"
  555. queryData[fsion2.Get("name").ValueStr()] = errorm
  556. continue
  557. } else if sql != "" {
  558. offset := fsion2.Get("offset").ValueInt()
  559. pagecount := fsion2.Get("pagecount").ValueInt()
  560. returntype := fsion2.Get("returntype").ValueStr()
  561. s_params := make([]interface{}, 0)
  562. if fsion2.HasKey("parammaps") {
  563. parammaps := fsion2.Get("parammaps")
  564. paramslist := strings.Split(p, ",")
  565. if len(paramslist) > 0 && p != "" {
  566. for _, value := range paramslist {
  567. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  568. if tempv, exists := c.Get("jwt_username"); exists {
  569. s_params = append(s_params, tempv.(string))
  570. } else {
  571. s_params = append(s_params, "")
  572. }
  573. } else {
  574. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  575. }
  576. }
  577. }
  578. } else if fsion2.HasKey("params") {
  579. params := fsion2.Get("params").Array()
  580. for _, v_params := range params {
  581. s_params = append(s_params, v_params.ValueStr())
  582. }
  583. }
  584. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  585. if err != nil {
  586. errorm := make(map[string]interface{})
  587. errorm["code"] = e.ERROR
  588. errorm["message"] = err.Error()
  589. queryData[fsion2.Get("name").ValueStr()] = errorm
  590. logging.Error("GetDataByNames err: ", err)
  591. continue
  592. } else {
  593. queryData[fsion2.Get("name").ValueStr()] = queryData1
  594. }
  595. }
  596. }
  597. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  598. }
  599. // @Summary 根据APISQL表中SQL执行得到数据集
  600. // @Tags PostDataByNameForm
  601. // @Accept json
  602. // @Produce json
  603. // @Param sqlname query string true "sqlname"
  604. // @Param offset query int true "offset"
  605. // @Param pagecount query int true "pagecount"
  606. // @Param returntype query string true "returntype"
  607. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  608. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  609. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  610. // @Router /data/PostDataByNameForm [POST]
  611. func PostDataByNameForm(c *gin.Context) {
  612. appG := app.Gin{C: c}
  613. c.Request.ParseForm()
  614. params := c.Request.Form
  615. sqlnamestr := params.Get("name")
  616. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  617. s_params := make([]interface{}, 0)
  618. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  619. paramslist := strings.Split(p, ",")
  620. if len(paramslist) > 0 {
  621. for _, value := range paramslist {
  622. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  623. }
  624. }
  625. if sql != "" {
  626. queryData, err := execDataBySql(sql, s_params)
  627. if err != nil {
  628. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  629. } else {
  630. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  631. }
  632. } else {
  633. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  634. }
  635. }
  636. // GetReportform 将数据集转换格式
  637. // @Tags PostDataByNameForm
  638. // @Accept json
  639. // @Produce json
  640. // @Param sqlname query string true "sqlname"
  641. // @Param offset query int true "offset"
  642. // @Param pagecount query int true "pagecount"
  643. // @Param returntype query string true "returntype"
  644. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  645. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  646. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  647. func GetReportform(c *gin.Context) {
  648. appG := app.Gin{C: c}
  649. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  650. fsion := gofasion.NewFasion(string(dataByte))
  651. sqlnamestr := fsion.Get("name").ValueStr()
  652. checked := fsion.Get("checked").ValueStr()
  653. offset := fsion.Get("offset").ValueDefaultInt(0)
  654. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  655. parammaps := fsion.Get("parammaps")
  656. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  657. mode := parammaps.Get("mode").ValueDefaultInt(0)
  658. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  659. tx := restful.Engine.NewSession()
  660. err := tx.Begin()
  661. defer func() {
  662. switch {
  663. case err != nil:
  664. if tx != nil {
  665. tx.Rollback()
  666. }
  667. default:
  668. if tx != nil {
  669. err = tx.Commit()
  670. }
  671. }
  672. if tx != nil {
  673. tx.Close()
  674. }
  675. }()
  676. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  677. if err != nil {
  678. appG.Response(http.StatusOK, e.ERROR, err.Error())
  679. } else {
  680. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  681. }
  682. }
  683. // GetUpkeepPlan 保养计划
  684. func GetUpkeepPlan(c *gin.Context) {
  685. appG := app.Gin{C: c}
  686. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  687. fsion := gofasion.NewFasion(string(dataByte))
  688. sqlnamestr := fsion.Get("name").ValueStr()
  689. offset := fsion.Get("offset").ValueDefaultInt(0)
  690. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  691. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  692. month := fsion.Get("month").ValueDefaultStr("map")
  693. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  694. tx := restful.Engine.NewSession()
  695. err := tx.Begin()
  696. defer func() {
  697. switch {
  698. case err != nil:
  699. if tx != nil {
  700. tx.Rollback()
  701. }
  702. default:
  703. if tx != nil {
  704. err = tx.Commit()
  705. }
  706. }
  707. if tx != nil {
  708. tx.Close()
  709. }
  710. }()
  711. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  712. if sql != "" {
  713. s_params := make([]interface{}, 0)
  714. if fsion.HasKey("parammaps") {
  715. parammaps := fsion.Get("parammaps")
  716. paramslist := strings.Split(p, ",")
  717. if len(paramslist) > 0 && p != "" {
  718. for _, value := range paramslist {
  719. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  720. if tempv, exists := c.Get("jwt_username"); exists {
  721. s_params = append(s_params, tempv.(string))
  722. } else {
  723. s_params = append(s_params, "")
  724. }
  725. } else {
  726. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  727. }
  728. }
  729. }
  730. } else if fsion.HasKey("params") {
  731. params := fsion.Get("params").Array()
  732. for _, v_params := range params {
  733. s_params = append(s_params, v_params.ValueStr())
  734. }
  735. }
  736. if returntype == "xlsx" {
  737. var xlsxfile *xlsx.File
  738. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  739. //c.File("c:/dd.xlsx")
  740. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  741. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  742. c.Header("Content-Transfer-Encoding", "binary")
  743. _ = xlsxfile.Write(c.Writer)
  744. } else {
  745. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  746. if err != nil {
  747. appG.Response(http.StatusOK, e.ERROR, err.Error())
  748. } else {
  749. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  750. if v, ok := value["id"]; ok {
  751. //month = "2020-03"
  752. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  753. if seviceplans != nil {
  754. for _, va := range seviceplans { //根据保养计划获取保养单
  755. //day,_ :=strconv.Atoi(va["day"])
  756. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  757. //buk := make(map[string]map[string]string)
  758. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  759. jstr := ""
  760. if bu["plantime"][8:9] == "0" {
  761. jstr = "m" + bu["plantime"][9:]
  762. } else {
  763. jstr = "m" + bu["plantime"][8:]
  764. }
  765. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  766. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  767. } else {
  768. if bu["flowCompeleted"] >= "2" {
  769. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  770. } else {
  771. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  772. }
  773. }
  774. }
  775. }
  776. }
  777. }
  778. }
  779. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  780. }
  781. }
  782. } else {
  783. appG.Response(http.StatusOK, e.SUCCESS, nil)
  784. }
  785. }
  786. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  787. // todo 优化性能 children统一查询
  788. // @Tags PostDataByNameForm
  789. // @Accept json
  790. // @Produce json
  791. // @Param sqlname query string true "sqlname"
  792. // @Param offset query int true "offset"
  793. // @Param pagecount query int true "pagecount"
  794. // @Param returntype query string true "returntype"
  795. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  796. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  797. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  798. func GetArrList(c *gin.Context) {
  799. appG := app.Gin{C: c}
  800. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  801. fsion := gofasion.NewFasion(string(dataByte))
  802. sqlnamestr := fsion.Get("name").ValueStr()
  803. sqlnamestr1 := fsion.Get("name1").ValueStr()
  804. offset := fsion.Get("offset").ValueDefaultInt(0)
  805. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  806. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  807. month := fsion.Get("month").ValueDefaultStr("map")
  808. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  809. tx := restful.Engine.NewSession()
  810. err := tx.Begin()
  811. defer func() {
  812. switch {
  813. case err != nil:
  814. if tx != nil {
  815. tx.Rollback()
  816. }
  817. default:
  818. if tx != nil {
  819. err = tx.Commit()
  820. }
  821. }
  822. if tx != nil {
  823. tx.Close()
  824. }
  825. }()
  826. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  827. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  828. if sql != "" {
  829. s_params := make([]interface{}, 0)
  830. if fsion.HasKey("parammaps") {
  831. parammaps := fsion.Get("parammaps")
  832. paramslist := strings.Split(p, ",")
  833. if len(paramslist) > 0 && p != "" {
  834. for _, value := range paramslist {
  835. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  836. if tempv, exists := c.Get("jwt_username"); exists {
  837. s_params = append(s_params, tempv.(string))
  838. } else {
  839. s_params = append(s_params, "")
  840. }
  841. } else {
  842. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  843. }
  844. }
  845. }
  846. }
  847. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  848. if err != nil {
  849. appG.Response(http.StatusOK, e.ERROR, err.Error())
  850. } else {
  851. paramslist1 := strings.Split(p1, ",")
  852. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  853. s_params1 := make([]interface{}, 0)
  854. if len(paramslist1) > 0 && p1 != "" {
  855. for _, v := range paramslist1 {
  856. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  857. }
  858. }
  859. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  860. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  861. }
  862. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  863. }
  864. } else {
  865. appG.Response(http.StatusOK, e.SUCCESS, nil)
  866. }
  867. }
  868. func GetAccount(c *gin.Context) {
  869. appG := app.Gin{C: c}
  870. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  871. fsion := gofasion.NewFasion(string(dataByte))
  872. sqlnamestr := fsion.Get("name").ValueStr()
  873. offset := fsion.Get("offset").ValueDefaultInt(0)
  874. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  875. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  876. tx := restful.Engine.NewSession()
  877. err := tx.Begin()
  878. defer func() {
  879. switch {
  880. case err != nil:
  881. logging.Error("tx.Begin 事务启动失败__error:", err)
  882. if tx != nil {
  883. tx.Rollback()
  884. }
  885. default:
  886. if tx != nil {
  887. err = tx.Commit()
  888. }
  889. }
  890. if tx != nil {
  891. tx.Close()
  892. }
  893. }()
  894. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  895. if sql != "" {
  896. s_params := make([]interface{}, 0)
  897. if fsion.HasKey("parammaps") {
  898. parammaps := fsion.Get("parammaps")
  899. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  900. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  901. }
  902. paramslist := strings.Split(p, ",")
  903. if len(paramslist) > 0 && p != "" {
  904. for _, value := range paramslist {
  905. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  906. if tempv, exists := c.Get("jwt_username"); exists {
  907. s_params = append(s_params, tempv.(string))
  908. } else {
  909. s_params = append(s_params, "")
  910. }
  911. } else {
  912. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  913. }
  914. }
  915. }
  916. } else if fsion.HasKey("params") {
  917. params := fsion.Get("params").Array()
  918. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  919. for _, v_params := range params {
  920. s_params = append(s_params, v_params.ValueStr())
  921. }
  922. }
  923. if returntype == "xlsx" {
  924. var xlsxfile *xlsx.File
  925. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  926. //c.File("c:/dd.xlsx")
  927. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  928. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  929. c.Header("Content-Transfer-Encoding", "binary")
  930. _ = xlsxfile.Write(c.Writer)
  931. } else {
  932. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  933. if err != nil {
  934. logging.Error("GetDataByName err: ", err)
  935. msg := geterrmsg(err.Error())
  936. appG.Response(http.StatusOK, e.ERROR, msg)
  937. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  938. } else {
  939. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  940. }
  941. }
  942. } else {
  943. appG.Response(http.StatusOK, e.SUCCESS, nil)
  944. }
  945. }
  946. // PostDataByName 根据APISQL表中SQL执行得到数据集
  947. // @Accept json
  948. // @Produce json
  949. // @Param sqlname query string true "sqlname"
  950. // @Param offset query int true "offset"
  951. // @Param pagecount query int true "pagecount"
  952. // @Param returntype query string true "returntype"
  953. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  954. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  955. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  956. // @Router /data/PostDataByName [POST]
  957. func PostDataByName(c *gin.Context) {
  958. appG := app.Gin{C: c}
  959. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  960. fsion := gofasion.NewFasion(string(dataByte))
  961. var err error
  962. queryData, err := module.PostDataByName(c, fsion)
  963. if err != nil {
  964. appG.Response(http.StatusOK, e.ERROR, err.Error())
  965. return
  966. }
  967. var (
  968. keyWord string
  969. )
  970. switch fsion.Get("name").ValueStr() {
  971. case "insertFeedclass":
  972. keyWord = "feed"
  973. err = module.GroupCategorySync(keyWord, fsion)
  974. case "deleteFeedclass":
  975. keyWord = "feed_delete"
  976. err = module.GroupCategoryDelete(keyWord, fsion)
  977. case "insertCowclass":
  978. keyWord = "cow"
  979. err = module.GroupCategorySync(keyWord, fsion)
  980. case "deleteCowclass":
  981. keyWord = "cow_delete"
  982. err = module.GroupCategoryDelete(keyWord, fsion)
  983. // case "updateFT":
  984. // FtdetailSurplus(fsion)
  985. // case "updateFeed":
  986. // FeedSurplus(fsion)
  987. default:
  988. }
  989. if err != nil {
  990. logging.Error(keyWord, err)
  991. }
  992. if queryData != nil {
  993. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  994. return
  995. }
  996. appG.Response(http.StatusOK, e.SUCCESS, nil)
  997. }
  998. //人脸识别/格润富德接口
  999. func GetRJSBData(c *gin.Context) {
  1000. appG := app.Gin{C: c}
  1001. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1002. fsion := gofasion.NewFasion(string(dataByte))
  1003. sqlnamestr := fsion.Get("name").ValueStr()
  1004. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1005. offset := fsion.Get("offset").ValueDefaultInt(0)
  1006. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1007. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1008. month := fsion.Get("month").ValueDefaultStr("map")
  1009. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1010. pagecount = 1
  1011. tx := restful.Engine.NewSession()
  1012. err := tx.Begin()
  1013. defer func() {
  1014. switch {
  1015. case err != nil:
  1016. if tx != nil {
  1017. tx.Rollback()
  1018. }
  1019. default:
  1020. if tx != nil {
  1021. err = tx.Commit()
  1022. }
  1023. }
  1024. if tx != nil {
  1025. tx.Close()
  1026. }
  1027. }()
  1028. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1029. _, 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 )
  1030. where id = (select tmrid from downloadedplan d where d.pid = (select pid from downloadedplan where lpplantype = 5 and mydate =
  1031. date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted= 0 ) and mydate = date_format(now() ,'%Y-%m-%d')
  1032. and lpplantype in(0,1)) `).Execute()
  1033. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1034. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1035. if sql != "" {
  1036. s_params := make([]interface{}, 0)
  1037. if fsion.HasKey("parammaps") {
  1038. parammaps := fsion.Get("parammaps")
  1039. paramslist := strings.Split(p, ",")
  1040. if len(paramslist) > 0 && p != "" {
  1041. for _, value := range paramslist {
  1042. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1043. if tempv, exists := c.Get("jwt_username"); exists {
  1044. s_params = append(s_params, tempv.(string))
  1045. } else {
  1046. s_params = append(s_params, "")
  1047. }
  1048. } else {
  1049. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1050. }
  1051. }
  1052. }
  1053. }
  1054. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1055. if err != nil {
  1056. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1057. } else {
  1058. paramslist1 := strings.Split(p1, ",")
  1059. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1060. s_params1 := make([]interface{}, 0)
  1061. if len(paramslist1) > 0 && p1 != "" {
  1062. for _, v := range paramslist1 {
  1063. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1064. }
  1065. }
  1066. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1067. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1068. }
  1069. var wg sync.WaitGroup
  1070. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1071. wg.Add(1)
  1072. go func(value map[string]interface{}) {
  1073. defer wg.Done()
  1074. // ,havebutton = 1
  1075. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1076. }(value)
  1077. }
  1078. wg.Wait()
  1079. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1080. }
  1081. fmt.Println("先锋获取数据:", time.Now(), queryData)
  1082. } else {
  1083. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1084. }
  1085. }
  1086. func PostRJSBData(c *gin.Context) {
  1087. appG := app.Gin{C: c}
  1088. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1089. fsion := gofasion.NewFasion(string(dataByte))
  1090. logging.Info("PostRJSBData err: ", string(dataByte))
  1091. s_params := make([]interface{}, 0)
  1092. tx := restful.Engine.NewSession()
  1093. err := tx.Begin()
  1094. defer func() {
  1095. switch {
  1096. case err != nil:
  1097. if tx != nil {
  1098. tx.Rollback()
  1099. }
  1100. default:
  1101. if tx != nil {
  1102. err = tx.Commit()
  1103. }
  1104. }
  1105. if tx != nil {
  1106. tx.Close()
  1107. }
  1108. }()
  1109. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1110. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1111. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1112. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1113. if !fsion.HasKey("parammaps") {
  1114. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1115. return
  1116. }
  1117. parammaps := fsion.Get("parammaps")
  1118. paramslist := strings.Split(p, ",")
  1119. if len(paramslist) > 0 && p != "" {
  1120. for _, value := range paramslist {
  1121. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1122. }
  1123. }
  1124. projuctid := parammaps.Get("projuctid").ValueStr()
  1125. _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
  1126. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1127. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1128. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1129. and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1130. if err != nil {
  1131. logging.Error("PostRJSBData-0 err: ", err)
  1132. msg := geterrmsg(err.Error())
  1133. // appG.Response(http.StatusOK, e.ERROR, msg)
  1134. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1135. return
  1136. }
  1137. _, err = tx.SQL(sql, s_params...).Execute()
  1138. if err != nil {
  1139. logging.Error("PostRJSBData err: ", err)
  1140. msg := geterrmsg(err.Error())
  1141. // appG.Response(http.StatusOK, e.ERROR, msg)
  1142. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1143. return
  1144. }
  1145. s_params = make([]interface{}, 0)
  1146. paramslist = strings.Split(p1, ",")
  1147. if len(paramslist) > 0 && p1 != "" {
  1148. for _, value := range paramslist {
  1149. // if value == "ID" {
  1150. // id := parammaps.Get("ID").ValueStr()
  1151. // pastureid := parammaps.Get("pastureid").ValueStr()
  1152. // 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
  1153. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1154. // if err != nil {
  1155. // logging.Error("PostRJSBData err: ", err)
  1156. // msg := geterrmsg(err.Error())
  1157. // appG.Response(http.StatusOK, e.ERROR, msg)
  1158. // return
  1159. // }
  1160. // for _, item := range datalist {
  1161. // id = item["id"]
  1162. // }
  1163. // s_params = append(s_params, id)
  1164. // } else {
  1165. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1166. // }
  1167. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1168. }
  1169. }
  1170. _, err = tx.SQL(sql1, s_params...).Execute()
  1171. if err != nil {
  1172. logging.Error("PostRJSBData1 err: ", err)
  1173. msg := geterrmsg(err.Error())
  1174. appG.Response(http.StatusOK, e.ERROR, msg)
  1175. return
  1176. }
  1177. s_params = make([]interface{}, 0)
  1178. paramslist = strings.Split(p2, ",")
  1179. if len(paramslist) > 0 && p2 != "" {
  1180. for _, value := range paramslist {
  1181. if value == "ID" {
  1182. id := parammaps.Get("ID").ValueStr()
  1183. pastureid := parammaps.Get("pastureid").ValueStr()
  1184. 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
  1185. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1186. if err != nil {
  1187. logging.Error("PostRJSBData err: ", err)
  1188. msg := geterrmsg(err.Error())
  1189. appG.Response(http.StatusOK, e.ERROR, msg)
  1190. return
  1191. }
  1192. for _, item := range datalist {
  1193. id = item["id"]
  1194. }
  1195. s_params = append(s_params, id)
  1196. } else {
  1197. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1198. }
  1199. }
  1200. }
  1201. _, err = tx.SQL(sql2, s_params...).Execute()
  1202. if err != nil {
  1203. logging.Error("PostRJSBData2 err: ", err)
  1204. msg := geterrmsg(err.Error())
  1205. appG.Response(http.StatusOK, e.ERROR, msg)
  1206. return
  1207. }
  1208. s_params = make([]interface{}, 0)
  1209. paramslist = strings.Split(p3, ",")
  1210. if len(paramslist) > 0 && p3 != "" {
  1211. for _, value := range paramslist {
  1212. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1213. }
  1214. }
  1215. _, err = tx.SQL(sql3, s_params...).Execute()
  1216. if err != nil {
  1217. logging.Error("PostRJSBData3 err: ", err)
  1218. msg := geterrmsg(err.Error())
  1219. appG.Response(http.StatusOK, e.ERROR, msg)
  1220. return
  1221. }
  1222. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1223. }
  1224. func PostRJSBDatas(c *gin.Context) {
  1225. appG := app.Gin{C: c}
  1226. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1227. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1228. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1229. fmt.Println("先锋回传数据:", time.Now(), string(dataByte))
  1230. tx := restful.Engine.NewSession()
  1231. err := tx.Begin()
  1232. defer func() {
  1233. switch {
  1234. case err != nil:
  1235. if tx != nil {
  1236. tx.Rollback()
  1237. }
  1238. default:
  1239. if tx != nil {
  1240. err = tx.Commit()
  1241. }
  1242. }
  1243. if tx != nil {
  1244. tx.Close()
  1245. }
  1246. }()
  1247. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1248. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1249. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1250. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1251. for _, fsion := range fsions {
  1252. if !fsion.HasKey("parammaps") {
  1253. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1254. return
  1255. }
  1256. parammaps := fsion.Get("parammaps")
  1257. ID := parammaps.Get("ID").ValueStr()
  1258. if ID == "" {
  1259. continue
  1260. }
  1261. s_params := make([]interface{}, 0)
  1262. paramslist := strings.Split(p, ",")
  1263. if len(paramslist) > 0 && p != "" {
  1264. for _, value := range paramslist {
  1265. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1266. }
  1267. }
  1268. _, err := tx.SQL(sql, s_params...).Execute()
  1269. if err != nil {
  1270. logging.Error("PostRJSBData err: ", err)
  1271. msg := geterrmsg(err.Error())
  1272. // appG.Response(http.StatusOK, e.ERROR, msg)
  1273. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1274. return
  1275. }
  1276. s_params = make([]interface{}, 0)
  1277. paramslist = strings.Split(p1, ",")
  1278. if len(paramslist) > 0 && p1 != "" {
  1279. for _, value := range paramslist {
  1280. // if value == "ID" {
  1281. // id := parammaps.Get("ID").ValueStr()
  1282. // pastureid := parammaps.Get("pastureid").ValueStr()
  1283. // 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
  1284. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1285. // if err != nil {
  1286. // logging.Error("PostRJSBData err: ", err)
  1287. // msg := geterrmsg(err.Error())
  1288. // appG.Response(http.StatusOK, e.ERROR, msg)
  1289. // return
  1290. // }
  1291. // for _, item := range datalist {
  1292. // id = item["id"]
  1293. // }
  1294. // s_params = append(s_params, id)
  1295. // } else {
  1296. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1297. // }
  1298. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1299. }
  1300. }
  1301. _, err = tx.SQL(sql1, s_params...).Execute()
  1302. if err != nil {
  1303. logging.Error("PostRJSBData1 err: ", err)
  1304. msg := geterrmsg(err.Error())
  1305. appG.Response(http.StatusOK, e.ERROR, msg)
  1306. return
  1307. }
  1308. s_params = make([]interface{}, 0)
  1309. paramslist = strings.Split(p2, ",")
  1310. if len(paramslist) > 0 && p2 != "" {
  1311. for _, value := range paramslist {
  1312. if value == "ID" {
  1313. id := parammaps.Get("ID").ValueStr()
  1314. pastureid := parammaps.Get("pastureid").ValueStr()
  1315. 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
  1316. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1317. if err != nil {
  1318. logging.Error("PostRJSBData err: ", err)
  1319. msg := geterrmsg(err.Error())
  1320. appG.Response(http.StatusOK, e.ERROR, msg)
  1321. return
  1322. }
  1323. for _, item := range datalist {
  1324. id = item["id"]
  1325. }
  1326. s_params = append(s_params, id)
  1327. } else {
  1328. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1329. }
  1330. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1331. }
  1332. }
  1333. _, err = tx.SQL(sql2, s_params...).Execute()
  1334. if err != nil {
  1335. logging.Error("PostRJSBData2 err: ", err)
  1336. msg := geterrmsg(err.Error())
  1337. appG.Response(http.StatusOK, e.ERROR, msg)
  1338. return
  1339. }
  1340. s_params = make([]interface{}, 0)
  1341. paramslist = strings.Split(p3, ",")
  1342. if len(paramslist) > 0 && p3 != "" {
  1343. for _, value := range paramslist {
  1344. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1345. }
  1346. }
  1347. _, err = tx.SQL(sql3, s_params...).Execute()
  1348. if err != nil {
  1349. logging.Error("PostRJSBData3 err: ", err)
  1350. msg := geterrmsg(err.Error())
  1351. appG.Response(http.StatusOK, e.ERROR, msg)
  1352. return
  1353. }
  1354. // ALTER TABLE `tmr`
  1355. // ADD COLUMN `concentrate` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 未回传 1 已回传' AFTER `appoint`
  1356. projuctid := parammaps.Get("projuctid").ValueStr()
  1357. _, err = tx.SQL(`update tmr set xianfeng = 0, concentrate = (select d.id from downloadedplan d
  1358. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1359. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1360. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1361. and lpplantype in(0,1)) and ( select count(1) from downloadedplan where id = ? and iscompleted = 0 ) = 0 `,
  1362. projuctid, projuctid, projuctid, projuctid, projuctid).Execute()
  1363. if err != nil {
  1364. logging.Error("PostRJSBData-0 err: ", err)
  1365. msg := geterrmsg(err.Error())
  1366. // appG.Response(http.StatusOK, e.ERROR, msg)
  1367. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1368. return
  1369. }
  1370. count, _ := tx.SQL(`select count(1) from downloadedplan where id = ? and iscompleted = 0`, projuctid).Count()
  1371. if count == 0 {
  1372. fmt.Println(projuctid, "先锋回传计划已完成", count, err)
  1373. }
  1374. }
  1375. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1376. }
  1377. // @Summary 根据APISQL表中SQL执行得到数据集
  1378. // @Tags ExecDataByConfig
  1379. // @Accept json
  1380. // @Produce json
  1381. // @Param sqlname query string true "sqlname"
  1382. // @Param offset query int true "offset"
  1383. // @Param pagecount query int true "pagecount"
  1384. // @Param returntype query string true "returntype"
  1385. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1386. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1387. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1388. // @Router /data/PostDataByName [POST]
  1389. func ExecDataByConfig(c *gin.Context) {
  1390. appG := app.Gin{C: c}
  1391. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1392. tempval_ := make(map[string]interface{})
  1393. tempCommon := make(map[string]interface{})
  1394. tempval := make([]map[string]interface{}, 0)
  1395. err := json.Unmarshal(dataByte, &tempval_)
  1396. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1397. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1398. if err != nil {
  1399. } else {
  1400. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1401. tempCommon = v
  1402. }
  1403. if v, ok := tempval_["data"].([]interface{}); ok {
  1404. for _, Tvalue := range v {
  1405. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1406. tempval = append(tempval, v1)
  1407. }
  1408. }
  1409. }
  1410. tx := restful.Engine.NewSession()
  1411. err := tx.Begin()
  1412. if err != nil {
  1413. logging.Error("tx.Begin 事务启动失败__error:", err)
  1414. }
  1415. defer func() {
  1416. switch {
  1417. case err != nil:
  1418. if tx != nil {
  1419. tx.Rollback()
  1420. }
  1421. default:
  1422. if tx != nil {
  1423. err = tx.Commit()
  1424. }
  1425. }
  1426. if tx != nil {
  1427. tx.Close()
  1428. }
  1429. }()
  1430. if err == nil {
  1431. if tempv, exists := c.Get("jwt_username"); exists {
  1432. tempCommon["jwt_username"] = tempv.(string)
  1433. }
  1434. for _, paramvalue := range tempval {
  1435. fmt.Println(paramvalue["name"])
  1436. if paramvalue["name"].(string) == "updateBigFP" {
  1437. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1438. if err != nil {
  1439. msg := geterrmsg(err.Error())
  1440. appG.Response(http.StatusOK, e.ERROR, msg)
  1441. return
  1442. }
  1443. }
  1444. }
  1445. for _, paramvalue := range tempval {
  1446. if _, ok := paramvalue["resultname"]; !ok {
  1447. paramvalue["resultname"] = paramvalue["name"]
  1448. }
  1449. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1450. if err != nil {
  1451. logging.Error("ExecDataParam error:", err)
  1452. break
  1453. }
  1454. // if paramvalue["name"].(string) == "createdownloadedplan" {
  1455. // checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1456. // }
  1457. }
  1458. if err == nil {
  1459. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1460. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1461. } else {
  1462. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1463. }
  1464. } else {
  1465. msg := geterrmsg(err.Error())
  1466. appG.Response(http.StatusOK, e.ERROR, msg)
  1467. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1468. }
  1469. }
  1470. }
  1471. if err != nil {
  1472. msg := geterrmsg(err.Error())
  1473. appG.Response(http.StatusOK, e.ERROR, msg)
  1474. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1475. }
  1476. }
  1477. func interfacetostring(val interface{}) string {
  1478. switch val.(type) {
  1479. case string:
  1480. ss := val.(string)
  1481. return ss
  1482. break
  1483. case int:
  1484. ss := val.(int)
  1485. return strconv.Itoa(ss)
  1486. break
  1487. case int64:
  1488. ss := val.(int64)
  1489. return strconv.FormatInt(ss, 10)
  1490. break
  1491. case float64:
  1492. ss := val.(float64)
  1493. return strconv.FormatFloat(ss, 'E', -1, 32)
  1494. break
  1495. }
  1496. return ""
  1497. }
  1498. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1499. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1500. tempstrb := strings.IndexAny(valuestring, "@")
  1501. tempstre := strings.IndexAny(valuestring, ".")
  1502. if tempstrb > -1 && tempstre > -1 {
  1503. for _, ParamMapList := range ParamMap {
  1504. if v, ok := ParamMapList["resultname"]; ok {
  1505. if v == valuestring[tempstrb+1:tempstre] {
  1506. if v1, ok := ParamMapList["resultmaps"]; ok {
  1507. if newA, ok := v1.([]map[string]interface{}); ok {
  1508. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1509. } else if newA, ok := v1.(map[string]interface{}); ok {
  1510. return interfacetostring(newA[valuestring[tempstre+1:]])
  1511. }
  1512. }
  1513. }
  1514. }
  1515. }
  1516. } else {
  1517. return valuestring
  1518. }
  1519. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1520. return fmt.Sprintf("%f", valuestring)
  1521. }
  1522. return ""
  1523. }
  1524. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1525. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1526. tempstrb := strings.IndexAny(valuestring, "@")
  1527. tempstre := strings.IndexAny(valuestring, ".")
  1528. if tempstrb > -1 && tempstre > -1 {
  1529. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1530. if s, ok := v.(string); ok {
  1531. return s
  1532. } else if s, ok := v.(float64); ok {
  1533. return strconv.FormatFloat(s, 'f', -1, 64)
  1534. // return strconv.FormatInt(int64(s), 10)
  1535. }
  1536. }
  1537. }
  1538. }
  1539. return ""
  1540. }
  1541. 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) {
  1542. sqlname := fasion["name"].(string)
  1543. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1544. if v, ok := fasion["type"]; ok {
  1545. sqltype = v.(string)
  1546. }
  1547. sql := ""
  1548. p := ""
  1549. s_params := make([]interface{}, 0)
  1550. if sqltype != "" {
  1551. sql, p = restful.GetSqlByName(sqlname, tx)
  1552. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1553. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1554. paramslist := strings.Split(p, ",")
  1555. if len(paramslist) > 0 && p != "" {
  1556. for _, value := range paramslist {
  1557. ss := ""
  1558. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1559. ids, err := setting.SnowIds.NextId()
  1560. if err != nil {
  1561. ids = time.Now().UnixNano()
  1562. logging.Info("create SnowIds err", err)
  1563. }
  1564. s_params = append(s_params, ids)
  1565. } else {
  1566. if ss == "" && CommonParamMap != nil {
  1567. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1568. ss = valuestring
  1569. tempstrb := strings.IndexAny(valuestring, "@")
  1570. tempstre := strings.IndexAny(valuestring, ".")
  1571. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1572. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1573. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1574. }
  1575. } else {
  1576. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1577. ss = ""
  1578. }
  1579. }
  1580. }
  1581. }
  1582. if ss == "" && ParentParamMap != nil {
  1583. ss = getParamValue_(v, value, ParentParamMap)
  1584. }
  1585. if ss == "" && sameParamMap != nil {
  1586. ss = getParamValue(v, value, sameParamMap)
  1587. }
  1588. if ss == "" && ParamMap != nil {
  1589. ss = getParamValue(v, value, ParamMap)
  1590. }
  1591. s_params = append(s_params, ss)
  1592. }
  1593. }
  1594. }
  1595. }
  1596. }
  1597. if sql == "" {
  1598. sqltype = ""
  1599. }
  1600. if sqltype == "s1" {
  1601. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1602. if v, ok := tempValParam.(map[string]interface{}); ok {
  1603. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1604. }
  1605. if err != nil {
  1606. return nil, err
  1607. }
  1608. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1609. if err != nil {
  1610. return nil, err
  1611. }
  1612. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1613. } else if sqltype == "sm" {
  1614. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1615. if v, ok := tempValParam.(map[string]interface{}); ok {
  1616. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1617. } else {
  1618. }
  1619. if err != nil {
  1620. return nil, err
  1621. }
  1622. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1623. if err != nil {
  1624. return nil, err
  1625. }
  1626. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1627. } else if sqltype == "v" {
  1628. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1629. if v, ok := tempValParam.(map[string]interface{}); ok {
  1630. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1631. } else {
  1632. }
  1633. if err != nil {
  1634. return nil, err
  1635. }
  1636. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1637. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1638. }
  1639. } else if sqltype == "e" {
  1640. tempVal_arrary := make([]map[string]interface{}, 0)
  1641. tempVal_map := make(map[string]interface{})
  1642. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1643. if err == nil {
  1644. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1645. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1646. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1647. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1648. return tempVal_arrary, err
  1649. }
  1650. return nil, err
  1651. } else {
  1652. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1653. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1654. if err != nil {
  1655. return nil, err
  1656. }
  1657. return nil, err
  1658. }
  1659. }
  1660. return nil, nil
  1661. }
  1662. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1663. var err error
  1664. subarray, ok := fasion["children"]
  1665. if ok {
  1666. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1667. tempVal_arrary := make([]map[string]interface{}, 0)
  1668. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1669. tempVal_ := make(map[string]interface{})
  1670. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1671. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1672. } else {
  1673. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1674. }
  1675. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1676. if err != nil {
  1677. return err
  1678. }
  1679. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1680. }
  1681. v.(map[string]interface{})["children"] = tempVal_arrary
  1682. }
  1683. }
  1684. return nil
  1685. }
  1686. // @Summary 删除图片
  1687. // @Tags RemovePicByName
  1688. // @Accept json
  1689. // @Produce json
  1690. // @Param sqlname query string true "sqlname"
  1691. // @Param offset query int true "offset"
  1692. // @Param pagecount query int true "pagecount"
  1693. // @Param returntype query string true "returntype"
  1694. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1695. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1696. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1697. // @Router /data/PostDataByName [POST]
  1698. func RemovePicByName(c *gin.Context) {
  1699. logging.Info("RemovePicByName ", c.Keys)
  1700. appG := app.Gin{C: c}
  1701. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1702. fsion := gofasion.NewFasion(string(dataByte))
  1703. sqlnamestr := fsion.Get("name").ValueStr()
  1704. picname := fsion.Get("picname").ValueStr()
  1705. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1706. params := fsion.Get("params").Array()
  1707. s_params := make([]interface{}, 0)
  1708. for _, v_params := range params {
  1709. s_params = append(s_params, v_params.ValueStr())
  1710. }
  1711. if sql != "" {
  1712. queryData, err := execDataBySql(sql, s_params)
  1713. if picname != "" {
  1714. // Destination
  1715. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1716. err := os.Remove(distPath) //删除文件test.txt
  1717. if err != nil {
  1718. //如果删除失败则输出 file remove Error!
  1719. fmt.Println("file remove Error!")
  1720. //输出错误详细信息
  1721. fmt.Printf("%s", err)
  1722. } else {
  1723. //如果删除成功则输出 file remove OK!
  1724. fmt.Print("file remove OK!")
  1725. }
  1726. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1727. err = os.Remove(distPath) //删除文件test.txt
  1728. if err != nil {
  1729. //如果删除失败则输出 file remove Error!
  1730. fmt.Println("file remove Error!")
  1731. //输出错误详细信息
  1732. fmt.Printf("%s", err)
  1733. } else {
  1734. //如果删除成功则输出 file remove OK!
  1735. fmt.Print("file remove OK!")
  1736. }
  1737. }
  1738. if err != nil {
  1739. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1740. } else {
  1741. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1742. }
  1743. } else {
  1744. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1745. }
  1746. }
  1747. // @Summary 删除文件
  1748. // @Tags RemoveFileByName
  1749. // @Accept json
  1750. // @Produce json
  1751. // @Param sqlname query string true "sqlname"
  1752. // @Param offset query int true "offset"
  1753. // @Param pagecount query int true "pagecount"
  1754. // @Param returntype query string true "returntype"
  1755. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1756. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1757. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1758. // @Router /data/PostDataByName [POST]
  1759. func RemoveFileByName(c *gin.Context) {
  1760. appG := app.Gin{C: c}
  1761. id := c.Param("id")
  1762. logging.Info("DownloadFile ", c.Keys, id)
  1763. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1764. if eqdoc == nil {
  1765. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1766. return
  1767. }
  1768. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1769. err = os.Remove(distPath) //删除文件test.txt
  1770. if err != nil {
  1771. //如果删除失败则输出 file remove Error!
  1772. fmt.Println("file remove Error!")
  1773. //输出错误详细信息
  1774. fmt.Printf("%s", err)
  1775. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1776. return
  1777. }
  1778. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1779. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1780. }
  1781. // @Summary 根据APISQL表中SQL执行得到数据集
  1782. // @Tags PostDataByName
  1783. // @Accept json
  1784. // @Produce json
  1785. // @Param sqlname query string true "sqlname"
  1786. // @Param offset query int true "offset"
  1787. // @Param pagecount query int true "pagecount"
  1788. // @Param returntype query string true "returntype"
  1789. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1790. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1791. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1792. // @Router /data/PostDataByName [POST]
  1793. func UpdateDataRelation(c *gin.Context) {
  1794. appG := app.Gin{C: c}
  1795. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1796. fsion := gofasion.NewFasion(string(dataByte))
  1797. tablename := fsion.Get("name").ValueStr()
  1798. dataname := fsion.Get("dataname").ValueStr()
  1799. datavalue := fsion.Get("datavalue").ValueStr()
  1800. valuename := fsion.Get("valuename").ValueStr()
  1801. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1802. values := fsion.Get("values").Array()
  1803. tx := restful.Engine.NewSession()
  1804. err := tx.Begin()
  1805. defer func() {
  1806. switch {
  1807. case err != nil:
  1808. if tx != nil {
  1809. tx.Rollback()
  1810. }
  1811. default:
  1812. if tx != nil {
  1813. err = tx.Commit()
  1814. }
  1815. }
  1816. if tx != nil {
  1817. tx.Close()
  1818. }
  1819. }()
  1820. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1821. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1822. d_params := make([]interface{}, 4)
  1823. d_params[0] = datavalue
  1824. s_params := ""
  1825. for _, v_values := range values {
  1826. d_params[1] = v_values.ValueStr()
  1827. if s_params == "" {
  1828. s_params = v_values.ValueStr()
  1829. } else {
  1830. s_params = s_params + "," + v_values.ValueStr()
  1831. }
  1832. d_params[2] = d_params[1]
  1833. d_params[3] = d_params[0]
  1834. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1835. if err != nil {
  1836. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1837. break
  1838. }
  1839. }
  1840. if s_params != "" {
  1841. deleteSqlstr := "delete from " + tablename + " " +
  1842. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1843. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1844. if err != nil {
  1845. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1846. } else if err == nil {
  1847. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1848. }
  1849. } else {
  1850. deleteSqlstr := "delete from " + tablename + " " +
  1851. " where " + dataname + " = " + datavalue
  1852. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1853. if err != nil {
  1854. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1855. } else if err == nil {
  1856. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1857. }
  1858. }
  1859. }
  1860. // @Summary 根据APISQL表中SQL执行得到数据集
  1861. // @Tags PostDatasByName
  1862. // @Accept json
  1863. // @Produce json
  1864. // @Param sqlname query string true "sqlname"
  1865. // @Param offset query int true "offset"
  1866. // @Param pagecount query int true "pagecount"
  1867. // @Param returntype query string true "returntype"
  1868. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1869. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1870. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1871. // @Router /data/PostDatasByName [POST]
  1872. func PostDataByNames(c *gin.Context) {
  1873. appG := app.Gin{C: c}
  1874. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1875. fsion := gofasion.NewFasion(string(dataByte))
  1876. sqlParams := fsion.Get("array").Array()
  1877. queryData := make(map[string]interface{})
  1878. for _, v := range sqlParams {
  1879. fsion2 := gofasion.NewFasion(v.Json())
  1880. ss := fsion2.Get("name")
  1881. aa := fsion2.Get("params")
  1882. fmt.Println(ss, aa)
  1883. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1884. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1885. if sql == "" {
  1886. errorm := make(map[string]interface{})
  1887. errorm["code"] = e.ERROR
  1888. errorm["message"] = "sql没有找到"
  1889. errorm["param"] = ""
  1890. queryData[fsion2.Get("name").ValueStr()] = errorm
  1891. continue
  1892. } else if sql != "" {
  1893. s_params := make([]interface{}, 0)
  1894. if fsion2.HasKey("parammaps") {
  1895. parammaps := fsion2.Get("parammaps")
  1896. paramslist := strings.Split(p, ",")
  1897. if len(paramslist) > 0 && p != "" {
  1898. for _, value := range paramslist {
  1899. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1900. if tempv, exists := c.Get("jwt_username"); exists {
  1901. s_params = append(s_params, tempv.(string))
  1902. } else {
  1903. s_params = append(s_params, "")
  1904. }
  1905. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1906. ids, err := setting.SnowIds.NextId()
  1907. if err != nil {
  1908. ids = time.Now().UnixNano()
  1909. logging.Info("create SnowIds err", err)
  1910. }
  1911. s_params = append(s_params, ids)
  1912. } else {
  1913. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1914. }
  1915. }
  1916. }
  1917. } else if fsion2.HasKey("params") {
  1918. params := fsion2.Get("params").Array()
  1919. //ids,err := setting.SnowIds.NextId()
  1920. //if err !=nil{
  1921. // ids = time.Now().UnixNano()
  1922. // logging.Info("create SnowIds err",err)
  1923. //}
  1924. //s_params = append(s_params, ids)
  1925. for _, v_params := range params {
  1926. s_params = append(s_params, v_params.ValueStr())
  1927. }
  1928. }
  1929. _, err := execDataBySql(sql, s_params)
  1930. if err != nil {
  1931. logging.Error("PostDataByName err: ", err)
  1932. errorm := make(map[string]interface{})
  1933. errorm["code"] = e.ERROR
  1934. errorm["message"] = err.Error()
  1935. errorm["param"] = s_params
  1936. queryData[fsion2.Get("name").ValueStr()] = errorm
  1937. continue
  1938. } else {
  1939. errorm := make(map[string]interface{})
  1940. errorm["code"] = e.SUCCESS
  1941. errorm["message"] = "success"
  1942. queryData[fsion2.Get("name").ValueStr()] = errorm
  1943. continue
  1944. }
  1945. } else {
  1946. errorm := make(map[string]interface{})
  1947. errorm["code"] = e.ERROR
  1948. errorm["message"] = "NO SQL"
  1949. errorm["param"] = ""
  1950. queryData[fsion2.Get("name").ValueStr()] = errorm
  1951. }
  1952. }
  1953. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1954. }
  1955. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1956. if offset > 0 {
  1957. offset = offset - 1
  1958. }
  1959. //if pagecount == 0 {
  1960. // pagecount = setting.AppSetting.PageSize
  1961. //}else if pagecount>setting.AppSetting.PageSize{
  1962. // pagecount = setting.AppSetting.PageSize
  1963. //}
  1964. if returntype == "list" {
  1965. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1966. return queryData, err
  1967. } else if returntype == "listlist" {
  1968. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1969. return queryData, err
  1970. } else {
  1971. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1972. return queryData, err
  1973. }
  1974. }
  1975. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1976. if offset > 0 {
  1977. offset = offset - 1
  1978. }
  1979. //if pagecount == 0 {
  1980. // pagecount = setting.AppSetting.PageSize
  1981. //}else if pagecount>setting.AppSetting.PageSize{
  1982. // pagecount = setting.AppSetting.PageSize
  1983. //}
  1984. if returntype == "list" {
  1985. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1986. return queryData, err
  1987. } else if returntype == "listlist" {
  1988. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1989. return queryData, err
  1990. } else {
  1991. fmt.Println(params)
  1992. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1993. return queryData, err
  1994. }
  1995. }
  1996. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1997. paramslist := strings.Split(Params, ",")
  1998. s_params := make([]interface{}, 0)
  1999. if isList {
  2000. for _, v_params := range thisParams["params"].([]interface{}) {
  2001. s_params = append(s_params, v_params)
  2002. }
  2003. } else {
  2004. paramslist := strings.Split(Params, ",")
  2005. if len(paramslist) > 0 && Params != "" {
  2006. for _, value := range paramslist {
  2007. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2008. }
  2009. }
  2010. }
  2011. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  2012. for _, queryData_ := range queryData {
  2013. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  2014. if isList {
  2015. if queryData_[idname] != nil {
  2016. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  2017. }
  2018. } else {
  2019. if queryData_[idname] != nil {
  2020. thisParams[idname] = queryData_[idname].(interface{})
  2021. }
  2022. if len(paramslist) > 0 && Params != "" {
  2023. s_params = make([]interface{}, 0)
  2024. for _, value := range paramslist {
  2025. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2026. }
  2027. }
  2028. }
  2029. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  2030. } else {
  2031. }
  2032. }
  2033. return queryData, err
  2034. }
  2035. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2036. queryData, err := restful.ExecQuery(sqlstr, params)
  2037. return queryData, err
  2038. }
  2039. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2040. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2041. return queryData, err
  2042. }
  2043. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2044. queryData, err := restful.ExecQuery(sqlstr, params)
  2045. return queryData, err
  2046. }
  2047. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2048. // @Tags ImportExcel
  2049. // @Accept json
  2050. // @Produce json
  2051. // @Param file query string true "文件名"
  2052. // @Param name header string true "执行sql的名字"
  2053. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2054. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2055. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2056. // @Router /data/ImportExcel [POST]
  2057. func ImportExcel(c *gin.Context) {
  2058. appG := app.Gin{C: c}
  2059. inputdata := ""
  2060. c.Request.ParseForm()
  2061. params := c.Request.Form
  2062. file, _, err := c.Request.FormFile("file")
  2063. if err != nil {
  2064. appG.Response(http.StatusOK, e.ERROR, err)
  2065. return
  2066. }
  2067. sqlnamestrs := params.Get("name")
  2068. sheetname := params.Get("sheetname")
  2069. pastureid := params.Get("pastureid")
  2070. //importParams := params.Get("importParams")
  2071. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2072. // 必输项参数 (字符串格式 "field1,field2,field3")
  2073. requiredParams := params.Get("requiredParams")
  2074. // 日期参数
  2075. dateParams := params.Get("dateParams")
  2076. // 数字参数
  2077. numParams := params.Get("numParams")
  2078. //将字符串分割开
  2079. dateParamslist := strings.Split(dateParams, ",")
  2080. requiredParamslist := strings.Split(requiredParams, ",")
  2081. numParamslist := strings.Split(numParams, ",")
  2082. queryData := make([]interface{}, 0)
  2083. sqlslist := strings.Split(sqlnamestrs, ",")
  2084. xlsx1, err := excelize.OpenReader(file)
  2085. if err != nil {
  2086. fmt.Println(err)
  2087. return
  2088. }
  2089. ok := 0
  2090. error := 0
  2091. isdone := true
  2092. rows := xlsx1.GetRows(sheetname)
  2093. // 限制10000条,多余的截取掉
  2094. if len(rows) > 10000 {
  2095. rows = rows[:10000]
  2096. }
  2097. for i, row := range rows {
  2098. if i > 0 {
  2099. entry := make(map[string]interface{})
  2100. outentry := make(map[string]interface{})
  2101. for j, colCell := range rows[0] {
  2102. for k, colCell1 := range row {
  2103. if j == k {
  2104. outentry[colCell] = colCell1
  2105. entry[colCell] = colCell1
  2106. }
  2107. }
  2108. }
  2109. inputdata = ""
  2110. a := ""
  2111. fmt.Println(outentry, entry)
  2112. //校验日期格式
  2113. for _, v := range dateParamslist {
  2114. if v == "" {
  2115. continue
  2116. }
  2117. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2118. dtime, err := TransfTime(d.(string))
  2119. if err != nil {
  2120. a = strings.Trim(v, " ")
  2121. break
  2122. }
  2123. outentry[strings.Trim(v, " ")] = dtime
  2124. }
  2125. }
  2126. if a != "" {
  2127. outentry["error_msg"] = a + " 格式错误"
  2128. error++
  2129. queryData = append(queryData, outentry)
  2130. continue
  2131. }
  2132. a = ""
  2133. //校验必填格式
  2134. for _, v := range requiredParamslist {
  2135. if v == "" {
  2136. continue
  2137. }
  2138. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2139. a = strings.Trim(v, " ")
  2140. break
  2141. }
  2142. }
  2143. if a != "" {
  2144. outentry["error_msg"] = a + " 未填或格式错误"
  2145. error++
  2146. queryData = append(queryData, outentry)
  2147. continue
  2148. }
  2149. a = ""
  2150. //校验数字格式
  2151. for _, v := range numParamslist {
  2152. if v == "" {
  2153. continue
  2154. }
  2155. d, ok := outentry[strings.Trim(v, " ")]
  2156. if !ok || d == "" {
  2157. outentry[strings.Trim(v, " ")] = 0
  2158. } else {
  2159. var fl float64
  2160. switch d.(type) {
  2161. case string:
  2162. fl, err = strconv.ParseFloat(d.(string), 64)
  2163. }
  2164. if err != nil || fl < 0 {
  2165. a = strings.Trim(v, " ")
  2166. break
  2167. }
  2168. }
  2169. }
  2170. if a != "" {
  2171. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2172. error++
  2173. queryData = append(queryData, outentry)
  2174. continue
  2175. }
  2176. tx := restful.Engine.NewSession()
  2177. err := tx.Begin()
  2178. for _, sqlnamestr := range sqlslist {
  2179. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2180. paramslist := strings.Split(paramslists, ",")
  2181. if len(paramslist) > 0 {
  2182. s_params := make([]interface{}, 0)
  2183. for _, value := range paramslist {
  2184. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2185. if tempv, exists := c.Get("jwt_username"); exists {
  2186. s_params = append(s_params, tempv.(string))
  2187. } else {
  2188. s_params = append(s_params, "")
  2189. }
  2190. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2191. s_params = append(s_params, pastureid)
  2192. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2193. ids, err := setting.SnowIds.NextId()
  2194. if err != nil {
  2195. ids = time.Now().UnixNano()
  2196. logging.Info("create SnowIds err", err)
  2197. }
  2198. s_params = append(s_params, ids)
  2199. } else {
  2200. if outentry[strings.Trim(value, " ")] == nil {
  2201. s_params = append(s_params, "")
  2202. } else {
  2203. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2204. }
  2205. }
  2206. }
  2207. outentry["input"] = inputdata
  2208. fmt.Println(sql, s_params)
  2209. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2210. if err != nil {
  2211. if tx != nil {
  2212. tx.Rollback()
  2213. }
  2214. if tx != nil {
  2215. tx.Close()
  2216. }
  2217. msg := geterrmsg(err.Error())
  2218. outentry["error_msg"] = msg
  2219. error++
  2220. queryData = append(queryData, outentry)
  2221. isdone = true
  2222. break
  2223. } else {
  2224. if len(returnmsgmap1) > 0 {
  2225. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2226. if tx != nil {
  2227. tx.Rollback()
  2228. }
  2229. if tx != nil {
  2230. tx.Close()
  2231. }
  2232. msg := geterrmsg(va.(string))
  2233. outentry["error_msg"] = msg
  2234. error++
  2235. queryData = append(queryData, outentry)
  2236. isdone = true
  2237. break
  2238. }
  2239. }
  2240. isdone = false
  2241. }
  2242. }
  2243. }
  2244. switch {
  2245. case err != nil:
  2246. if tx != nil {
  2247. tx.Rollback()
  2248. }
  2249. default:
  2250. if tx != nil {
  2251. err = tx.Commit()
  2252. }
  2253. }
  2254. if tx != nil {
  2255. tx.Close()
  2256. }
  2257. }
  2258. if !isdone {
  2259. ok++
  2260. isdone = true
  2261. }
  2262. }
  2263. data := make(map[string]interface{})
  2264. data["result"] = queryData
  2265. data["success"] = ok
  2266. data["err_count"] = error
  2267. appG.Response(http.StatusOK, e.SUCCESS, data)
  2268. }
  2269. func TransfTime(timestr string) (string, error) {
  2270. if timestr == "" {
  2271. return time.Now().Format("2006-01-02"), nil
  2272. }
  2273. days, err := strconv.Atoi(timestr)
  2274. if err != nil {
  2275. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2276. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2277. }
  2278. _, err := time.Parse("2006-01-02", timestr)
  2279. if err != nil {
  2280. t, err := time.Parse("2006/01/02", timestr)
  2281. if err != nil {
  2282. t, err := time.Parse("2006.01.02", timestr)
  2283. if err != nil {
  2284. return "", err
  2285. } else {
  2286. return t.Format("2006-01-02"), nil
  2287. }
  2288. } else {
  2289. return t.Format("2006-01-02"), nil
  2290. }
  2291. } else {
  2292. return timestr, nil
  2293. }
  2294. }
  2295. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2296. times = times.AddDate(0, 0, days)
  2297. return times.Format("2006-01-02"), nil
  2298. }
  2299. func Createchart(c *gin.Context) {
  2300. appG := app.Gin{C: c}
  2301. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2302. fsion := gofasion.NewFasion(string(dataByte))
  2303. chart_name := fsion.Get("chart_name").ValueStr()
  2304. desc := fsion.Get("desc").ValueStr()
  2305. pastureid := fsion.Get("pastureid").ValueStr()
  2306. source_id := fsion.Get("source_id").ValueStr()
  2307. emp := fsion.Get("emp").ValueStr()
  2308. content := fsion.Get("content").Json()
  2309. var mapResult map[string]interface{}
  2310. err1 := json.Unmarshal([]byte(content), &mapResult)
  2311. if err1 != nil {
  2312. fmt.Println("JsonToMapDemo err: ", err1)
  2313. }
  2314. tx := restful.Engine.NewSession()
  2315. err := tx.Begin()
  2316. defer func() {
  2317. switch {
  2318. case err != nil:
  2319. logging.Error("tx.Begin 事务启动失败__error:", err)
  2320. if tx != nil {
  2321. tx.Rollback()
  2322. }
  2323. default:
  2324. if tx != nil {
  2325. err = tx.Commit()
  2326. }
  2327. }
  2328. if tx != nil {
  2329. tx.Close()
  2330. }
  2331. }()
  2332. ids, err := setting.SnowIds.NextId()
  2333. if err != nil {
  2334. ids = time.Now().UnixNano()
  2335. logging.Info("create SnowIds err", err)
  2336. }
  2337. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2338. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2339. if err != nil {
  2340. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2341. } else {
  2342. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2343. }
  2344. }
  2345. func Updatedashboard(c *gin.Context) {
  2346. appG := app.Gin{C: c}
  2347. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2348. fsion := gofasion.NewFasion(string(dataByte))
  2349. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2350. pastureid := fsion.Get("pastureid").ValueStr()
  2351. content := fsion.Get("content").Json()
  2352. var mapResult map[string]interface{}
  2353. err1 := json.Unmarshal([]byte(content), &mapResult)
  2354. if err1 != nil {
  2355. fmt.Println("JsonToMapDemo err: ", err1)
  2356. }
  2357. layout := mapResult["layout"]
  2358. tx := restful.Engine.NewSession()
  2359. err := tx.Begin()
  2360. defer func() {
  2361. switch {
  2362. case err != nil:
  2363. logging.Error("tx.Begin 事务启动失败__error:", err)
  2364. if tx != nil {
  2365. tx.Rollback()
  2366. }
  2367. default:
  2368. if tx != nil {
  2369. err = tx.Commit()
  2370. }
  2371. }
  2372. if tx != nil {
  2373. tx.Close()
  2374. }
  2375. }()
  2376. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2377. if err != nil {
  2378. println("2", err.Error())
  2379. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2380. } else {
  2381. if exec != nil {
  2382. if exec[0]["content"] == nil {
  2383. mapR := make(map[string]interface{})
  2384. mapR["layout"] = layout
  2385. mjson, _ := json.Marshal(mapR)
  2386. mString := string(mjson)
  2387. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2388. if err3 != nil {
  2389. println("3", err3.Error())
  2390. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2391. } else {
  2392. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2393. }
  2394. } else {
  2395. var mapR map[string]interface{}
  2396. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2397. if err1 != nil {
  2398. fmt.Println("JsonToMapDemo err: ", err2)
  2399. }
  2400. mapR["layout"] = layout
  2401. mjson, _ := json.Marshal(mapR)
  2402. mString := string(mjson)
  2403. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2404. if err3 != nil {
  2405. println("3", err3.Error())
  2406. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2407. } else {
  2408. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2409. }
  2410. }
  2411. } else {
  2412. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2413. }
  2414. }
  2415. }
  2416. func ExecSQL(c *gin.Context) {
  2417. appG := app.Gin{C: c}
  2418. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2419. fsion := gofasion.NewFasion(string(dataByte))
  2420. content := fsion.Get("content").Json()
  2421. pastureid := fsion.Get("pastureid").ValueStr()
  2422. var mapResult map[string]interface{}
  2423. err1 := json.Unmarshal([]byte(content), &mapResult)
  2424. if err1 != nil {
  2425. fmt.Println("JsonToMapDemo err: ", err1)
  2426. }
  2427. sqlstr := "select "
  2428. groupstr := " GROUP BY "
  2429. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2430. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2431. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2432. }
  2433. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2434. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2435. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2436. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2437. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2438. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2439. sqlstr = sqlstr + tem + ","
  2440. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2441. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2442. sqlstr = sqlstr + tem + ","
  2443. } else {
  2444. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2445. sqlstr = sqlstr + tem + ","
  2446. }
  2447. }
  2448. if _, ok := mapResult["selectedCalcul2"]; ok {
  2449. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2450. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2451. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2452. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2453. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2454. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2455. sqlstr = sqlstr + tem + ","
  2456. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2457. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2458. sqlstr = sqlstr + tem + ","
  2459. } else {
  2460. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2461. sqlstr = sqlstr + tem + ","
  2462. }
  2463. }
  2464. }
  2465. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2466. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2467. sqlstr = sqlstr + " where pastureid=" + pastureid
  2468. if len(mapResult["filters"].([]interface{})) > 0 {
  2469. sqlstr = sqlstr + " and "
  2470. }
  2471. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2472. for _, value := range mapResult["filters"].([]interface{}) {
  2473. switch value.(map[string]interface{})["filterOperator"].(string) {
  2474. case ">", "=", "<", ">=", "<=", "!=", "like":
  2475. 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 "
  2476. case "IN":
  2477. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2478. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2479. sqlstr = sqlstr + value1.(string) + ","
  2480. }
  2481. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2482. sqlstr = sqlstr + ")" + " AND "
  2483. case "BETWEEN":
  2484. 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 "
  2485. }
  2486. }
  2487. if len(mapResult["filters"].([]interface{})) > 0 {
  2488. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2489. }
  2490. //
  2491. groupstr = groupstr[0 : len(groupstr)-1]
  2492. sqlstr = sqlstr + groupstr + " "
  2493. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2494. sqlstr = sqlstr + " order by "
  2495. }
  2496. //
  2497. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2498. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2499. sqlstr = sqlstr + value.(string) + " "
  2500. } else {
  2501. sqlstr = sqlstr + value.(string) + ","
  2502. }
  2503. }
  2504. //
  2505. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2506. tx := restful.Engine.NewSession()
  2507. err := tx.Begin()
  2508. defer func() {
  2509. switch {
  2510. case err != nil:
  2511. logging.Error("tx.Begin 事务启动失败__error:", err)
  2512. if tx != nil {
  2513. tx.Rollback()
  2514. }
  2515. default:
  2516. if tx != nil {
  2517. err = tx.Commit()
  2518. }
  2519. }
  2520. if tx != nil {
  2521. tx.Close()
  2522. }
  2523. }()
  2524. exec, err := tx.SQL(sqlstr).Query().List()
  2525. if err != nil {
  2526. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2527. } else {
  2528. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2529. }
  2530. }
  2531. func Dashboards(c *gin.Context) {
  2532. appG := app.Gin{C: c}
  2533. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2534. fsion := gofasion.NewFasion(string(dataByte))
  2535. sqlnamestr := fsion.Get("name").ValueStr()
  2536. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2537. offset := fsion.Get("offset").ValueDefaultInt(0)
  2538. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2539. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2540. month := fsion.Get("month").ValueDefaultStr("map")
  2541. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2542. tx := restful.Engine.NewSession()
  2543. err := tx.Begin()
  2544. defer func() {
  2545. switch {
  2546. case err != nil:
  2547. if tx != nil {
  2548. tx.Rollback()
  2549. }
  2550. default:
  2551. if tx != nil {
  2552. err = tx.Commit()
  2553. }
  2554. }
  2555. if tx != nil {
  2556. tx.Close()
  2557. }
  2558. }()
  2559. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2560. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2561. if sql != "" {
  2562. s_params := make([]interface{}, 0)
  2563. if fsion.HasKey("parammaps") {
  2564. parammaps := fsion.Get("parammaps")
  2565. paramslist := strings.Split(p, ",")
  2566. if len(paramslist) > 0 && p != "" {
  2567. for _, value := range paramslist {
  2568. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2569. if tempv, exists := c.Get("jwt_username"); exists {
  2570. s_params = append(s_params, tempv.(string))
  2571. } else {
  2572. s_params = append(s_params, "")
  2573. }
  2574. } else {
  2575. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2576. }
  2577. }
  2578. }
  2579. }
  2580. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2581. if err != nil {
  2582. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2583. } else {
  2584. //paramslist1 := strings.Split(p1, ",")
  2585. dids := make([]interface{}, 0)
  2586. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2587. var mapResult map[string]interface{}
  2588. dids = append(dids, value["dashboard_id"])
  2589. if value["content"] != nil {
  2590. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2591. if err1 != nil {
  2592. println("JsonToMapDemo1 err: ", err1)
  2593. }
  2594. temap := make(map[string]interface{})
  2595. tem := mapResult["layout"].([]interface{})
  2596. if v, ok := value["chartids"]; ok {
  2597. chartids := strings.Split(v.(string), ",")
  2598. for _, va := range chartids {
  2599. a := false
  2600. for _, v2 := range tem {
  2601. if v2.(map[string]interface{})["id"].(string) == va {
  2602. a = true
  2603. //println("va1======",va)
  2604. }
  2605. }
  2606. if !a {
  2607. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2608. va + "\",\"id\":\"" + va +
  2609. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2610. var mapTem map[string]interface{}
  2611. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2612. if err1 != nil {
  2613. println("JsonToMapDemo err: ", err1)
  2614. }
  2615. tem = append(tem, mapTem)
  2616. }
  2617. }
  2618. temap["layout"] = tem
  2619. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2620. }
  2621. } else {
  2622. temap := make(map[string]interface{})
  2623. tem := make([]interface{}, 0)
  2624. if v, ok := value["chartids"]; ok {
  2625. chartids := strings.Split(v.(string), ",")
  2626. for _, va := range chartids {
  2627. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2628. va + "\",\"id\":\"" + va +
  2629. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2630. var mapTem map[string]interface{}
  2631. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2632. if err1 != nil {
  2633. println("JsonToMapDemo err: ", err1)
  2634. }
  2635. tem = append(tem, mapTem)
  2636. }
  2637. temap["layout"] = tem
  2638. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2639. }
  2640. }
  2641. }
  2642. queryData.(map[string]interface{})["order"] = dids
  2643. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2644. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2645. }
  2646. } else {
  2647. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2648. }
  2649. }
  2650. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2651. fsion := gofasion.NewFasion(parammaps)
  2652. sqlnamestr := fsion.Get("name").ValueStr()
  2653. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2654. offset := fsion.Get("offset").ValueDefaultInt(0)
  2655. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2656. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2657. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2658. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2659. body := []byte("")
  2660. if sql != "" {
  2661. s_params := make([]interface{}, 0)
  2662. if fsion.HasKey("parammaps") {
  2663. parammaps := fsion.Get("parammaps")
  2664. paramslist := strings.Split(p, ",")
  2665. if len(paramslist) > 0 && p != "" {
  2666. for _, value := range paramslist {
  2667. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2668. }
  2669. }
  2670. }
  2671. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2672. if err != nil {
  2673. } else {
  2674. paramslist1 := strings.Split(p1, ",")
  2675. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2676. s_params1 := make([]interface{}, 0)
  2677. if len(paramslist1) > 0 && p1 != "" {
  2678. for _, v := range paramslist1 {
  2679. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2680. }
  2681. }
  2682. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2683. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2684. body, _ = json.Marshal(queryData)
  2685. }
  2686. }
  2687. }
  2688. bs := bytes.NewBuffer(body)
  2689. client := &http.Client{}
  2690. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2691. req, err := http.NewRequest(RequestMethod,
  2692. url,
  2693. bs,
  2694. )
  2695. if err != nil {
  2696. }
  2697. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2698. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2699. if err != nil {
  2700. // handle error
  2701. }
  2702. resp, err := client.Do(req)
  2703. if err != nil {
  2704. return ""
  2705. }
  2706. defer resp.Body.Close()
  2707. result_body, err := ioutil.ReadAll(resp.Body)
  2708. if err != nil {
  2709. return ""
  2710. }
  2711. fmt.Println(string(result_body))
  2712. return ""
  2713. }
  2714. func GetSummary(c *gin.Context) {
  2715. appG := app.Gin{C: c}
  2716. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2717. fsion := gofasion.NewFasion(string(dataByte))
  2718. offset := fsion.Get("offset").ValueDefaultInt(0)
  2719. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2720. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2721. parammaps := fsion.Get("parammaps")
  2722. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2723. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2724. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2725. tx := restful.Engine.NewSession()
  2726. defer tx.Close()
  2727. sqlnamestr := ""
  2728. if genre == "0" {
  2729. if status == "0" {
  2730. sqlnamestr = "getAccuracyJSY"
  2731. } else if status == "1" {
  2732. sqlnamestr = "getAccuracyHFT"
  2733. } else if status == "2" {
  2734. sqlnamestr = "getAccuracyHNS"
  2735. } else if status == "3" {
  2736. sqlnamestr = "getAccuracyHSC"
  2737. } else if status == "4" {
  2738. sqlnamestr = "getAccuracyHCC"
  2739. } else if status == "5" {
  2740. sqlnamestr = "getAccuracyMC"
  2741. } else if status == "6" {
  2742. sqlnamestr = "getAccuracyFeedHL"
  2743. } else if status == "7" {
  2744. sqlnamestr = "getAccuracyRT"
  2745. }
  2746. } else {
  2747. if status == "0" {
  2748. sqlnamestr = "getAccuracySCCJSY"
  2749. } else if status == "1" {
  2750. sqlnamestr = "getAccuracySFT"
  2751. } else if status == "2" {
  2752. sqlnamestr = "getAccuracySNS"
  2753. } else if status == "3" {
  2754. sqlnamestr = "getAccuracySSC"
  2755. } else if status == "4" {
  2756. sqlnamestr = "getAccuracySCC"
  2757. } else if status == "5" {
  2758. sqlnamestr = "getAccuracySLCL"
  2759. } else if status == "7" {
  2760. sqlnamestr = "getAccuracySCCRT"
  2761. }
  2762. }
  2763. if isDate == "1" {
  2764. sqlnamestr += "Date"
  2765. }
  2766. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2767. // fmt.Println(sqlnamestr, sql)
  2768. if sql != "" {
  2769. s_params := make([]interface{}, 0)
  2770. // if fsion.HasKey("parammaps") {
  2771. fmt.Println(s_params, "222", p)
  2772. paramslist := strings.Split(p, ",")
  2773. if len(paramslist) > 0 && p != "" {
  2774. for _, value := range paramslist {
  2775. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2776. if tempv, exists := c.Get("jwt_username"); exists {
  2777. s_params = append(s_params, tempv.(string))
  2778. } else {
  2779. s_params = append(s_params, "")
  2780. }
  2781. } else {
  2782. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2783. }
  2784. }
  2785. }
  2786. if returntype == "xlsx" {
  2787. var xlsxfile *xlsx.File
  2788. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2789. //c.File("c:/dd.xlsx")
  2790. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2791. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2792. c.Header("Content-Transfer-Encoding", "binary")
  2793. _ = xlsxfile.Write(c.Writer)
  2794. } else {
  2795. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2796. if err != nil {
  2797. logging.Error("GetDataByName err: ", err)
  2798. msg := geterrmsg(err.Error())
  2799. appG.Response(http.StatusOK, e.ERROR, msg)
  2800. } else {
  2801. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2802. }
  2803. }
  2804. } else {
  2805. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2806. }
  2807. }
  2808. // type lpplanStruct struct {
  2809. // Id int64 `xorm:"id"`
  2810. // Tmrname string `xorm:"tmrname"`
  2811. // Tmrid int64 `xorm:"tmrid"`
  2812. // Sort int64 `xorm:"sort"`
  2813. // Sel int64 `xorm:"sel"`
  2814. // Times int64 `xorm:"times"`
  2815. // Ftname string `xorm:"ftname"`
  2816. // Ftid int64 `xorm:"ftid"`
  2817. // Maxweight float64 `xorm:"maxweight"`
  2818. // Sumweight float64 `xorm:"sumweight"`
  2819. // Sumcowcount int64 `xorm:"sumcowcount"`
  2820. // Pastureid string `xorm:"pastureid"`
  2821. // Display string `xorm:"display"`
  2822. // Issplit int64 `xorm:"issplit"`
  2823. // BeginTime string `xorm:"begintime"`
  2824. // }
  2825. func UpdateFTdetail(c *gin.Context) {
  2826. appG := app.Gin{C: c}
  2827. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2828. tempval_ := make(map[string]interface{})
  2829. tempCommon := make(map[string]interface{})
  2830. tempval := make([]map[string]interface{}, 0)
  2831. fTChange := make(map[string]interface{}, 0)
  2832. // fpdOldDataList := make([]map[string]interface{}, 0)
  2833. // fpdDataList := make([]map[string]interface{}, 0)
  2834. fsion := gofasion.NewFasion(string(dataByte))
  2835. // parammaps := fsion.Get("parammaps")
  2836. createdate := time.Now().Format("2006-01-02 15:04:05")
  2837. err := json.Unmarshal(dataByte, &tempval_)
  2838. if err != nil {
  2839. appG.Response(http.StatusOK, e.ERROR, false)
  2840. return
  2841. }
  2842. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2843. tx := restful.Engine.NewSession()
  2844. if v, ok := tempval_["data"].([]interface{}); ok {
  2845. for _, Tvalue := range v {
  2846. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2847. if v1["name"] == "updateFPbyFTChange" {
  2848. fTChange = v1
  2849. continue
  2850. }
  2851. tempval = append(tempval, v1)
  2852. }
  2853. }
  2854. }
  2855. parammaps := fTChange["parammaps"].(map[string]interface{})
  2856. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2857. // if err != nil {
  2858. // logs.Error(err)
  2859. // appG.Response(http.StatusOK, e.ERROR, false)
  2860. // return
  2861. // }
  2862. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2863. // if err != nil {
  2864. // logs.Error(err)
  2865. // appG.Response(http.StatusOK, e.ERROR, false)
  2866. // return
  2867. // }
  2868. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2869. // if err != nil {
  2870. // logs.Error(err)
  2871. // appG.Response(http.StatusOK, e.ERROR, false)
  2872. // return
  2873. // }
  2874. err = tx.Begin()
  2875. if err != nil {
  2876. logging.Error("tx.Begin 事务启动失败__error:", err)
  2877. }
  2878. defer func() {
  2879. if err != nil {
  2880. if tx != nil {
  2881. tx.Rollback()
  2882. }
  2883. }
  2884. if tx != nil {
  2885. tx.Close()
  2886. }
  2887. }()
  2888. if err != nil {
  2889. } else {
  2890. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2891. tempCommon = v
  2892. }
  2893. // 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 ,
  2894. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2895. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2896. // UNION
  2897. // 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 ,
  2898. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2899. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2900. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2901. if err == nil {
  2902. if tempv, exists := c.Get("jwt_username"); exists {
  2903. tempCommon["jwt_username"] = tempv.(string)
  2904. }
  2905. for _, paramvalue := range tempval {
  2906. if _, ok := paramvalue["resultname"]; !ok {
  2907. paramvalue["resultname"] = paramvalue["name"]
  2908. }
  2909. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2910. if err != nil {
  2911. logging.Error("ExecDataParam error:", err)
  2912. break
  2913. }
  2914. }
  2915. if err != nil {
  2916. msg := geterrmsg(err.Error())
  2917. appG.Response(http.StatusOK, e.ERROR, msg)
  2918. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2919. }
  2920. }
  2921. }
  2922. tx.Commit()
  2923. // go func() {
  2924. if fTChange != nil {
  2925. parammaps := fTChange["parammaps"].(map[string]interface{})
  2926. if parammaps["type"].(float64) == 1 {
  2927. _, err = tx.SQL(`UPDATE feedp fp
  2928. set
  2929. ccountratio = ccount *(ratio /100 ),
  2930. fp.ftweight= IFNULL(IF(
  2931. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2932. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2933. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2934. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2935. ),0),fp.feedweight = IFNULL(IF(
  2936. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2937. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2938. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2939. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2940. ),0) +ifnull(fp.supplyweight,0)
  2941. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2942. _, err = tx.SQL(`UPDATE fpdetail fpd
  2943. INNER JOIN feedp fp
  2944. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2945. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2946. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2947. } else {
  2948. _, err = tx.SQL(`UPDATE feedp fp
  2949. SET ccountratio = ccount *(ratio /100 ),
  2950. fp.supplyweight= IFNULL(IF(
  2951. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2952. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2953. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2954. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2955. ),0),fp.feedweight = IFNULL(IF(
  2956. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2957. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2958. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2959. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2960. ),0) +ifnull(fp.supplyweight,0)
  2961. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2962. _, err = tx.SQL(`UPDATE fpdetail fpd
  2963. INNER JOIN feedp fp
  2964. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2965. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2966. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2967. }
  2968. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  2969. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  2970. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  2971. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  2972. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  2973. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  2974. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  2975. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  2976. join feedtemplet ft on ft.id = fp.ftid where ft.id = ?`, parammaps["ftid"]).QueryString()
  2977. // fmt.Println(ftId)
  2978. FpdBatchEditGrfd(fmt.Sprintf("%v", parammaps["pastureid"]), values1)
  2979. // 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 ,
  2980. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2981. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2982. // UNION
  2983. // 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 ,
  2984. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2985. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2986. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2987. // lpplanList := make([]*lpplanStruct, 0)
  2988. // err = tx.SQL(`select id,times,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpplan.pastureid ) = 0 ,
  2989. // ifnull((select maxstirfeed from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),100000),(select ifnull(volume,0) from tmr where id = lpplan.tmrid ) *
  2990. // (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)
  2991. // if err != nil {
  2992. // logs.Error(err, 1)
  2993. // return
  2994. // }
  2995. // lppidlist := []string{}
  2996. // for _, lpp := range lpplanList {
  2997. // lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2998. // }
  2999. // if len(lppidlist) <= 0 {
  3000. // appG.Response(http.StatusOK, e.SUCCESS, true)
  3001. // return
  3002. // }
  3003. // lpplandtl1AllList := make([]*lpplandtl1, 0)
  3004. // err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  3005. // order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  3006. // if err != nil {
  3007. // // tx.Rollback()
  3008. // logs.Error(err, 2, parammaps["pastureid"])
  3009. // return
  3010. // }
  3011. // for _, lpp := range lpplandtl1AllList {
  3012. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  3013. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  3014. // if err != nil {
  3015. // logs.Error(err)
  3016. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3017. // return
  3018. // }
  3019. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3020. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  3021. // if err != nil {
  3022. // logs.Error(err)
  3023. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3024. // return
  3025. // }
  3026. // }
  3027. // var wg sync.WaitGroup
  3028. // for _, old := range fpdOldDataList {
  3029. // for _, fpd := range fpdDataList {
  3030. // wg.Add(1)
  3031. // go func(old, fpd map[string]interface{}) {
  3032. // updateLppandList := make([]*lpplandtl1, 0)
  3033. // defer wg.Done()
  3034. // if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3035. // fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3036. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3037. // oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3038. // // if weight > oldweight {
  3039. // // return
  3040. // // }
  3041. // var w float64
  3042. // var status int
  3043. // if weight < oldweight {
  3044. // if weight >= 0 {
  3045. // return
  3046. // }
  3047. // w = weight
  3048. // status = 0
  3049. // } else {
  3050. // if oldweight > 0 {
  3051. // return
  3052. // }
  3053. // w = weight
  3054. // status = 1
  3055. // }
  3056. // // fweight = w
  3057. // for _, lpp := range lpplanList {
  3058. // var fweight float64
  3059. // var lweight float64
  3060. // lpplandtl1List := make([]*lpplandtl1, 0)
  3061. // fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3062. // for _, lppland := range lpplandtl1AllList {
  3063. // if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3064. // lpplandtl1List = append(lpplandtl1List, lppland)
  3065. // }
  3066. // }
  3067. // if len(lpplandtl1List) == 0 {
  3068. // continue
  3069. // }
  3070. // for _, lppland := range lpplandtl1List {
  3071. // lweight += lppland.Lweight
  3072. // }
  3073. // if status == 0 {
  3074. // if lweight <= 0 {
  3075. // continue
  3076. // }
  3077. // } else {
  3078. // if lpp.Maxweight <= lweight {
  3079. // continue
  3080. // }
  3081. // }
  3082. // for _, lppland := range lpplandtl1List {
  3083. // if fpdid == lppland.Fpdid {
  3084. // if status == 1 {
  3085. // // if w <= lppland.Lweight {
  3086. // if lpp.Maxweight <= lweight {
  3087. // continue
  3088. // }
  3089. // if w+lweight <= lpp.Maxweight {
  3090. // lppland.Lweight += w
  3091. // lweight += w
  3092. // fweight += w
  3093. // w = 0
  3094. // } else {
  3095. // w = w - (lpp.Maxweight - lweight)
  3096. // n := (lpp.Maxweight - lweight)
  3097. // lppland.Lweight = lppland.Lweight + n
  3098. // lweight += n
  3099. // fweight += n
  3100. // }
  3101. // } else {
  3102. // if lppland.Lweight == 0 {
  3103. // continue
  3104. // }
  3105. // if w+lppland.Lweight >= 0 {
  3106. // lppland.Lweight = lppland.Lweight + w
  3107. // lweight = lweight + w
  3108. // fweight = fweight + w
  3109. // w = 0
  3110. // } else {
  3111. // w = w + lppland.Lweight
  3112. // lweight = lweight - lppland.Lweight
  3113. // fweight = fweight - lppland.Lweight
  3114. // lppland.Lweight = 0
  3115. // }
  3116. // }
  3117. // updateLppandList = append(updateLppandList, lppland)
  3118. // break
  3119. // }
  3120. // }
  3121. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3122. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3123. // WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3124. // if err != nil {
  3125. // // tx.Rollback()
  3126. // logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3127. // return
  3128. // }
  3129. // for _, lppland := range updateLppandList {
  3130. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3131. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3132. // if err != nil {
  3133. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3134. // // tx.Rollback()
  3135. // logs.Error(err, 3)
  3136. // return
  3137. // }
  3138. // // defer wg.Done()
  3139. // }
  3140. // updateLppandList = []*lpplandtl1{}
  3141. // if w == 0 {
  3142. // break
  3143. // }
  3144. // }
  3145. // }
  3146. // }(old, fpd)
  3147. // }
  3148. // }
  3149. // wg.Wait()
  3150. }
  3151. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3152. if err != nil {
  3153. logs.Error(err)
  3154. appG.Response(http.StatusOK, e.ERROR, false)
  3155. return
  3156. }
  3157. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3158. if err != nil {
  3159. logs.Error(err)
  3160. appG.Response(http.StatusOK, e.ERROR, false)
  3161. return
  3162. }
  3163. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3164. if err != nil {
  3165. logs.Error(err)
  3166. appG.Response(http.StatusOK, e.ERROR, false)
  3167. return
  3168. }
  3169. now := createdate
  3170. // for _, oldFpd := range oldFpdDataList {
  3171. for _, newFpd := range newFpdDataList {
  3172. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3173. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3174. // go func() {
  3175. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3176. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3177. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3178. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3179. if err != nil {
  3180. logs.Error(err)
  3181. appG.Response(http.StatusOK, e.ERROR, false)
  3182. return
  3183. }
  3184. // }()
  3185. }
  3186. // break
  3187. // }
  3188. // }
  3189. // }
  3190. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3191. for _, newLpplandtl1 := range newLpplandtl1List {
  3192. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3193. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3194. // go func() {
  3195. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3196. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3197. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3198. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3199. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3200. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3201. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3202. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3203. if err != nil {
  3204. logs.Error(err)
  3205. appG.Response(http.StatusOK, e.ERROR, false)
  3206. return
  3207. }
  3208. // }()
  3209. // }
  3210. // break
  3211. // }
  3212. // }
  3213. }
  3214. // for _, oldFeedp := range oldFeedpList {
  3215. for _, newFeedp := range newFeedpList {
  3216. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3217. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3218. // go func() {
  3219. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3220. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3221. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3222. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3223. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3224. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3225. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3226. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3227. if err != nil {
  3228. logs.Error(err)
  3229. appG.Response(http.StatusOK, e.ERROR, false)
  3230. return
  3231. }
  3232. }
  3233. // ,,parammaps["ftid"])
  3234. // surplus, surplusId, id, pastureId string
  3235. // FtdetailSurplusFt(parammaps["ftid"].)
  3236. ftList1, err := tx.SQL(` SELECT
  3237. f.id,
  3238. f.surplus surplusId,
  3239. f.pastureid,
  3240. s.surplus
  3241. FROM
  3242. feedtemplet f
  3243. JOIN surplus s ON s.id = f.surplus
  3244. WHERE
  3245. f.id = ?`, parammaps["ftid"]).QueryString()
  3246. for _, ft := range ftList1 {
  3247. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3248. }
  3249. appG.Response(http.StatusOK, e.SUCCESS, true)
  3250. }
  3251. type lpplandtlInfo struct {
  3252. Id int64 `xorm:"id"`
  3253. Pastureid int64 `xorm:"pastureid"`
  3254. Lppid int64 `xorm:"lppid"`
  3255. Barid int64 `xorm:"barid"`
  3256. Barname string `xorm:"barname"`
  3257. Fpdid int64 `xorm:"fpdid"`
  3258. Fttype int64 `xorm:"fttype"`
  3259. Lweight float64 `xorm:"lweight"`
  3260. Sort int64 `xorm:"sort"`
  3261. Tmrid int64 `xorm:"tmrid"`
  3262. Tmrname string `xorm:"tmrname"`
  3263. Cowcount int64 `xorm:"cowcount"`
  3264. Ccountradio float64 `xorm:"ccountradio"`
  3265. Background string `xorm:"background"`
  3266. Lweighthis float64 `xorm:"lweighthis"`
  3267. Maxweight float64 `xorm:"maxweight"`
  3268. }
  3269. func UpdateFpdetailBar(c *gin.Context) {
  3270. appG := app.Gin{C: c}
  3271. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3272. fsion := gofasion.NewFasion(string(dataByte))
  3273. pastureid := fsion.Get("pastureid").ValueStr()
  3274. id := fsion.Get("id").ValueStr()
  3275. tx := restful.Engine.NewSession()
  3276. tx.Begin()
  3277. 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 `,
  3278. pastureid, id).Query().List()
  3279. if err != nil {
  3280. logs.Error(err)
  3281. }
  3282. for _, fpd := range fpdList {
  3283. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3284. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3285. pastureid, fpd["id"]).Query().List()
  3286. if err != nil {
  3287. tx.Rollback()
  3288. logs.Error(err)
  3289. appG.Response(http.StatusOK, e.ERROR, false)
  3290. return
  3291. }
  3292. var lweight float64
  3293. for _, lppland := range lpplandList {
  3294. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3295. lweight += lweight1
  3296. }
  3297. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3298. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3299. if fpdweight >= ptuse && lweight == ptuse {
  3300. continue
  3301. } else {
  3302. if lweight <= fpdweight {
  3303. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3304. if err != nil {
  3305. tx.Rollback()
  3306. logs.Error(err)
  3307. appG.Response(http.StatusOK, e.ERROR, false)
  3308. return
  3309. }
  3310. } else {
  3311. weight := fpdweight - lweight
  3312. for _, lppland := range lpplandList {
  3313. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3314. if weight >= lpplandlweight {
  3315. weight = weight - lpplandlweight
  3316. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3317. if err != nil {
  3318. tx.Rollback()
  3319. logs.Error(err)
  3320. appG.Response(http.StatusOK, e.ERROR, false)
  3321. return
  3322. }
  3323. } else {
  3324. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3325. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3326. // if err != nil {
  3327. // tx.Rollback()
  3328. // logs.Error(err)
  3329. // appG.Response(http.StatusOK, e.ERROR, false)
  3330. // return
  3331. // }
  3332. weight = 0
  3333. break
  3334. }
  3335. }
  3336. }
  3337. }
  3338. }
  3339. fsionData := fsion.Get("data").Array()
  3340. for _, list := range fsionData {
  3341. ftmap := make(map[string]interface{})
  3342. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3343. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3344. ftmap["times"] = list.Get("times").ValueInt64()
  3345. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3346. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3347. // fmt.Println(ftmap)
  3348. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3349. // and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3350. // if count == 1 {
  3351. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3352. // and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3353. // if err != nil {
  3354. // tx.Rollback()
  3355. // logs.Error(err)
  3356. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3357. // return
  3358. // }
  3359. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3360. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3361. // if err != nil {
  3362. // tx.Rollback()
  3363. // logs.Error(err)
  3364. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3365. // return
  3366. // }
  3367. // }
  3368. fpdDataList, err := tx.SQL(`
  3369. 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 ,
  3370. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3371. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3372. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3373. if err != nil {
  3374. tx.Rollback()
  3375. logs.Error(err)
  3376. }
  3377. for _, fpd := range fpdDataList {
  3378. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3379. fttype := -1
  3380. if fpd["fttype"].(string) == "1" {
  3381. fttype = 1
  3382. }
  3383. var fweight float64
  3384. var lweight float64
  3385. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3386. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  3387. t.maxstirfeed,(select ifnull(volume,0) from tmr where id = lpp.tmrid ) *
  3388. (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  3389. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3390. join tmr t on t.id = lpp.tmrid
  3391. where lppland.fpdid =?
  3392. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3393. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3394. if err != nil {
  3395. tx.Rollback()
  3396. logs.Error(err)
  3397. }
  3398. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3399. var w float64
  3400. var status int
  3401. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3402. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3403. if weight >= 0 {
  3404. continue
  3405. }
  3406. w = weight
  3407. status = 0
  3408. } else {
  3409. // continue
  3410. if weight <= 0 {
  3411. continue
  3412. }
  3413. w = weight
  3414. status = 1
  3415. }
  3416. // for _, lppland := range lpplandtl1List {
  3417. // lweight += lppland.Lweight
  3418. // }
  3419. for _, lppland := range lpplandtl1List {
  3420. lpplandInfo := new(lpplandtlInfo)
  3421. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3422. lweight = lpplandInfo.Lweight
  3423. if status == 1 {
  3424. // if w <= lppland.Lweight {
  3425. if lppland.Maxweight <= lweight {
  3426. continue
  3427. }
  3428. if w+lweight <= lppland.Maxweight {
  3429. lppland.Lweight += w
  3430. lweight += w
  3431. fweight += w
  3432. w = 0
  3433. } else {
  3434. w = w - (lppland.Maxweight - lweight)
  3435. n := (lppland.Maxweight - lweight)
  3436. lppland.Lweight = lppland.Lweight + n
  3437. lweight += n
  3438. fweight += n
  3439. }
  3440. } else {
  3441. if lppland.Lweight == 0 {
  3442. continue
  3443. }
  3444. if w+lppland.Lweight >= 0 {
  3445. lppland.Lweight = lppland.Lweight + w
  3446. lweight = lweight + w
  3447. fweight = fweight + w
  3448. w = 0
  3449. } else {
  3450. w = w + lppland.Lweight
  3451. lweight = lweight - lppland.Lweight
  3452. fweight = fweight - lppland.Lweight
  3453. lppland.Lweight = 0
  3454. }
  3455. }
  3456. if lppland.Lweight > 0 {
  3457. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3458. if err != nil {
  3459. tx.Rollback()
  3460. logs.Error(err)
  3461. return
  3462. }
  3463. } else {
  3464. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3465. if err != nil {
  3466. tx.Rollback()
  3467. logs.Error(err)
  3468. return
  3469. }
  3470. }
  3471. if w == 0 {
  3472. break
  3473. }
  3474. // break
  3475. }
  3476. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3477. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3478. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3479. if err != nil {
  3480. tx.Rollback()
  3481. logs.Error(err)
  3482. }
  3483. if w == 0 {
  3484. break
  3485. }
  3486. }
  3487. }
  3488. }
  3489. tx.Commit()
  3490. now := time.Now()
  3491. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3492. if err != nil {
  3493. logs.Error(err)
  3494. appG.Response(http.StatusOK, e.ERROR, false)
  3495. return
  3496. }
  3497. for _, newLpplandtl1 := range newLpplandtl1List {
  3498. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3499. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3500. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3501. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3502. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3503. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3504. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3505. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3506. if err != nil {
  3507. logs.Error(err)
  3508. appG.Response(http.StatusOK, e.ERROR, false)
  3509. return
  3510. }
  3511. }
  3512. appG.Response(http.StatusOK, e.SUCCESS, true)
  3513. }
  3514. func GetProcessAnalysis(c *gin.Context) {
  3515. appG := app.Gin{C: c}
  3516. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3517. fsion := gofasion.NewFasion(string(dataByte))
  3518. sqlnamestr := fsion.Get("name").ValueStr()
  3519. offset := fsion.Get("offset").ValueDefaultInt(0)
  3520. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3521. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3522. parammaps := fsion.Get("parammaps")
  3523. tx := restful.Engine.NewSession()
  3524. err := tx.Begin()
  3525. defer func() {
  3526. switch {
  3527. case err != nil:
  3528. logging.Error("tx.Begin 事务启动失败__error:", err)
  3529. if tx != nil {
  3530. tx.Rollback()
  3531. }
  3532. default:
  3533. if tx != nil {
  3534. err = tx.Commit()
  3535. }
  3536. }
  3537. if tx != nil {
  3538. tx.Close()
  3539. }
  3540. }()
  3541. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3542. s_params := make([]interface{}, 0)
  3543. paramslist := strings.Split(p, ",")
  3544. if len(paramslist) > 0 && p != "" {
  3545. for _, value := range paramslist {
  3546. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3547. if tempv, exists := c.Get("jwt_username"); exists {
  3548. s_params = append(s_params, tempv.(string))
  3549. } else {
  3550. s_params = append(s_params, "")
  3551. }
  3552. } else {
  3553. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3554. }
  3555. }
  3556. }
  3557. tmrtnameStr := ""
  3558. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3559. if len(tmrtnameStr) == 0 {
  3560. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3561. } else {
  3562. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3563. }
  3564. }
  3565. if len(tmrtnameStr) > 0 {
  3566. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3567. }
  3568. sql += " ORDER BY d.intime"
  3569. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3570. if err != nil {
  3571. logging.Error("GetDataByName err: ", err)
  3572. msg := geterrmsg(err.Error())
  3573. appG.Response(http.StatusOK, e.ERROR, msg)
  3574. } else {
  3575. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3576. }
  3577. }
  3578. func UpdateFeedtempletStatus(c *gin.Context) {
  3579. appG := app.Gin{C: c}
  3580. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3581. fsion := gofasion.NewFasion(string(dataByte))
  3582. parammaps := fsion.Get("parammaps")
  3583. tx := restful.Engine.NewSession()
  3584. tx.Begin()
  3585. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3586. if err != nil {
  3587. tx.Rollback()
  3588. logs.Error(err)
  3589. appG.Response(http.StatusOK, e.ERROR, err)
  3590. return
  3591. }
  3592. tx.Commit()
  3593. appG.Response(http.StatusOK, e.SUCCESS, true)
  3594. }
  3595. func AddFtdry(c *gin.Context) {
  3596. appG := app.Gin{C: c}
  3597. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3598. fsion := gofasion.NewFasion(string(dataByte))
  3599. sqlnamestr := fsion.Get("name").ValueStr()
  3600. s_params := make([]interface{}, 0)
  3601. tx := restful.Engine.NewSession()
  3602. err := tx.Begin()
  3603. defer func() {
  3604. switch {
  3605. case err != nil:
  3606. if tx != nil {
  3607. tx.Rollback()
  3608. }
  3609. default:
  3610. if tx != nil {
  3611. err = tx.Commit()
  3612. }
  3613. }
  3614. if tx != nil {
  3615. tx.Close()
  3616. }
  3617. }()
  3618. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3619. if sql != "" {
  3620. parammaps := fsion.Get("parammaps")
  3621. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3622. paramslist := strings.Split(p, ",")
  3623. if len(paramslist) > 0 && p != "" {
  3624. for _, value := range paramslist {
  3625. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3626. if tempv, exists := c.Get("jwt_username"); exists {
  3627. s_params = append(s_params, tempv.(string))
  3628. } else {
  3629. s_params = append(s_params, "")
  3630. }
  3631. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3632. ids, err := setting.SnowIds.NextId()
  3633. if err != nil {
  3634. ids = time.Now().UnixNano()
  3635. logging.Info("create SnowIds err", err)
  3636. }
  3637. s_params = append(s_params, ids)
  3638. } else {
  3639. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3640. }
  3641. }
  3642. }
  3643. var actweight float64
  3644. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3645. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3646. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3647. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3648. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3649. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3650. 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()
  3651. if err != nil {
  3652. logging.Error("AddFtdry err: ", err)
  3653. msg := geterrmsg(err.Error())
  3654. appG.Response(http.StatusOK, e.ERROR, msg)
  3655. }
  3656. if len(actweightList) > 0 {
  3657. for _, item := range actweightList {
  3658. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3659. if err != nil {
  3660. logging.Error("AddFtdry err: ", err)
  3661. msg := geterrmsg(err.Error())
  3662. appG.Response(http.StatusOK, e.ERROR, msg)
  3663. }
  3664. actweight = fl
  3665. }
  3666. } else {
  3667. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3668. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3669. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3670. if err != nil {
  3671. logging.Error("AddFtdry err: ", err)
  3672. msg := geterrmsg(err.Error())
  3673. appG.Response(http.StatusOK, e.ERROR, msg)
  3674. }
  3675. for _, item := range dryList {
  3676. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3677. if err != nil {
  3678. logging.Error("AddFtdry err: ", err)
  3679. msg := geterrmsg(err.Error())
  3680. appG.Response(http.StatusOK, e.ERROR, msg)
  3681. }
  3682. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3683. }
  3684. }
  3685. if sqlnamestr == "insertFtdry" {
  3686. s_params = append(s_params, actweight)
  3687. } else if sqlnamestr == "updateFtdry" {
  3688. sql = fmt.Sprintf(sql, actweight)
  3689. }
  3690. queryData, err := execDataBySqlT(sql, s_params, tx)
  3691. if err != nil {
  3692. logging.Error("AddFtdry err: ", err)
  3693. msg := geterrmsg(err.Error())
  3694. appG.Response(http.StatusOK, e.ERROR, msg)
  3695. } else {
  3696. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3697. }
  3698. } else {
  3699. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3700. }
  3701. }
  3702. func CheckDates(c *gin.Context) {
  3703. tx := restful.Engine.NewSession()
  3704. defer tx.Close()
  3705. appG := app.Gin{C: c}
  3706. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3707. tempval_ := make(map[string]interface{})
  3708. tempCommon := make(map[string]interface{})
  3709. tempval := make([]map[string]interface{}, 0)
  3710. err := json.Unmarshal(dataByte, &tempval_)
  3711. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3712. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3713. if err != nil {
  3714. } else {
  3715. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3716. tempCommon = v
  3717. }
  3718. if v, ok := tempval_["data"].([]interface{}); ok {
  3719. for _, Tvalue := range v {
  3720. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3721. tempval = append(tempval, v1)
  3722. }
  3723. }
  3724. }
  3725. if err == nil {
  3726. if tempv, exists := c.Get("jwt_username"); exists {
  3727. tempCommon["jwt_username"] = tempv.(string)
  3728. }
  3729. for _, paramvalue := range tempval {
  3730. if _, ok := paramvalue["resultname"]; !ok {
  3731. paramvalue["resultname"] = paramvalue["name"]
  3732. }
  3733. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3734. if err != nil {
  3735. logging.Error("ExecDataParam error:", err)
  3736. }
  3737. }
  3738. if err == nil {
  3739. vmsg := ""
  3740. for _, item := range tempval {
  3741. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3742. for _, childrenList := range list.([]interface{}) {
  3743. for k, children := range childrenList.(map[string]interface{}) {
  3744. if k != "children" {
  3745. continue
  3746. }
  3747. for _, v := range children.([]map[string]interface{}) {
  3748. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3749. if k1 == "list" {
  3750. for _, v2 := range v1.([]map[string]interface{}) {
  3751. if v2["vmsg"].(string) != "1" {
  3752. if len(vmsg) == 0 {
  3753. vmsg = v2["vmsg"].(string)
  3754. } else {
  3755. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3756. }
  3757. }
  3758. }
  3759. }
  3760. }
  3761. }
  3762. }
  3763. }
  3764. }
  3765. }
  3766. if len(vmsg) > 0 {
  3767. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3768. } else {
  3769. appG.Response(http.StatusOK, e.SUCCESS, true)
  3770. }
  3771. } else {
  3772. msg := geterrmsg(err.Error())
  3773. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3774. }
  3775. }
  3776. }
  3777. if err != nil {
  3778. msg := geterrmsg(err.Error())
  3779. appG.Response(http.StatusOK, e.ERROR, msg)
  3780. }
  3781. }
  3782. 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) {
  3783. sqlname := fasion["name"].(string)
  3784. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3785. if v, ok := fasion["type"]; ok {
  3786. sqltype = v.(string)
  3787. }
  3788. sql := ""
  3789. p := ""
  3790. s_params := make([]interface{}, 0)
  3791. if sqltype != "" {
  3792. sql, p = restful.GetSqlByName(sqlname, tx)
  3793. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3794. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3795. paramslist := strings.Split(p, ",")
  3796. if len(paramslist) > 0 && p != "" {
  3797. for _, value := range paramslist {
  3798. ss := ""
  3799. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3800. ids, err := setting.SnowIds.NextId()
  3801. if err != nil {
  3802. ids = time.Now().UnixNano()
  3803. logging.Info("create SnowIds err", err)
  3804. }
  3805. s_params = append(s_params, ids)
  3806. } else {
  3807. if ss == "" && CommonParamMap != nil {
  3808. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3809. ss = valuestring
  3810. tempstrb := strings.IndexAny(valuestring, "@")
  3811. tempstre := strings.IndexAny(valuestring, ".")
  3812. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3813. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3814. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3815. }
  3816. } else {
  3817. ss = ""
  3818. }
  3819. }
  3820. }
  3821. if ss == "" && ParentParamMap != nil {
  3822. ss = getParamValue_(v, value, ParentParamMap)
  3823. }
  3824. if ss == "" && sameParamMap != nil {
  3825. ss = getParamValue(v, value, sameParamMap)
  3826. }
  3827. if ss == "" && ParamMap != nil {
  3828. ss = getParamValue(v, value, ParamMap)
  3829. }
  3830. s_params = append(s_params, ss)
  3831. }
  3832. }
  3833. }
  3834. }
  3835. }
  3836. if sql == "" {
  3837. sqltype = ""
  3838. }
  3839. if sql != "" {
  3840. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3841. if err != nil {
  3842. return nil, err
  3843. }
  3844. // fmt.Println(tempValParam)
  3845. return tempValParam.(map[string]interface{}), nil
  3846. } else {
  3847. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3848. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3849. if err != nil {
  3850. return nil, err
  3851. }
  3852. return nil, err
  3853. }
  3854. }
  3855. return nil, nil
  3856. }
  3857. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3858. var err error
  3859. subarray, ok := fasion["children"]
  3860. if ok {
  3861. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3862. tempVal_arrary := make([]map[string]interface{}, 0)
  3863. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3864. tempVal_ := make(map[string]interface{})
  3865. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3866. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3867. } else {
  3868. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3869. }
  3870. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3871. if err != nil {
  3872. return err
  3873. }
  3874. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3875. }
  3876. v.(map[string]interface{})["children"] = tempVal_arrary
  3877. }
  3878. }
  3879. return nil
  3880. }
  3881. func FpdImportExcel(c *gin.Context) {
  3882. appG := app.Gin{C: c}
  3883. inputdata := ""
  3884. c.Request.ParseForm()
  3885. params := c.Request.Form
  3886. file, _, err := c.Request.FormFile("file")
  3887. if err != nil {
  3888. appG.Response(http.StatusOK, e.ERROR, err)
  3889. return
  3890. }
  3891. sqlnamestrs := params.Get("name")
  3892. sheetname := params.Get("sheetname")
  3893. pastureid := params.Get("pastureid")
  3894. // importParams := params.Get("importParams")
  3895. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3896. // 必输项参数 (字符串格式 "field1,field2,field3")
  3897. requiredParams := params.Get("requiredParams")
  3898. // 日期参数
  3899. dateParams := params.Get("dateParams")
  3900. // 数字参数
  3901. numParams := params.Get("numParams")
  3902. //将字符串分割开
  3903. dateParamslist := strings.Split(dateParams, ",")
  3904. requiredParamslist := strings.Split(requiredParams, ",")
  3905. numParamslist := strings.Split(numParams, ",")
  3906. queryData := make([]interface{}, 0)
  3907. sqlslist := strings.Split(sqlnamestrs, ",")
  3908. xlsx1, err := excelize.OpenReader(file)
  3909. if err != nil {
  3910. fmt.Println(err)
  3911. return
  3912. }
  3913. ok := 0
  3914. error := 0
  3915. isdone := true
  3916. tx := restful.Engine.NewSession()
  3917. defer tx.Close()
  3918. languageStatus := GetLanguageStatus()
  3919. if languageStatus == "0" {
  3920. 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
  3921. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3922. if err != nil {
  3923. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3924. return
  3925. }
  3926. rows := xlsx1.GetRows(sheetname)
  3927. // 限制10000条,多余的截取掉
  3928. if len(rows) > 10000 {
  3929. rows = rows[:10000]
  3930. }
  3931. dataList := make(map[string][]*upFpdetail, 0)
  3932. for i, row := range rows {
  3933. if i > 0 {
  3934. entry := make(map[string]interface{})
  3935. outentry := make(map[string]interface{})
  3936. for j, colCell := range rows[0] {
  3937. for k, colCell1 := range row {
  3938. if j == k {
  3939. outentry[colCell] = colCell1
  3940. entry[colCell] = colCell1
  3941. }
  3942. }
  3943. }
  3944. inputdata = ""
  3945. a := ""
  3946. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3947. //校验日期格式
  3948. for _, v := range dateParamslist {
  3949. if v == "" {
  3950. continue
  3951. }
  3952. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3953. dtime, err := TransfTime(d.(string))
  3954. if err != nil {
  3955. a = strings.Trim(v, " ")
  3956. break
  3957. }
  3958. outentry[strings.Trim(v, " ")] = dtime
  3959. }
  3960. }
  3961. if a != "" {
  3962. outentry["error_msg"] = a + " 格式错误"
  3963. error++
  3964. queryData = append(queryData, outentry)
  3965. continue
  3966. }
  3967. a = ""
  3968. //校验必填格式
  3969. for _, v := range requiredParamslist {
  3970. if v == "" {
  3971. continue
  3972. }
  3973. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3974. a = strings.Trim(v, " ")
  3975. break
  3976. }
  3977. }
  3978. if a != "" {
  3979. outentry["error_msg"] = a + " 未填或格式错误"
  3980. error++
  3981. queryData = append(queryData, outentry)
  3982. continue
  3983. }
  3984. a = ""
  3985. //校验数字格式
  3986. for _, v := range numParamslist {
  3987. if v == "" {
  3988. continue
  3989. }
  3990. d, ok := outentry[strings.Trim(v, " ")]
  3991. if !ok || d == "" {
  3992. outentry[strings.Trim(v, " ")] = 0
  3993. } else {
  3994. var fl float64
  3995. switch d.(type) {
  3996. case string:
  3997. fl, err = strconv.ParseFloat(d.(string), 64)
  3998. }
  3999. if err != nil || fl < 0 {
  4000. a = strings.Trim(v, " ")
  4001. break
  4002. }
  4003. }
  4004. }
  4005. if a != "" {
  4006. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  4007. error++
  4008. queryData = append(queryData, outentry)
  4009. continue
  4010. }
  4011. errExist := false
  4012. for _, sqlnamestr := range sqlslist {
  4013. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4014. paramslist := strings.Split(paramslists, ",")
  4015. if len(paramslist) > 0 {
  4016. s_params := make([]interface{}, 0)
  4017. for _, value := range paramslist {
  4018. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4019. if tempv, exists := c.Get("jwt_username"); exists {
  4020. s_params = append(s_params, tempv.(string))
  4021. } else {
  4022. s_params = append(s_params, "")
  4023. }
  4024. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4025. s_params = append(s_params, pastureid)
  4026. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4027. ids, err := setting.SnowIds.NextId()
  4028. if err != nil {
  4029. ids = time.Now().UnixNano()
  4030. logging.Info("create SnowIds err", err)
  4031. }
  4032. s_params = append(s_params, ids)
  4033. } else {
  4034. if outentry[strings.Trim(value, " ")] == nil {
  4035. s_params = append(s_params, "")
  4036. } else {
  4037. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4038. }
  4039. }
  4040. }
  4041. outentry["input"] = inputdata
  4042. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4043. if err != nil {
  4044. errExist = true
  4045. // if tx != nil {
  4046. // tx.Rollback()
  4047. // }
  4048. // if tx != nil {
  4049. // tx.Close()
  4050. // }
  4051. msg := geterrmsg(err.Error())
  4052. outentry["error_msg"] = msg
  4053. error++
  4054. queryData = append(queryData, outentry)
  4055. isdone = true
  4056. break
  4057. } else {
  4058. if len(returnmsgmap1) > 0 {
  4059. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4060. // if tx != nil {
  4061. // tx.Rollback()
  4062. // }
  4063. // if tx != nil {
  4064. // tx.Close()
  4065. // }
  4066. msg := geterrmsg(va.(string))
  4067. outentry["error_msg"] = msg
  4068. error++
  4069. queryData = append(queryData, outentry)
  4070. isdone = true
  4071. break
  4072. }
  4073. }
  4074. isdone = false
  4075. }
  4076. }
  4077. }
  4078. fmt.Println(outentry["栏舍名称"])
  4079. if !errExist {
  4080. dataexcel := make(map[string]interface{}, 0)
  4081. if _, ok := outentry["栏舍名称"]; ok {
  4082. dataexcel["barname"] = outentry["栏舍名称"]
  4083. }
  4084. if _, ok := outentry["实际牛头数"]; ok {
  4085. dataexcel["ccount"] = outentry["实际牛头数"]
  4086. }
  4087. if _, ok := outentry["系数(%)"]; ok {
  4088. dataexcel["ratio"] = outentry["系数(%)"]
  4089. }
  4090. if _, ok := outentry["配方模板"]; ok {
  4091. dataexcel["ftname"] = outentry["配方模板"]
  4092. }
  4093. if _, ok := outentry["补料配方"]; ok {
  4094. dataexcel["ptsfname"] = outentry["补料配方"]
  4095. }
  4096. if _, ok := outentry["第一班比例(%)"]; ok {
  4097. dataexcel["1"] = outentry["第一班比例(%)"]
  4098. if fmt.Sprintf("%v", dataexcel["1"]) == "" {
  4099. dataexcel["1"] = 0
  4100. }
  4101. } else {
  4102. dataexcel["1"] = 0
  4103. }
  4104. if _, ok := outentry["第二班比例(%)"]; ok {
  4105. dataexcel["2"] = outentry["第二班比例(%)"]
  4106. if fmt.Sprintf("%v", dataexcel["2"]) == "" {
  4107. dataexcel["2"] = 0
  4108. }
  4109. } else {
  4110. dataexcel["2"] = 0
  4111. }
  4112. if _, ok := outentry["第三班比例(%)"]; ok {
  4113. dataexcel["3"] = outentry["第三班比例(%)"]
  4114. if fmt.Sprintf("%v", dataexcel["3"]) == "" {
  4115. dataexcel["3"] = 0
  4116. }
  4117. } else {
  4118. dataexcel["3"] = 0
  4119. }
  4120. if _, ok := outentry["第四班比例(%)"]; ok {
  4121. dataexcel["4"] = outentry["第四班比例(%)"]
  4122. if fmt.Sprintf("%v", dataexcel["4"]) == "" {
  4123. dataexcel["4"] = 0
  4124. }
  4125. } else {
  4126. dataexcel["4"] = 0
  4127. }
  4128. if _, ok := outentry["第五班比例(%)"]; ok {
  4129. dataexcel["5"] = outentry["第五班比例(%)"]
  4130. if fmt.Sprintf("%v", dataexcel["5"]) == "" {
  4131. dataexcel["5"] = 0
  4132. }
  4133. } else {
  4134. dataexcel["5"] = 0
  4135. }
  4136. if _, ok := outentry["第六班比例(%)"]; ok {
  4137. dataexcel["6"] = outentry["第六班比例(%)"]
  4138. if fmt.Sprintf("%v", dataexcel["6"]) == "" {
  4139. dataexcel["6"] = 0
  4140. }
  4141. } else {
  4142. dataexcel["6"] = 0
  4143. }
  4144. dataWeight := new(models.FpdetailEdit)
  4145. // dataWeightMap := make(map[string]interface{}, 0)
  4146. if _, ok := outentry["第一班重量"]; ok {
  4147. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4148. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4149. }
  4150. if _, ok := outentry["第二班重量"]; ok {
  4151. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4152. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4153. }
  4154. if _, ok := outentry["第三班重量"]; ok {
  4155. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4156. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4157. }
  4158. if _, ok := outentry["第四班重量"]; ok {
  4159. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4160. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4161. }
  4162. if _, ok := outentry["第五班重量"]; ok {
  4163. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4164. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4165. }
  4166. if _, ok := outentry["第六班重量"]; ok {
  4167. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4168. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4169. }
  4170. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4171. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4172. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4173. // fmt.Println(err)
  4174. if fmt.Sprintf("%v", dataexcel["ccount"]) == "0" {
  4175. dataWeight.Weight1 = 0
  4176. dataWeight.Weight2 = 0
  4177. dataWeight.Weight3 = 0
  4178. dataWeight.Weight4 = 0
  4179. dataWeight.Weight5 = 0
  4180. dataWeight.Weight6 = 0
  4181. }
  4182. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4183. if weight > 0 {
  4184. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4185. if err != nil {
  4186. logs.Error(err)
  4187. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4188. return
  4189. }
  4190. if !existbar {
  4191. continue
  4192. }
  4193. _, 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()
  4194. if err != nil {
  4195. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4196. return
  4197. }
  4198. _, 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()
  4199. if err != nil {
  4200. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4201. return
  4202. }
  4203. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4204. if err != nil {
  4205. logs.Error(err)
  4206. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4207. return
  4208. }
  4209. if !existft {
  4210. continue
  4211. }
  4212. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4213. if err != nil {
  4214. logs.Error(err)
  4215. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4216. return
  4217. }
  4218. if !ftexist {
  4219. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4220. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4221. if err != nil {
  4222. logs.Error(err)
  4223. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4224. return
  4225. }
  4226. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4227. if err != nil {
  4228. logs.Error(err)
  4229. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4230. return
  4231. }
  4232. }
  4233. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4234. if err != nil {
  4235. logs.Error(err)
  4236. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4237. return
  4238. }
  4239. if !exist {
  4240. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4241. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4242. if err != nil {
  4243. logs.Error(err)
  4244. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4245. return
  4246. }
  4247. }
  4248. var feedpargs []interface{}
  4249. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4250. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4251. if _, ok := dataexcel["ftname"]; ok {
  4252. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4253. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4254. // upFeedpSql += `,ftweight = ? `
  4255. // feedpargs = append(feedpargs, weight)
  4256. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4257. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4258. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4259. } else {
  4260. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4261. }
  4262. if _, ok := dataexcel["ptsfname"]; ok {
  4263. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4264. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4265. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4266. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4267. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4268. } else {
  4269. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4270. }
  4271. upFeedpSql += " where barname = ? and pastureid = ? "
  4272. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4273. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4274. if err != nil {
  4275. logs.Error(err)
  4276. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4277. return
  4278. }
  4279. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4280. if err != nil {
  4281. logs.Error(err)
  4282. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4283. return
  4284. }
  4285. if !exist1 {
  4286. _, 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) `,
  4287. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4288. if err != nil {
  4289. logs.Error(err)
  4290. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4291. return
  4292. }
  4293. }
  4294. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4295. if err != nil {
  4296. logs.Error(err)
  4297. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4298. return
  4299. }
  4300. if !exist2 {
  4301. _, 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) `,
  4302. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4303. if err != nil {
  4304. logs.Error(err)
  4305. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4306. return
  4307. }
  4308. }
  4309. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4310. if err != nil {
  4311. logs.Error(err)
  4312. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4313. return
  4314. }
  4315. if !exist3 {
  4316. _, 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) `,
  4317. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4318. if err != nil {
  4319. logs.Error(err)
  4320. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4321. return
  4322. }
  4323. }
  4324. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4325. if err != nil {
  4326. logs.Error(err)
  4327. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4328. return
  4329. }
  4330. if !exist4 {
  4331. _, 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) `,
  4332. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4333. if err != nil {
  4334. logs.Error(err)
  4335. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4336. return
  4337. }
  4338. }
  4339. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4340. if err != nil {
  4341. logs.Error(err)
  4342. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4343. return
  4344. }
  4345. if !exist5 {
  4346. _, 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) `,
  4347. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4348. if err != nil {
  4349. logs.Error(err)
  4350. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4351. return
  4352. }
  4353. }
  4354. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4355. if err != nil {
  4356. logs.Error(err)
  4357. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4358. return
  4359. }
  4360. if !exist6 {
  4361. _, 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) `,
  4362. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4363. if err != nil {
  4364. logs.Error(err)
  4365. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4366. return
  4367. }
  4368. }
  4369. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4370. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4371. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4372. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4373. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4374. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4375. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4376. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4377. and pastureid = ? and times = ?`
  4378. var fpdargs1 []interface{}
  4379. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4380. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4381. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4382. if err != nil {
  4383. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4384. return
  4385. }
  4386. var fpdargs2 []interface{}
  4387. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4388. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4389. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4390. if err != nil {
  4391. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4392. return
  4393. }
  4394. var fpdargs3 []interface{}
  4395. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4396. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4397. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4398. if err != nil {
  4399. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4400. return
  4401. }
  4402. var fpdargs4 []interface{}
  4403. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4404. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4405. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4406. if err != nil {
  4407. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4408. return
  4409. }
  4410. var fpdargs5 []interface{}
  4411. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4412. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4413. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4414. if err != nil {
  4415. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4416. return
  4417. }
  4418. var fpdargs6 []interface{}
  4419. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4420. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4421. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4422. if err != nil {
  4423. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4424. return
  4425. }
  4426. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4427. 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()
  4428. if err != nil {
  4429. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4430. return
  4431. }
  4432. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4433. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4434. upFpdetailList := make([]*upFpdetail, 0)
  4435. for _, newfpd := range newList {
  4436. for _, oldfpd := range oldFpdList {
  4437. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4438. var oldweight, newweight float64
  4439. if oldfpd["weight"] != nil {
  4440. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4441. }
  4442. if newfpd["weight"] != nil {
  4443. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4444. }
  4445. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4446. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4447. Old: oldweight,
  4448. New: newweight,
  4449. Times: newfpd["times"].(int64),
  4450. Ptid: newfpd["ptid"].(int64),
  4451. Fweight: fweight,
  4452. Id: oldfpd["id"].(int64),
  4453. })
  4454. break
  4455. }
  4456. }
  4457. }
  4458. // fmt.Println(dataexcel["barname"])
  4459. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4460. } else {
  4461. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4462. if err != nil {
  4463. logs.Error(err)
  4464. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4465. return
  4466. }
  4467. if !existbar {
  4468. continue
  4469. }
  4470. _, 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()
  4471. if err != nil {
  4472. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4473. return
  4474. }
  4475. _, 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()
  4476. if err != nil {
  4477. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4478. return
  4479. }
  4480. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4481. if err != nil {
  4482. logs.Error(err)
  4483. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4484. return
  4485. }
  4486. if !existft {
  4487. continue
  4488. }
  4489. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4490. if err != nil {
  4491. logs.Error(err)
  4492. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4493. return
  4494. }
  4495. if !ftexist {
  4496. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4497. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4498. if err != nil {
  4499. logs.Error(err)
  4500. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4501. return
  4502. }
  4503. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4504. if err != nil {
  4505. logs.Error(err)
  4506. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4507. return
  4508. }
  4509. }
  4510. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4511. if err != nil {
  4512. logs.Error(err)
  4513. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4514. return
  4515. }
  4516. if !exist {
  4517. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4518. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4519. if err != nil {
  4520. logs.Error(err)
  4521. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4522. return
  4523. }
  4524. }
  4525. var feedpargs []interface{}
  4526. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4527. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4528. if _, ok := dataexcel["ftname"]; ok {
  4529. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4530. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4531. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4532. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4533. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4534. } else {
  4535. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4536. }
  4537. if _, ok := dataexcel["ptsfname"]; ok {
  4538. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4539. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4540. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4541. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4542. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4543. } else {
  4544. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4545. }
  4546. upFeedpSql += " where barname = ? and pastureid = ? "
  4547. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4548. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4549. if err != nil {
  4550. logs.Error(err)
  4551. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4552. return
  4553. }
  4554. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4555. if err != nil {
  4556. logs.Error(err)
  4557. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4558. return
  4559. }
  4560. if !exist1 {
  4561. _, 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) `,
  4562. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4563. if err != nil {
  4564. logs.Error(err)
  4565. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4566. return
  4567. }
  4568. }
  4569. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4570. if err != nil {
  4571. logs.Error(err)
  4572. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4573. return
  4574. }
  4575. if !exist2 {
  4576. _, 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) `,
  4577. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4578. if err != nil {
  4579. logs.Error(err)
  4580. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4581. return
  4582. }
  4583. }
  4584. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4585. if err != nil {
  4586. logs.Error(err)
  4587. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4588. return
  4589. }
  4590. if !exist3 {
  4591. _, 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) `,
  4592. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4593. if err != nil {
  4594. logs.Error(err)
  4595. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4596. return
  4597. }
  4598. }
  4599. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4600. if err != nil {
  4601. logs.Error(err)
  4602. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4603. return
  4604. }
  4605. if !exist4 {
  4606. _, 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) `,
  4607. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4608. if err != nil {
  4609. logs.Error(err)
  4610. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4611. return
  4612. }
  4613. }
  4614. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4615. if err != nil {
  4616. logs.Error(err)
  4617. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4618. return
  4619. }
  4620. if !exist5 {
  4621. _, 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) `,
  4622. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4623. if err != nil {
  4624. logs.Error(err)
  4625. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4626. return
  4627. }
  4628. }
  4629. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4630. if err != nil {
  4631. logs.Error(err)
  4632. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4633. return
  4634. }
  4635. if !exist6 {
  4636. _, 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) `,
  4637. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4638. if err != nil {
  4639. logs.Error(err)
  4640. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4641. return
  4642. }
  4643. }
  4644. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4645. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4646. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4647. and pastureid = ? and times = ?`
  4648. var fpdargs1 []interface{}
  4649. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4650. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4651. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4652. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4653. if err != nil {
  4654. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4655. return
  4656. }
  4657. var fpdargs2 []interface{}
  4658. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4659. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4660. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4661. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4662. if err != nil {
  4663. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4664. return
  4665. }
  4666. var fpdargs3 []interface{}
  4667. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4668. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4669. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4670. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4671. if err != nil {
  4672. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4673. return
  4674. }
  4675. var fpdargs4 []interface{}
  4676. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4677. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4678. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4679. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4680. if err != nil {
  4681. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4682. return
  4683. }
  4684. var fpdargs5 []interface{}
  4685. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4686. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4687. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4688. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4689. if err != nil {
  4690. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4691. return
  4692. }
  4693. var fpdargs6 []interface{}
  4694. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4695. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4696. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4697. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4698. if err != nil {
  4699. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4700. return
  4701. }
  4702. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4703. 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()
  4704. if err != nil {
  4705. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4706. return
  4707. }
  4708. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4709. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4710. upFpdetailList := make([]*upFpdetail, 0)
  4711. for _, newfpd := range newList {
  4712. for _, oldfpd := range oldFpdList {
  4713. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4714. var oldweight, newweight float64
  4715. if oldfpd["weight"] != nil {
  4716. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4717. }
  4718. if newfpd["weight"] != nil {
  4719. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4720. }
  4721. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4722. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4723. Old: oldweight,
  4724. New: newweight,
  4725. Times: newfpd["times"].(int64),
  4726. Ptid: newfpd["ptid"].(int64),
  4727. Fweight: fweight,
  4728. Id: oldfpd["id"].(int64),
  4729. })
  4730. break
  4731. }
  4732. }
  4733. }
  4734. // fmt.Println(dataexcel["barname"])
  4735. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4736. }
  4737. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4738. }
  4739. }
  4740. if !isdone {
  4741. ok++
  4742. isdone = true
  4743. }
  4744. }
  4745. for barname, v := range dataList {
  4746. // for _, v1 := range v {
  4747. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4748. // and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4749. // if count == 1 {
  4750. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4751. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4752. // if err != nil {
  4753. // logs.Error(err)
  4754. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4755. // return
  4756. // }
  4757. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4758. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4759. // if err != nil {
  4760. // logs.Error(err)
  4761. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4762. // return
  4763. // }
  4764. // }
  4765. // }
  4766. updateFpdetailByBar(pastureid, barname, v)
  4767. }
  4768. } else {
  4769. 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
  4770. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4771. if err != nil {
  4772. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4773. return
  4774. }
  4775. rows := xlsx1.GetRows(sheetname)
  4776. // 限制10000条,多余的截取掉
  4777. if len(rows) > 10000 {
  4778. rows = rows[:10000]
  4779. }
  4780. dataList := make(map[string][]*upFpdetail, 0)
  4781. for i, row := range rows {
  4782. if i > 0 {
  4783. entry := make(map[string]interface{})
  4784. outentry := make(map[string]interface{})
  4785. for j, colCell := range rows[0] {
  4786. for k, colCell1 := range row {
  4787. if j == k {
  4788. outentry[colCell] = colCell1
  4789. entry[colCell] = colCell1
  4790. }
  4791. }
  4792. }
  4793. inputdata = ""
  4794. a := ""
  4795. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4796. //校验日期格式
  4797. for _, v := range dateParamslist {
  4798. if v == "" {
  4799. continue
  4800. }
  4801. if d, ok := outentry[v]; ok {
  4802. dtime, err := TransfTime(d.(string))
  4803. if err != nil {
  4804. a = v
  4805. break
  4806. }
  4807. outentry[v] = dtime
  4808. }
  4809. }
  4810. if a != "" {
  4811. outentry["error_msg"] = a + " format error"
  4812. error++
  4813. queryData = append(queryData, outentry)
  4814. continue
  4815. }
  4816. a = ""
  4817. //校验必填格式
  4818. for _, v := range requiredParamslist {
  4819. if v == "" {
  4820. continue
  4821. }
  4822. if d, ok := outentry[v]; !ok || d == "" {
  4823. a = v
  4824. break
  4825. }
  4826. }
  4827. if a != "" {
  4828. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4829. error++
  4830. queryData = append(queryData, outentry)
  4831. continue
  4832. }
  4833. a = ""
  4834. //校验数字格式
  4835. for _, v := range numParamslist {
  4836. if v == "" {
  4837. continue
  4838. }
  4839. d, ok := outentry[v]
  4840. if !ok || d == "" {
  4841. outentry[v] = 0
  4842. } else {
  4843. var fl float64
  4844. switch d.(type) {
  4845. case string:
  4846. fl, err = strconv.ParseFloat(d.(string), 64)
  4847. }
  4848. if err != nil || fl < 0 {
  4849. a = v
  4850. break
  4851. }
  4852. }
  4853. }
  4854. if a != "" {
  4855. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4856. error++
  4857. queryData = append(queryData, outentry)
  4858. continue
  4859. }
  4860. errExist := false
  4861. for _, sqlnamestr := range sqlslist {
  4862. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4863. paramslist := strings.Split(paramslists, ",")
  4864. if len(paramslist) > 0 {
  4865. s_params := make([]interface{}, 0)
  4866. for _, value := range paramslist {
  4867. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4868. if tempv, exists := c.Get("jwt_username"); exists {
  4869. s_params = append(s_params, tempv.(string))
  4870. } else {
  4871. s_params = append(s_params, "")
  4872. }
  4873. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4874. s_params = append(s_params, pastureid)
  4875. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4876. ids, err := setting.SnowIds.NextId()
  4877. if err != nil {
  4878. ids = time.Now().UnixNano()
  4879. logging.Info("create SnowIds err", err)
  4880. }
  4881. s_params = append(s_params, ids)
  4882. } else {
  4883. if outentry[strings.Trim(value, " ")] == nil {
  4884. s_params = append(s_params, "")
  4885. } else {
  4886. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4887. }
  4888. }
  4889. }
  4890. outentry["input"] = inputdata
  4891. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4892. if err != nil {
  4893. errExist = true
  4894. // if tx != nil {
  4895. // tx.Rollback()
  4896. // }
  4897. // if tx != nil {
  4898. // tx.Close()
  4899. // }
  4900. msg := geterrmsg(err.Error())
  4901. outentry["error_msg"] = msg
  4902. error++
  4903. queryData = append(queryData, outentry)
  4904. isdone = true
  4905. break
  4906. } else {
  4907. if len(returnmsgmap1) > 0 {
  4908. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4909. // if tx != nil {
  4910. // tx.Rollback()
  4911. // }
  4912. // if tx != nil {
  4913. // tx.Close()
  4914. // }
  4915. msg := geterrmsg(va.(string))
  4916. outentry["error_msg"] = msg
  4917. error++
  4918. queryData = append(queryData, outentry)
  4919. isdone = true
  4920. break
  4921. }
  4922. }
  4923. isdone = false
  4924. }
  4925. }
  4926. }
  4927. if !errExist {
  4928. dataexcel := make(map[string]interface{}, 0)
  4929. if _, ok := outentry["Pen Name"]; ok {
  4930. dataexcel["barname"] = outentry["Pen Name"]
  4931. }
  4932. if _, ok := outentry["Actual Cattle Number"]; ok {
  4933. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4934. }
  4935. if _, ok := outentry["Coefficient(%)"]; ok {
  4936. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4937. }
  4938. if _, ok := outentry["Formula Template"]; ok {
  4939. dataexcel["ftname"] = outentry["Formula Template"]
  4940. }
  4941. if _, ok := outentry["Supplement Formula"]; ok {
  4942. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4943. }
  4944. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4945. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4946. }
  4947. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4948. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4949. }
  4950. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4951. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4952. }
  4953. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4954. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4955. }
  4956. if _, ok := outentry["Fifth Shift Ratio(%)"]; ok {
  4957. dataexcel["5"] = outentry["Fifth Shift Ratio(%)"]
  4958. }
  4959. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4960. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4961. }
  4962. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4963. if err != nil {
  4964. logs.Error(err)
  4965. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4966. return
  4967. }
  4968. if !existbar {
  4969. continue
  4970. }
  4971. _, 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()
  4972. if err != nil {
  4973. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4974. return
  4975. }
  4976. _, 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()
  4977. if err != nil {
  4978. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4979. return
  4980. }
  4981. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4982. if err != nil {
  4983. logs.Error(err)
  4984. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  4985. return
  4986. }
  4987. if !existft {
  4988. continue
  4989. }
  4990. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4991. if err != nil {
  4992. logs.Error(err)
  4993. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4994. return
  4995. }
  4996. if !ftexist {
  4997. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4998. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4999. if err != nil {
  5000. logs.Error(err)
  5001. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5002. return
  5003. }
  5004. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5005. if err != nil {
  5006. logs.Error(err)
  5007. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5008. return
  5009. }
  5010. }
  5011. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5012. if err != nil {
  5013. logs.Error(err)
  5014. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5015. return
  5016. }
  5017. if !exist {
  5018. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  5019. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  5020. if err != nil {
  5021. logs.Error(err)
  5022. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5023. return
  5024. }
  5025. }
  5026. var feedpargs []interface{}
  5027. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  5028. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  5029. if _, ok := dataexcel["ftname"]; ok {
  5030. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  5031. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  5032. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  5033. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  5034. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5035. } else {
  5036. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  5037. }
  5038. if _, ok := dataexcel["ptsfname"]; ok {
  5039. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  5040. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  5041. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  5042. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  5043. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5044. } else {
  5045. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  5046. }
  5047. upFeedpSql += " where barname = ? and pastureid = ? "
  5048. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  5049. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  5050. if err != nil {
  5051. logs.Error(err)
  5052. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5053. return
  5054. }
  5055. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  5056. if err != nil {
  5057. logs.Error(err)
  5058. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5059. return
  5060. }
  5061. if !exist1 {
  5062. _, 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) `,
  5063. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5064. if err != nil {
  5065. logs.Error(err)
  5066. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5067. return
  5068. }
  5069. }
  5070. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5071. if err != nil {
  5072. logs.Error(err)
  5073. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5074. return
  5075. }
  5076. if !exist2 {
  5077. _, 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) `,
  5078. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5079. if err != nil {
  5080. logs.Error(err)
  5081. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5082. return
  5083. }
  5084. }
  5085. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5086. if err != nil {
  5087. logs.Error(err)
  5088. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5089. return
  5090. }
  5091. if !exist3 {
  5092. _, 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) `,
  5093. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5094. if err != nil {
  5095. logs.Error(err)
  5096. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5097. return
  5098. }
  5099. }
  5100. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5101. if err != nil {
  5102. logs.Error(err)
  5103. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5104. return
  5105. }
  5106. if !exist4 {
  5107. _, 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) `,
  5108. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5109. if err != nil {
  5110. logs.Error(err)
  5111. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5112. return
  5113. }
  5114. }
  5115. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5116. if err != nil {
  5117. logs.Error(err)
  5118. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5119. return
  5120. }
  5121. if !exist5 {
  5122. _, 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) `,
  5123. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5124. if err != nil {
  5125. logs.Error(err)
  5126. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5127. return
  5128. }
  5129. }
  5130. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5131. if err != nil {
  5132. logs.Error(err)
  5133. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5134. return
  5135. }
  5136. if !exist6 {
  5137. _, 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) `,
  5138. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5139. if err != nil {
  5140. logs.Error(err)
  5141. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5142. return
  5143. }
  5144. }
  5145. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5146. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5147. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5148. and pastureid = ? and times = ?`
  5149. var fpdargs1 []interface{}
  5150. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5151. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5152. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5153. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5154. if err != nil {
  5155. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5156. return
  5157. }
  5158. var fpdargs2 []interface{}
  5159. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5160. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5161. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5162. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5163. if err != nil {
  5164. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5165. return
  5166. }
  5167. var fpdargs3 []interface{}
  5168. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5169. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5170. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5171. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5172. if err != nil {
  5173. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5174. return
  5175. }
  5176. var fpdargs4 []interface{}
  5177. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5178. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5179. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5180. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5181. if err != nil {
  5182. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5183. return
  5184. }
  5185. var fpdargs5 []interface{}
  5186. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5187. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5188. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5189. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5190. if err != nil {
  5191. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5192. return
  5193. }
  5194. var fpdargs6 []interface{}
  5195. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5196. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5197. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5198. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5199. if err != nil {
  5200. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5201. return
  5202. }
  5203. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5204. 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()
  5205. if err != nil {
  5206. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5207. return
  5208. }
  5209. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5210. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5211. upFpdetailList := make([]*upFpdetail, 0)
  5212. for _, newfpd := range newList {
  5213. for _, oldfpd := range oldFpdList {
  5214. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5215. var oldweight, newweight float64
  5216. if oldfpd["weight"] != nil {
  5217. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5218. }
  5219. if newfpd["weight"] != nil {
  5220. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5221. }
  5222. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5223. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5224. Old: oldweight,
  5225. New: newweight,
  5226. Times: newfpd["times"].(int64),
  5227. Ptid: newfpd["ptid"].(int64),
  5228. Fweight: fweight,
  5229. Id: oldfpd["id"].(int64),
  5230. })
  5231. break
  5232. }
  5233. }
  5234. }
  5235. // fmt.Println(dataexcel["barname"])
  5236. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5237. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5238. }
  5239. }
  5240. if !isdone {
  5241. ok++
  5242. isdone = true
  5243. }
  5244. }
  5245. for barname, v := range dataList {
  5246. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5247. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5248. if err != nil {
  5249. logs.Error(err)
  5250. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5251. return
  5252. }
  5253. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5254. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5255. if err != nil {
  5256. logs.Error(err)
  5257. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5258. return
  5259. }
  5260. updateFpdetailByBar(pastureid, barname, v)
  5261. }
  5262. }
  5263. data := make(map[string]interface{})
  5264. data["result"] = queryData
  5265. data["success"] = ok
  5266. data["err_count"] = error
  5267. appG.Response(http.StatusOK, e.SUCCESS, data)
  5268. }
  5269. type upFpdetail struct {
  5270. Old float64
  5271. New float64
  5272. Times int64
  5273. Ptid int64
  5274. Fweight float64
  5275. Id int64
  5276. // Ptsid string
  5277. }
  5278. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5279. tx := restful.Engine.NewSession()
  5280. defer tx.Close()
  5281. tx.Begin()
  5282. 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 `,
  5283. pastureid, barname).Query().List()
  5284. if err != nil {
  5285. logs.Error(err)
  5286. }
  5287. for _, fpd := range fpdList {
  5288. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5289. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5290. pastureid, fpd["id"], fpd["times"]).Query().List()
  5291. if err != nil {
  5292. tx.Rollback()
  5293. logs.Error(err)
  5294. return err
  5295. }
  5296. var lweight float64
  5297. for _, lppland := range lpplandList {
  5298. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5299. lweight += lweight1
  5300. }
  5301. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5302. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5303. if fpdweight >= ptuse && lweight == ptuse {
  5304. continue
  5305. } else {
  5306. if lweight <= fpdweight {
  5307. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5308. if err != nil {
  5309. tx.Rollback()
  5310. logs.Error(err)
  5311. return err
  5312. }
  5313. } else {
  5314. weight := lweight - fpdweight
  5315. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5316. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5317. if err != nil {
  5318. tx.Rollback()
  5319. logs.Error(err)
  5320. return err
  5321. }
  5322. for _, lppland := range lpplandList {
  5323. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5324. if weight >= lpplandlweight {
  5325. weight = weight - lpplandlweight
  5326. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5327. if err != nil {
  5328. tx.Rollback()
  5329. logs.Error(err)
  5330. return err
  5331. }
  5332. } else {
  5333. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5334. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5335. if err != nil {
  5336. tx.Rollback()
  5337. logs.Error(err)
  5338. return err
  5339. }
  5340. weight = 0
  5341. break
  5342. }
  5343. }
  5344. }
  5345. }
  5346. }
  5347. for _, list := range dataList {
  5348. ftmap := make(map[string]interface{})
  5349. ftmap["old"] = list.Old
  5350. ftmap["new"] = list.New
  5351. ftmap["times"] = list.Times
  5352. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5353. ftmap["ptsid"] = ""
  5354. // fmt.Println(ftmap)
  5355. // 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 ,
  5356. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5357. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5358. // UNION
  5359. fpdDataList, err := tx.SQL(`
  5360. 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 ,
  5361. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5362. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5363. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5364. if err != nil {
  5365. tx.Rollback()
  5366. logs.Error(err)
  5367. }
  5368. for _, fpd := range fpdDataList {
  5369. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5370. // fttype := -1
  5371. // if fpd["fttype"].(string) == "1" {
  5372. fttype := 1
  5373. // }
  5374. var fweight float64
  5375. var lweight float64
  5376. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5377. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  5378. t.maxstirfeed,t.volume * (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  5379. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5380. join tmr t on t.id = lpp.tmrid
  5381. where lppland.fpdid =?
  5382. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5383. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5384. if err != nil {
  5385. tx.Rollback()
  5386. logs.Error(err)
  5387. }
  5388. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5389. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5390. // 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
  5391. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5392. var w float64
  5393. var status int
  5394. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5395. if weight >= 0 {
  5396. continue
  5397. }
  5398. w = weight
  5399. status = 0
  5400. } else {
  5401. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5402. // continue
  5403. // }
  5404. w = weight
  5405. status = 1
  5406. }
  5407. // for _, lppland := range lpplandtl1List {
  5408. // lweight += lppland.Lweight
  5409. // }
  5410. for _, lppland := range lpplandtl1List {
  5411. lpplandInfo := new(lpplandtlInfo)
  5412. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5413. lweight = lpplandInfo.Lweight
  5414. if status == 1 {
  5415. // if w <= lppland.Lweight {
  5416. if lppland.Maxweight <= lweight {
  5417. continue
  5418. }
  5419. if w+lweight <= lppland.Maxweight {
  5420. lppland.Lweight += w
  5421. lweight += w
  5422. fweight += w
  5423. w = 0
  5424. } else {
  5425. w = w - (lppland.Maxweight - lweight)
  5426. n := (lppland.Maxweight - lweight)
  5427. lppland.Lweight = lppland.Lweight + n
  5428. lweight += n
  5429. fweight += n
  5430. }
  5431. } else {
  5432. if lppland.Lweight == 0 {
  5433. continue
  5434. }
  5435. if w+lppland.Lweight >= 0 {
  5436. lppland.Lweight = lppland.Lweight + w
  5437. lweight = lweight + w
  5438. fweight = fweight + w
  5439. w = 0
  5440. } else {
  5441. w = w + lppland.Lweight
  5442. lweight = lweight - lppland.Lweight
  5443. fweight = fweight - lppland.Lweight
  5444. lppland.Lweight = 0
  5445. }
  5446. }
  5447. if lppland.Lweight > 0 {
  5448. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5449. if err != nil {
  5450. tx.Rollback()
  5451. logs.Error(err)
  5452. return err
  5453. }
  5454. } else {
  5455. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5456. if err != nil {
  5457. tx.Rollback()
  5458. logs.Error(err)
  5459. return err
  5460. }
  5461. }
  5462. if w == 0 {
  5463. break
  5464. }
  5465. }
  5466. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5467. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5468. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5469. if err != nil {
  5470. tx.Rollback()
  5471. logs.Error(err)
  5472. }
  5473. if w == 0 {
  5474. break
  5475. }
  5476. }
  5477. }
  5478. }
  5479. err = tx.Commit()
  5480. if err != nil {
  5481. logs.Error(err)
  5482. tx.Rollback()
  5483. return err
  5484. }
  5485. now := time.Now()
  5486. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5487. if err != nil {
  5488. logs.Error(err)
  5489. return nil
  5490. }
  5491. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5492. if err != nil {
  5493. logs.Error(err)
  5494. return nil
  5495. }
  5496. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5497. if err != nil {
  5498. logs.Error(err)
  5499. return nil
  5500. }
  5501. for _, newLpplandtl1 := range newLpplandtl1List {
  5502. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5503. background,cowcount,ccountradio,lweighthis,createdate)
  5504. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5505. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5506. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5507. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5508. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5509. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5510. if err != nil {
  5511. logs.Error(err)
  5512. // appG.Response(http.StatusOK, e.ERROR, false)
  5513. return err
  5514. }
  5515. }
  5516. for _, newFpd := range newFpdDataList {
  5517. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5518. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5519. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5520. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5521. if err != nil {
  5522. logs.Error(err)
  5523. // appG.Response(http.StatusOK, e.ERROR, false)
  5524. return err
  5525. }
  5526. }
  5527. for _, newFeedp := range newFeedpList {
  5528. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5529. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5530. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5531. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5532. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5533. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5534. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5535. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5536. if err != nil {
  5537. logs.Error(err)
  5538. // appG.Response(http.StatusOK, e.ERROR, false)
  5539. return err
  5540. }
  5541. }
  5542. return nil
  5543. }
  5544. func DeleteFTdetail(c *gin.Context) {
  5545. appG := app.Gin{C: c}
  5546. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5547. fsion := gofasion.NewFasion(string(dataByte))
  5548. parammaps := fsion.Get("parammaps")
  5549. pastureid := parammaps.Get("pastureid").ValueStr()
  5550. ftid := parammaps.Get("ftid").ValueStr()
  5551. tx := restful.Engine.NewSession()
  5552. defer tx.Close()
  5553. tx.Begin()
  5554. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5555. if err != nil {
  5556. tx.Rollback()
  5557. logs.Error(err)
  5558. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5559. return
  5560. }
  5561. if parammaps.Get("type").ValueStr() == "1" {
  5562. _, err := tx.SQL(`UPDATE feedp fp
  5563. set
  5564. fp.ftweight= IFNULL(IF(
  5565. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5566. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5567. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5568. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5569. ),0),fp.feedweight = IFNULL(IF(
  5570. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5571. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5572. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5573. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5574. ),0) +ifnull(fp.supplyweight,0)
  5575. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5576. if err != nil {
  5577. tx.Rollback()
  5578. logs.Error(err)
  5579. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5580. return
  5581. }
  5582. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5583. _, err = tx.SQL(`
  5584. UPDATE fpdetail fpd
  5585. INNER JOIN feedp fp
  5586. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5587. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5588. ptuse= 0
  5589. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5590. if err != nil {
  5591. tx.Rollback()
  5592. logs.Error(err)
  5593. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5594. return
  5595. }
  5596. } else {
  5597. _, err := tx.SQL(`UPDATE feedp fp
  5598. SET
  5599. fp.supplyweight= IFNULL(IF(
  5600. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5601. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5602. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5603. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5604. ),0),fp.feedweight = IFNULL(IF(
  5605. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5606. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5607. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5608. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5609. ),0) + ifnull(fp.supplyweight,0)
  5610. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5611. if err != nil {
  5612. tx.Rollback()
  5613. logs.Error(err)
  5614. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5615. return
  5616. }
  5617. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5618. _, err = tx.SQL(`
  5619. UPDATE fpdetail fpd
  5620. INNER JOIN feedp fp
  5621. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5622. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5623. ptsrate = 0
  5624. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5625. if err != nil {
  5626. tx.Rollback()
  5627. logs.Error(err)
  5628. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5629. return
  5630. }
  5631. }
  5632. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5633. if err != nil {
  5634. tx.Rollback()
  5635. logs.Error(err)
  5636. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5637. return
  5638. }
  5639. err = tx.Commit()
  5640. if err != nil {
  5641. tx.Rollback()
  5642. logs.Error(err)
  5643. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5644. return
  5645. }
  5646. appG.Response(http.StatusOK, e.SUCCESS, true)
  5647. }
  5648. func DeleteSpillageAll(c *gin.Context) {
  5649. appG := app.Gin{C: c}
  5650. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5651. fsion := gofasion.NewFasion(string(dataByte))
  5652. parammaps := fsion.Get("parammaps")
  5653. pastureid := parammaps.Get("pastureid").ValueStr()
  5654. times := parammaps.Get("times").ValueStr()
  5655. barid := parammaps.Get("barid").ValueStr()
  5656. tx := restful.Engine.NewSession()
  5657. defer tx.Close()
  5658. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5659. if err != nil {
  5660. logs.Error(err)
  5661. appG.Response(http.StatusOK, e.ERROR, false)
  5662. return
  5663. }
  5664. now := time.Now()
  5665. for _, item := range lpplandtl1List {
  5666. go func(item map[string]interface{}) {
  5667. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5668. background,cowcount,ccountradio,lweighthis,createdate)
  5669. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5670. item["pastureid"], item["lppid"], item["barid"],
  5671. item["barname"], item["fpdid"], item["fttype"],
  5672. item["lweight"], item["sort"], item["tmrid"],
  5673. item["tmrname"], item["background"], item["cowcount"],
  5674. item["ccountradio"], item["lweighthis"], now).Execute()
  5675. if err != nil {
  5676. logs.Error(err)
  5677. appG.Response(http.StatusOK, e.ERROR, false)
  5678. return
  5679. }
  5680. }(item)
  5681. }
  5682. tx.Begin()
  5683. _, 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()
  5684. if err != nil {
  5685. tx.Rollback()
  5686. logs.Error(err)
  5687. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5688. return
  5689. }
  5690. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5691. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5692. if err != nil {
  5693. tx.Rollback()
  5694. logs.Error(err)
  5695. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5696. return
  5697. }
  5698. err = tx.Commit()
  5699. if err != nil {
  5700. tx.Rollback()
  5701. logs.Error(err)
  5702. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5703. return
  5704. }
  5705. appG.Response(http.StatusOK, e.SUCCESS, true)
  5706. }
  5707. func GetTMRListEnableTypeAll(c *gin.Context) {
  5708. appG := app.Gin{C: c}
  5709. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5710. fsion := gofasion.NewFasion(string(dataByte))
  5711. parammaps := fsion.Get("parammaps")
  5712. pastureid := parammaps.Get("pastureid").ValueStr()
  5713. tx := restful.Engine.NewSession()
  5714. defer tx.Close()
  5715. dataList, err := tx.SQL(`SELECT
  5716. eqcode,
  5717. tname,
  5718. datacaptureno,
  5719. trim(tclassid) tclassid,
  5720. concat(tname,' / ',eqcode) tmrmix,
  5721. d.label tclassname,
  5722. maxstirfeed,
  5723. remark,
  5724. tmr.enable,
  5725. TRIM(tmr.id) id,
  5726. TRIM(tmr.pastureid)pastureid
  5727. FROM
  5728. tmr
  5729. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5730. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5731. ORDER BY id DESC`, pastureid).Query().List()
  5732. if err != nil {
  5733. logs.Error(err)
  5734. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5735. return
  5736. }
  5737. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5738. if err != nil {
  5739. logs.Error(err)
  5740. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5741. return
  5742. }
  5743. var carNum int64
  5744. for _, sysopt := range sysoptData {
  5745. if sysopt["inforvalue"] == nil {
  5746. carNum = 1
  5747. } else {
  5748. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5749. }
  5750. }
  5751. id := 200
  5752. n := 0
  5753. for i := carNum; i > 0; i-- {
  5754. id++
  5755. n++
  5756. data := make(map[string]interface{}, 0)
  5757. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5758. data["tname"] = fmt.Sprintf("任意车%d", n)
  5759. data["datacaptureno"] = -2
  5760. data["tclassid"] = -2
  5761. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5762. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5763. data["maxstirfeed"] = 100000
  5764. data["remark"] = fmt.Sprintf("任意车%d", n)
  5765. data["enable"] = 1
  5766. data["id"] = fmt.Sprintf("%d", id)
  5767. data["pastureid"] = pastureid
  5768. // data := make(map[string]interface{}, 0)
  5769. // data["eqcode"] = fmt.Sprintf("AnyCar%d", n)
  5770. // data["tname"] = fmt.Sprintf("AnyCar%d", n)
  5771. // data["datacaptureno"] = -2
  5772. // data["tclassid"] = -2
  5773. // data["tmrmix"] = fmt.Sprintf("AnyCar%d", n)
  5774. // data["tclassname"] = fmt.Sprintf("AnyCar%d", n)
  5775. // data["maxstirfeed"] = 100000
  5776. // data["remark"] = fmt.Sprintf("AnyCar%d", n)
  5777. // data["enable"] = 1
  5778. // data["id"] = fmt.Sprintf("%d", id)
  5779. // data["pastureid"] = pastureid
  5780. dataList = append(dataList, data)
  5781. }
  5782. // UNION ALL
  5783. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5784. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5785. }
  5786. func GetFeedpHistory(c *gin.Context) {
  5787. appG := app.Gin{C: c}
  5788. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5789. fsion := gofasion.NewFasion(string(dataByte))
  5790. // parammaps := fsion.Get("parammaps")
  5791. bar := fsion.Get("barname").ValueStr()
  5792. startDate := fsion.Get("startDate").ValueStr()
  5793. endDate := fsion.Get("endDate").ValueStr()
  5794. tx := restful.Engine.NewSession()
  5795. defer tx.Close()
  5796. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5797. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5798. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5799. if err != nil {
  5800. logs.Error(err)
  5801. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5802. return
  5803. }
  5804. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5805. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5806. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5807. if err != nil {
  5808. logs.Error(err)
  5809. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5810. return
  5811. }
  5812. for _, feedp := range feedpList {
  5813. // LastftList, err := tx.SQL(` select tname ,id
  5814. // from feedtemplethistory where id = ?
  5815. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5816. // if err != nil {
  5817. // logs.Error(err)
  5818. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5819. // return
  5820. // }
  5821. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5822. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5823. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5824. if err != nil {
  5825. logs.Error(err)
  5826. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5827. return
  5828. }
  5829. var ftname interface{}
  5830. ftnamestatus := 0
  5831. ftname = feedp["ftname"]
  5832. var lastftid int64
  5833. if len(nextfeedpList) > 0 {
  5834. for _, ft := range nextfeedpList {
  5835. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5836. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5837. lastftid = ft["ftid"].(int64)
  5838. ftnamestatus = 1
  5839. break
  5840. }
  5841. }
  5842. }
  5843. for i, fpd := range fpdList {
  5844. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5845. fpd["weightstatus"] = 0
  5846. fpd["tratiostatus"] = 0
  5847. fpd["ftnamestatus"] = ftnamestatus
  5848. for k, fpd2 := range fpdList {
  5849. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5850. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5851. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5852. fpd["weightstatus"] = 1
  5853. }
  5854. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5855. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5856. fpd["tratiostatus"] = 1
  5857. }
  5858. break
  5859. }
  5860. }
  5861. fpd["barid"] = feedp["barid"]
  5862. fpd["barname"] = feedp["barname"]
  5863. fpd["ccount"] = feedp["ccount"]
  5864. fpd["ratio"] = feedp["ratio"]
  5865. fpd["ccountratio"] = feedp["ccountratio"]
  5866. fpd["ftid"] = feedp["ftid"]
  5867. fpd["ftname"] = ftname
  5868. fpd["ccountstatus"] = 0
  5869. fpd["ccountratiostatus"] = 0
  5870. fpd["ratiostatus"] = 0
  5871. fpd["ftnamestatus"] = 0
  5872. fpd["lastftid"] = lastftid
  5873. for _, next := range nextfeedpList {
  5874. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5875. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5876. fpd["ccountstatus"] = 1
  5877. }
  5878. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5879. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5880. fpd["ccountratiostatus"] = 1
  5881. }
  5882. if next["ratio"].(string) != fpd["ratio"].(string) {
  5883. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5884. fpd["ratiostatus"] = 1
  5885. }
  5886. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5887. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5888. // fpd["ftnamestatus"] = 1
  5889. // }
  5890. }
  5891. }
  5892. }
  5893. }
  5894. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5895. }
  5896. // func GetLpplandtl1History(c *gin.Context) {
  5897. // appG := app.Gin{C: c}
  5898. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5899. // fsion := gofasion.NewFasion(string(dataByte))
  5900. // // parammaps := fsion.Get("parammaps")
  5901. // barid := fsion.Get("barid").ValueStr()
  5902. // startDate := fsion.Get("startDate").ValueStr()
  5903. // endDate := fsion.Get("endDate").ValueStr()
  5904. // tx := restful.Engine.NewSession()
  5905. // defer tx.Close()
  5906. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5907. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5908. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5909. // // if err != nil {
  5910. // // logs.Error(err)
  5911. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5912. // // return
  5913. // // }
  5914. // // for _, feedp := range feedpList {
  5915. // // fmt.Println(feedp)
  5916. // // for i, fpd := range fpdList {
  5917. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5918. // // for k, fpd2 := range fpdList {
  5919. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5920. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5921. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5922. // // }
  5923. // // break
  5924. // // }
  5925. // // }
  5926. // // fpd["barid"] = feedp["barid"]
  5927. // // fpd["barname"] = feedp["barname"]
  5928. // // fpd["ccount"] = feedp["ccount"]
  5929. // // fpd["ratio"] = feedp["ratio"]
  5930. // // fpd["ccountratio"] = feedp["ccountratio"]
  5931. // // fpd["ftid"] = feedp["ftid"]
  5932. // // fpd["ftname"] = feedp["ftname"]
  5933. // // }
  5934. // // }
  5935. // // }
  5936. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5937. // }
  5938. func GetRemind(c *gin.Context) {
  5939. appG := app.Gin{C: c}
  5940. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5941. fsion := gofasion.NewFasion(string(dataByte))
  5942. parammaps := fsion.Get("parammaps")
  5943. pastureid := parammaps.Get("pastureid").ValueStr()
  5944. tx := restful.Engine.NewSession()
  5945. defer tx.Close()
  5946. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5947. if err != nil {
  5948. logs.Error(err)
  5949. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5950. return
  5951. }
  5952. // pastureid = "3"
  5953. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5954. if err != nil {
  5955. logs.Error(err)
  5956. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5957. return
  5958. }
  5959. defer resp.Body.Close()
  5960. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5961. buf.ReadFrom(resp.Body)
  5962. fmt.Println(string(buf.Bytes()))
  5963. respMap := make(map[string]interface{}, 0)
  5964. err = json.Unmarshal(buf.Bytes(), &respMap)
  5965. if err != nil {
  5966. logs.Error(err)
  5967. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5968. return
  5969. }
  5970. for _, data := range dataList {
  5971. r := make(map[string]interface{}, 0)
  5972. r["sys_name"] = ""
  5973. r["service_id"] = ""
  5974. r["pasture_id"] = ""
  5975. r["type_name"] = ""
  5976. r["remind_type_id"] = ""
  5977. r["remind_type"] = ""
  5978. r["push_date"] = ""
  5979. r["push_time"] = ""
  5980. r["interval_time"] = ""
  5981. r["push_limit"] = ""
  5982. r["template_id"] = ""
  5983. r["roles_id"] = ""
  5984. r["users_id"] = ""
  5985. r["date_type"] = ""
  5986. r["cycle_type"] = ""
  5987. data["data"] = r
  5988. for _, resp := range respMap["data"].([]interface{}) {
  5989. resp1 := resp.(map[string]interface{})
  5990. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5991. if resp1["push_time"] == nil {
  5992. resp1["push_time"] = ""
  5993. }
  5994. data["data"] = resp1
  5995. break
  5996. }
  5997. }
  5998. }
  5999. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  6000. }
  6001. type NoticeMsgtype struct {
  6002. SysName string `json:"sys_name"`
  6003. PastureId int64 `json:"pasture_id"`
  6004. ServiceId int64 `json:"service_id"`
  6005. TypeName string `json:"type_name"`
  6006. RemindType int64 `json:"remind_type"`
  6007. PushDate int64 `json:"push_date"`
  6008. PushTime string `json:"push_time"`
  6009. IntervalTime int64 `json:"interval_time"`
  6010. PushLimit int64 `json:"push_limit"`
  6011. TemplateId string `json:"template_id"`
  6012. UsersId string `json:"users_id"`
  6013. DateType int64 `json:"date_type"`
  6014. CycleType int64 `json:"cycle_type"`
  6015. DelayTime int64 `json:"delay_time"`
  6016. Status int64 `json:"status"`
  6017. }
  6018. func UpdateRemind(c *gin.Context) {
  6019. appG := app.Gin{C: c}
  6020. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6021. parammaps := gofasion.NewFasion(string(dataByte))
  6022. // parammaps := fsion.Get("parammaps")
  6023. // user := parammaps.Get("user").ValueStr()
  6024. id := parammaps.Get("id").ValueInt64()
  6025. noticeMsgtype := new(NoticeMsgtype)
  6026. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  6027. noticeMsgtype.ServiceId = id
  6028. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  6029. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  6030. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  6031. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  6032. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  6033. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  6034. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  6035. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  6036. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  6037. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  6038. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  6039. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  6040. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  6041. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  6042. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  6043. //TODO
  6044. noticeMsgtype.SysName = "tmrWatch"
  6045. userList := parammaps.Get("user").Array()
  6046. var userstr []string
  6047. for _, user := range userList {
  6048. userstr = append(userstr, user.ValueStr())
  6049. }
  6050. tx := restful.Engine.NewSession()
  6051. defer tx.Close()
  6052. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  6053. if err != nil {
  6054. logs.Error(err)
  6055. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6056. return
  6057. }
  6058. // var jsonStr = []byte(noticeMsgtype
  6059. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  6060. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  6061. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  6062. req.Header.Set("Content-Type", "application/json")
  6063. client := &http.Client{}
  6064. resp, err := client.Do(req)
  6065. if err != nil {
  6066. logs.Error(err)
  6067. }
  6068. defer resp.Body.Close()
  6069. body, _ := ioutil.ReadAll(resp.Body)
  6070. fmt.Println("response Body:", string(body))
  6071. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  6072. if err != nil {
  6073. logs.Error(err)
  6074. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6075. return
  6076. }
  6077. defer getresp.Body.Close()
  6078. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6079. buf.ReadFrom(getresp.Body)
  6080. // fmt.Println(string(buf.Bytes()))
  6081. respMap := make(map[string]interface{}, 0)
  6082. err = json.Unmarshal(buf.Bytes(), &respMap)
  6083. if err != nil {
  6084. logs.Error(err)
  6085. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6086. return
  6087. }
  6088. for _, resp := range respMap["data"].([]interface{}) {
  6089. resp1 := resp.(map[string]interface{})
  6090. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6091. if err != nil {
  6092. logs.Error(err)
  6093. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6094. return
  6095. }
  6096. }
  6097. appG.Response(http.StatusOK, e.SUCCESS, true)
  6098. }
  6099. func GetSpillageallHistory(c *gin.Context) {
  6100. appG := app.Gin{C: c}
  6101. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6102. parammaps := gofasion.NewFasion(string(dataByte))
  6103. barname := parammaps.Get("barname").ValueStr()
  6104. pastureid := parammaps.Get("pastureid").ValueStr()
  6105. startdate := parammaps.Get("startDate").ValueStr()
  6106. enddate := parammaps.Get("endDate").ValueStr()
  6107. tx := restful.Engine.NewSession()
  6108. defer tx.Close()
  6109. 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
  6110. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6111. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6112. if err != nil {
  6113. logs.Error(err)
  6114. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6115. return
  6116. }
  6117. respMap := make([]map[string]interface{}, 0)
  6118. data := make(map[interface{}]interface{})
  6119. for _, history := range historyList {
  6120. data[history["createdate"]] = history["createdate"]
  6121. }
  6122. createList := []string{}
  6123. for _, v := range data {
  6124. createList = append(createList, v.(string))
  6125. }
  6126. // sort.Sort()
  6127. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6128. sort.Slice(createList, func(i, j int) bool {
  6129. return createList[i] > createList[j]
  6130. })
  6131. for _, v := range createList {
  6132. a := make(map[string]interface{})
  6133. a["createdate"] = data[v]
  6134. // createList = append(createList, v.(string))
  6135. respMap = append(respMap, a)
  6136. }
  6137. number := 0
  6138. dataMap := make([]interface{}, 0)
  6139. for k, resp := range respMap {
  6140. createdate := resp["createdate"].(string)
  6141. var nextcreatedate string
  6142. if len(respMap) > k+1 {
  6143. nextcreatedate = respMap[k+1]["createdate"].(string)
  6144. }
  6145. // dataList := make(map[string][]interface{})
  6146. // list := make(map[string]interface{})
  6147. times := make(map[interface{}]int)
  6148. for _, history := range historyList {
  6149. // List := make(map[interface{}][]interface{})
  6150. i := 0
  6151. if history["createdate"].(string) == createdate {
  6152. times[history["times"]]++
  6153. data := make(map[string]interface{})
  6154. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6155. // exist := false
  6156. if nextcreatedate != "" {
  6157. for _, history1 := range historyList {
  6158. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6159. history1["times"].(int64) == history["times"].(int64) {
  6160. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6161. break
  6162. // exist = true
  6163. }
  6164. }
  6165. }
  6166. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6167. i++
  6168. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6169. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6170. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6171. // resp["times"] = history["times"]
  6172. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6173. data1 := make(map[string]interface{})
  6174. data1["times"] = history["times"]
  6175. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6176. data1["createdate"] = resp["createdate"]
  6177. // fmt.Println(dataList)
  6178. dataMap = append(dataMap, data1)
  6179. }
  6180. if i > number {
  6181. number = i
  6182. }
  6183. // respMap = append(respMap, dataList)
  6184. }
  6185. // for k, data := range dataList {
  6186. // resp[k] = data
  6187. // }
  6188. // resp["data"] = dataList
  6189. }
  6190. // resp := make(map[string]interface{})
  6191. // sort.Strings(createList)
  6192. //
  6193. // for _, create := range createList {
  6194. // for _, r := range respMap {
  6195. // if create == r["createdate"].(string) {
  6196. // resp[create] = r
  6197. // break
  6198. // }
  6199. // }
  6200. // }
  6201. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6202. var trainsList []interface{}
  6203. for i := 0; i < number; i++ {
  6204. trains := make(map[string]interface{})
  6205. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6206. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6207. trainsList = append(trainsList, trains)
  6208. }
  6209. respdata := make(map[string]interface{})
  6210. respdata["data"] = dataMap
  6211. respdata["trains"] = trainsList
  6212. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6213. }
  6214. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6215. appG := app.Gin{C: c}
  6216. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6217. parammaps := gofasion.NewFasion(string(dataByte))
  6218. ftid := parammaps.Get("ftid").ValueInt64()
  6219. lastftid := parammaps.Get("lastftid").ValueInt64()
  6220. pastureid := parammaps.Get("pastureid").ValueInt64()
  6221. // createdate := parammaps.Get("createdate").ValueStr()
  6222. tx := restful.Engine.NewSession()
  6223. defer tx.Close()
  6224. data := make(map[string]interface{})
  6225. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6226. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6227. if err != nil {
  6228. logs.Error(err)
  6229. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6230. return
  6231. }
  6232. feedtemplet := make(map[string]interface{})
  6233. for _, f := range feedtempletList {
  6234. feedtemplet = f
  6235. }
  6236. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  6237. if err != nil {
  6238. logs.Error(err)
  6239. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6240. return
  6241. }
  6242. feedtemplet["fit"] = fitList
  6243. data["current"] = feedtemplet
  6244. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6245. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6246. if err != nil {
  6247. logs.Error(err)
  6248. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6249. return
  6250. }
  6251. lastfeedtemplet := make(map[string]interface{})
  6252. for _, f := range lastfeedtempletList {
  6253. lastfeedtemplet = f
  6254. }
  6255. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  6256. if err != nil {
  6257. logs.Error(err)
  6258. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6259. return
  6260. }
  6261. lastfeedtemplet["fit"] = lastfitList
  6262. data["last"] = lastfeedtemplet
  6263. appG.Response(http.StatusOK, e.SUCCESS, data)
  6264. }
  6265. func GetFeedtempletHistory(c *gin.Context) {
  6266. appG := app.Gin{C: c}
  6267. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6268. parammaps := gofasion.NewFasion(string(dataByte))
  6269. ftid := parammaps.Get("ftid").ValueStr()
  6270. pastureid := parammaps.Get("pastureid").ValueInt64()
  6271. start := parammaps.Get("startdate").ValueStr()
  6272. end := parammaps.Get("enddate").ValueStr()
  6273. tx := restful.Engine.NewSession()
  6274. defer tx.Close()
  6275. 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 ?
  6276. and id = ? and pastureid = ? order by createdate desc `,
  6277. start, end, ftid, pastureid).Query().List()
  6278. if err != nil {
  6279. logs.Error(err)
  6280. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6281. return
  6282. }
  6283. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6284. ftid, pastureid).Query().List()
  6285. if err != nil {
  6286. logs.Error(err)
  6287. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6288. return
  6289. }
  6290. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6291. for i, ft := range ftList {
  6292. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6293. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6294. (select empname from user where id = fit.userId) empname,
  6295. 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
  6296. where fit.fitid = ?
  6297. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6298. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6299. if err != nil {
  6300. logs.Error(err)
  6301. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6302. return
  6303. }
  6304. ft["createdate"] = ft["createdate1"]
  6305. // data["tname"] = ft["tname"]
  6306. // data["tcode"] = ft["tcode"]
  6307. // data["tcolor"] = ft["tcolor"]
  6308. // data["fttype"] = ft["fttype"]
  6309. // data["ccname"] = ft["ccname"]
  6310. // data["source"] = ft["source"]
  6311. // data["version"] = ft["version"]
  6312. // data["remark"] = ft["remark"]
  6313. for n, ft2 := range ftList {
  6314. if i < n {
  6315. if ft["tname"].(string) != ft2["tname"].(string) {
  6316. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6317. }
  6318. if _, ok := ft["tcode"]; ok {
  6319. if _, ok := ft2["tcode"]; ok {
  6320. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6321. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6322. }
  6323. }
  6324. }
  6325. if _, ok := ft["tcolor"]; ok {
  6326. if _, ok := ft2["tcolor"]; ok {
  6327. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6328. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6329. }
  6330. }
  6331. }
  6332. if _, ok := ft["fttype"]; ok {
  6333. if _, ok := ft2["fttype"]; ok {
  6334. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6335. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6336. }
  6337. }
  6338. }
  6339. if _, ok := ft["ccname"]; ok {
  6340. if _, ok := ft2["ccname"]; ok {
  6341. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6342. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6343. }
  6344. }
  6345. }
  6346. if _, ok := ft["source"]; ok {
  6347. if _, ok := ft2["source"]; ok {
  6348. if ft["source"].(string) != ft2["source"].(string) {
  6349. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6350. }
  6351. }
  6352. }
  6353. if _, ok := ft["version"]; ok {
  6354. if _, ok := ft2["version"]; ok {
  6355. if ft["version"].(int64) != ft2["version"].(int64) {
  6356. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6357. }
  6358. }
  6359. }
  6360. if _, ok := ft["remark"]; ok {
  6361. if _, ok := ft2["remark"]; ok {
  6362. if ft["remark"].(string) != ft2["remark"].(string) {
  6363. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6364. }
  6365. }
  6366. }
  6367. break
  6368. }
  6369. }
  6370. dataList := make([]map[string]interface{}, 0)
  6371. if len(fithisList) > 0 {
  6372. for _, fit := range fithisList {
  6373. data := make(map[string]interface{})
  6374. data["feedgroup"] = fit["feedgroup"]
  6375. data["fname"] = fit["fname"]
  6376. data["empname"] = fit["empname"]
  6377. if fit["Eweight"] != nil {
  6378. if fit["Eweight"].(string) != fit["weight"].(string) {
  6379. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6380. } else {
  6381. data["fweight"] = fit["Eweight"]
  6382. }
  6383. data["fweightstatus"] = 1
  6384. } else {
  6385. data["fweight"] = fit["weight"]
  6386. data["fweightstatus"] = 0
  6387. }
  6388. data["autosecond"] = fit["autosecond"]
  6389. // data["tname"] = ft["tname"]
  6390. // data["tcode"] = ft["tcode"]
  6391. // data["tcolor"] = ft["tcolor"]
  6392. // data["fttype"] = ft["fttype"]
  6393. // data["ccname"] = ft["ccname"]
  6394. // data["source"] = ft["source"]
  6395. // data["version"] = ft["version"]
  6396. // data["remark"] = ft["remark"]
  6397. // data["createdate"] = ft["createdate1"]
  6398. // ft["fit"] = data
  6399. dataList = append(dataList, data)
  6400. }
  6401. } else {
  6402. for _, fit := range ftdetailList {
  6403. data := make(map[string]interface{})
  6404. data["feedgroup"] = fit["feedgroup"]
  6405. data["fname"] = fit["fname"]
  6406. // if fit["Eweight"] != nil {
  6407. // data["weight"] = fit["Eweight"]
  6408. // } else {
  6409. data["fweight"] = fit["fweight"]
  6410. // }
  6411. data["autosecond"] = fit["autosecond"]
  6412. // ft["fit"] = data
  6413. dataList = append(dataList, data)
  6414. }
  6415. }
  6416. ft["fit"] = dataList
  6417. }
  6418. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6419. }
  6420. func UpdateMaterialTMR(c *gin.Context) {
  6421. appG := app.Gin{C: c}
  6422. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6423. parammaps := gofasion.NewFasion(string(dataByte))
  6424. tmrid := parammaps.Get("tmrid").ValueStr()
  6425. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6426. lppid := parammaps.Get("lppid").ValueStr()
  6427. times := parammaps.Get("times").ValueStr()
  6428. pastureid := parammaps.Get("pastureid").ValueStr()
  6429. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6430. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6431. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6432. tx := restful.Engine.NewSession()
  6433. defer tx.Close()
  6434. tx.Begin()
  6435. if tmrid != "1000" {
  6436. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6437. if err != nil {
  6438. logs.Error(err)
  6439. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6440. return
  6441. }
  6442. var maxstirfeed float64
  6443. for _, tmr := range tmrList {
  6444. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6445. }
  6446. if status == 0 {
  6447. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6448. if err != nil {
  6449. tx.Rollback()
  6450. logs.Error(err)
  6451. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6452. return
  6453. }
  6454. var lweight float64
  6455. for _, item := range lpplandtl1List {
  6456. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6457. lweight += fl
  6458. }
  6459. if lweight > maxstirfeed {
  6460. lweight = lweight - maxstirfeed
  6461. } else {
  6462. lweight = 0
  6463. }
  6464. if lweight > 0 {
  6465. lweight1 := lweight / float64(len(lpplandtl1List))
  6466. number := 0
  6467. for _, item := range lpplandtl1List {
  6468. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6469. if lweight1 >= fl {
  6470. number++
  6471. }
  6472. }
  6473. lweight := lweight / float64((len(lpplandtl1List) - number))
  6474. for _, item := range lpplandtl1List {
  6475. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6476. if lweight1 >= fl {
  6477. continue
  6478. }
  6479. if tmrtype == "1" {
  6480. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6481. if err != nil {
  6482. tx.Rollback()
  6483. logs.Error(err)
  6484. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6485. return
  6486. }
  6487. } else if tmrtype == "2" {
  6488. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6489. if err != nil {
  6490. tx.Rollback()
  6491. logs.Error(err)
  6492. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6493. return
  6494. }
  6495. }
  6496. if item["fttype"].(int64) == 0 {
  6497. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6498. if err != nil {
  6499. tx.Rollback()
  6500. logs.Error(err)
  6501. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6502. return
  6503. }
  6504. } else {
  6505. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6506. if err != nil {
  6507. tx.Rollback()
  6508. logs.Error(err)
  6509. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6510. return
  6511. }
  6512. }
  6513. }
  6514. } else {
  6515. for _, item := range lpplandtl1List {
  6516. // 自走式
  6517. if tmrtype == "1" {
  6518. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6519. if err != nil {
  6520. logs.Error(err)
  6521. tx.Rollback()
  6522. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6523. return
  6524. }
  6525. } else if tmrtype == "2" {
  6526. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6527. if err != nil {
  6528. logs.Error(err)
  6529. tx.Rollback()
  6530. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6531. return
  6532. }
  6533. }
  6534. }
  6535. }
  6536. } else if status == 1 {
  6537. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6538. if err != nil {
  6539. logs.Error(err)
  6540. tx.Rollback()
  6541. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6542. return
  6543. }
  6544. var lweight float64
  6545. for _, item := range lpplandtl1List {
  6546. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6547. lweight += fl
  6548. }
  6549. if lweight > maxstirfeed {
  6550. lweight = lweight - maxstirfeed
  6551. } else {
  6552. lweight = 0
  6553. }
  6554. for _, item := range lpplandtl1List {
  6555. if lweight > 0 {
  6556. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6557. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6558. if fl >= lweight {
  6559. item["lweight"] = fl - lweight
  6560. lweight = 0
  6561. if tmrtype == "1" {
  6562. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6563. if err != nil {
  6564. logs.Error(err)
  6565. tx.Rollback()
  6566. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6567. return
  6568. }
  6569. } else if tmrtype == "2" {
  6570. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6571. if err != nil {
  6572. logs.Error(err)
  6573. tx.Rollback()
  6574. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6575. return
  6576. }
  6577. }
  6578. if item["fttype"].(int64) == 0 {
  6579. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6580. if err != nil {
  6581. logs.Error(err)
  6582. tx.Rollback()
  6583. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6584. return
  6585. }
  6586. } else {
  6587. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6588. if err != nil {
  6589. logs.Error(err)
  6590. tx.Rollback()
  6591. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6592. return
  6593. }
  6594. }
  6595. } else {
  6596. lweight = lweight - fl
  6597. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6598. if err != nil {
  6599. logs.Error(err)
  6600. tx.Rollback()
  6601. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6602. return
  6603. }
  6604. if item["fttype"].(int64) == 0 {
  6605. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6606. if err != nil {
  6607. logs.Error(err)
  6608. tx.Rollback()
  6609. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6610. return
  6611. }
  6612. } else {
  6613. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6614. if err != nil {
  6615. logs.Error(err)
  6616. tx.Rollback()
  6617. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6618. return
  6619. }
  6620. }
  6621. }
  6622. } else {
  6623. // 自走式
  6624. if tmrtype == "1" {
  6625. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6626. if err != nil {
  6627. logs.Error(err)
  6628. tx.Rollback()
  6629. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6630. return
  6631. }
  6632. } else if tmrtype == "2" {
  6633. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6634. if err != nil {
  6635. logs.Error(err)
  6636. tx.Rollback()
  6637. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6638. return
  6639. }
  6640. }
  6641. }
  6642. }
  6643. } else {
  6644. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6645. if err != nil {
  6646. logs.Error(err)
  6647. tx.Rollback()
  6648. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6649. return
  6650. }
  6651. for _, item := range lpplandtl1List {
  6652. if item["fttype"].(int64) == 0 {
  6653. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6654. if err != nil {
  6655. logs.Error(err)
  6656. tx.Rollback()
  6657. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6658. return
  6659. }
  6660. } else {
  6661. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6662. if err != nil {
  6663. logs.Error(err)
  6664. tx.Rollback()
  6665. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6666. return
  6667. }
  6668. }
  6669. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6670. if err != nil {
  6671. logs.Error(err)
  6672. tx.Rollback()
  6673. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6674. return
  6675. }
  6676. }
  6677. }
  6678. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6679. if err != nil {
  6680. logs.Error(err)
  6681. tx.Rollback()
  6682. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6683. return
  6684. }
  6685. } else {
  6686. if status == 2 {
  6687. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6688. if err != nil {
  6689. logs.Error(err)
  6690. tx.Rollback()
  6691. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6692. return
  6693. }
  6694. for _, item := range lpplandtl1List {
  6695. if item["fttype"].(int64) == 0 {
  6696. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6697. if err != nil {
  6698. logs.Error(err)
  6699. tx.Rollback()
  6700. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6701. return
  6702. }
  6703. } else {
  6704. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6705. if err != nil {
  6706. logs.Error(err)
  6707. tx.Rollback()
  6708. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6709. return
  6710. }
  6711. }
  6712. }
  6713. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6714. if err != nil {
  6715. logs.Error(err)
  6716. tx.Rollback()
  6717. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6718. return
  6719. }
  6720. } else {
  6721. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6722. if err != nil {
  6723. logs.Error(err)
  6724. tx.Rollback()
  6725. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6726. return
  6727. }
  6728. }
  6729. }
  6730. err := tx.Commit()
  6731. if err != nil {
  6732. logs.Error(err)
  6733. tx.Rollback()
  6734. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6735. return
  6736. }
  6737. appG.Response(http.StatusOK, e.SUCCESS, true)
  6738. }
  6739. func UpdateMaterialTMRDate(c *gin.Context) {
  6740. appG := app.Gin{C: c}
  6741. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6742. parammaps := gofasion.NewFasion(string(dataByte))
  6743. tmrid := parammaps.Get("tmrid").ValueStr()
  6744. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6745. lppid := parammaps.Get("lppid").ValueStr()
  6746. times := parammaps.Get("times").ValueStr()
  6747. pastureid := parammaps.Get("pastureid").ValueStr()
  6748. date := parammaps.Get("date").ValueStr()
  6749. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6750. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6751. tx := restful.Engine.NewSession()
  6752. defer tx.Close()
  6753. tx.Begin()
  6754. if tmrid != "1000" {
  6755. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6756. if err != nil {
  6757. logs.Error(err)
  6758. tx.Rollback()
  6759. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6760. return
  6761. }
  6762. var maxstirfeed float64
  6763. for _, tmr := range tmrList {
  6764. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6765. }
  6766. if status == 0 {
  6767. 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()
  6768. if err != nil {
  6769. logs.Error(err)
  6770. tx.Rollback()
  6771. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6772. return
  6773. }
  6774. var lweight float64
  6775. for _, item := range lpplandtl1List {
  6776. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6777. lweight += fl
  6778. }
  6779. if lweight > maxstirfeed {
  6780. lweight = lweight - maxstirfeed
  6781. } else {
  6782. lweight = 0
  6783. }
  6784. if lweight > 0 {
  6785. lweight1 := lweight / float64(len(lpplandtl1List))
  6786. number := 0
  6787. for _, item := range lpplandtl1List {
  6788. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6789. if lweight1 >= fl {
  6790. number++
  6791. }
  6792. }
  6793. lweight := lweight / float64((len(lpplandtl1List) - number))
  6794. for _, item := range lpplandtl1List {
  6795. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6796. if lweight1 >= fl {
  6797. continue
  6798. }
  6799. if tmrtype == "1" {
  6800. _, 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()
  6801. if err != nil {
  6802. logs.Error(err)
  6803. tx.Rollback()
  6804. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6805. return
  6806. }
  6807. } else if tmrtype == "2" {
  6808. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6809. if err != nil {
  6810. logs.Error(err)
  6811. tx.Rollback()
  6812. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6813. return
  6814. }
  6815. }
  6816. if item["fttype"].(int64) == 0 {
  6817. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6818. if err != nil {
  6819. logs.Error(err)
  6820. tx.Rollback()
  6821. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6822. return
  6823. }
  6824. } else {
  6825. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6826. if err != nil {
  6827. logs.Error(err)
  6828. tx.Rollback()
  6829. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6830. return
  6831. }
  6832. }
  6833. }
  6834. } else {
  6835. for _, item := range lpplandtl1List {
  6836. // 自走式
  6837. if tmrtype == "1" {
  6838. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6839. if err != nil {
  6840. logs.Error(err)
  6841. tx.Rollback()
  6842. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6843. return
  6844. }
  6845. } else if tmrtype == "2" {
  6846. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6847. if err != nil {
  6848. logs.Error(err)
  6849. tx.Rollback()
  6850. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6851. return
  6852. }
  6853. }
  6854. }
  6855. }
  6856. } else if status == 1 {
  6857. 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()
  6858. if err != nil {
  6859. logs.Error(err)
  6860. tx.Rollback()
  6861. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6862. return
  6863. }
  6864. var lweight float64
  6865. for _, item := range lpplandtl1List {
  6866. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6867. lweight += fl
  6868. }
  6869. if lweight > maxstirfeed {
  6870. lweight = lweight - maxstirfeed
  6871. } else {
  6872. lweight = 0
  6873. }
  6874. for _, item := range lpplandtl1List {
  6875. if lweight > 0 {
  6876. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6877. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6878. if fl >= lweight {
  6879. item["lweight"] = fl - lweight
  6880. lweight = 0
  6881. if tmrtype == "1" {
  6882. _, 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()
  6883. if err != nil {
  6884. logs.Error(err)
  6885. tx.Rollback()
  6886. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6887. return
  6888. }
  6889. } else if tmrtype == "2" {
  6890. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6891. if err != nil {
  6892. logs.Error(err)
  6893. tx.Rollback()
  6894. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6895. return
  6896. }
  6897. }
  6898. if item["fttype"].(int64) == 0 {
  6899. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6900. if err != nil {
  6901. logs.Error(err)
  6902. tx.Rollback()
  6903. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6904. return
  6905. }
  6906. } else {
  6907. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6908. if err != nil {
  6909. logs.Error(err)
  6910. tx.Rollback()
  6911. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6912. return
  6913. }
  6914. }
  6915. } else {
  6916. lweight = lweight - fl
  6917. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6918. if err != nil {
  6919. logs.Error(err)
  6920. tx.Rollback()
  6921. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6922. return
  6923. }
  6924. if item["fttype"].(int64) == 0 {
  6925. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6926. if err != nil {
  6927. logs.Error(err)
  6928. tx.Rollback()
  6929. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6930. return
  6931. }
  6932. } else {
  6933. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6934. if err != nil {
  6935. logs.Error(err)
  6936. tx.Rollback()
  6937. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6938. return
  6939. }
  6940. }
  6941. }
  6942. } else {
  6943. // 自走式
  6944. if tmrtype == "1" {
  6945. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6946. if err != nil {
  6947. logs.Error(err)
  6948. tx.Rollback()
  6949. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6950. return
  6951. }
  6952. } else if tmrtype == "2" {
  6953. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6954. if err != nil {
  6955. logs.Error(err)
  6956. tx.Rollback()
  6957. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6958. return
  6959. }
  6960. }
  6961. }
  6962. }
  6963. } else {
  6964. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6965. if err != nil {
  6966. logs.Error(err)
  6967. tx.Rollback()
  6968. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6969. return
  6970. }
  6971. for _, item := range lpplandtl1List {
  6972. if item["fttype"].(int64) == 0 {
  6973. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6974. if err != nil {
  6975. logs.Error(err)
  6976. tx.Rollback()
  6977. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6978. return
  6979. }
  6980. } else {
  6981. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6982. if err != nil {
  6983. logs.Error(err)
  6984. tx.Rollback()
  6985. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6986. return
  6987. }
  6988. }
  6989. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6990. if err != nil {
  6991. logs.Error(err)
  6992. tx.Rollback()
  6993. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6994. return
  6995. }
  6996. }
  6997. }
  6998. _, 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()
  6999. if err != nil {
  7000. logs.Error(err)
  7001. tx.Rollback()
  7002. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7003. return
  7004. }
  7005. } else {
  7006. if status == 2 {
  7007. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  7008. if err != nil {
  7009. logs.Error(err)
  7010. tx.Rollback()
  7011. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7012. return
  7013. }
  7014. for _, item := range lpplandtl1List {
  7015. if item["fttype"].(int64) == 0 {
  7016. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7017. if err != nil {
  7018. logs.Error(err)
  7019. tx.Rollback()
  7020. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7021. return
  7022. }
  7023. } else {
  7024. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7025. if err != nil {
  7026. logs.Error(err)
  7027. tx.Rollback()
  7028. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7029. return
  7030. }
  7031. }
  7032. }
  7033. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  7034. if err != nil {
  7035. logs.Error(err)
  7036. tx.Rollback()
  7037. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7038. return
  7039. }
  7040. } else {
  7041. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  7042. if err != nil {
  7043. logs.Error(err)
  7044. tx.Rollback()
  7045. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7046. return
  7047. }
  7048. }
  7049. }
  7050. err := tx.Commit()
  7051. if err != nil {
  7052. logs.Error(err)
  7053. tx.Rollback()
  7054. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7055. return
  7056. }
  7057. appG.Response(http.StatusOK, e.SUCCESS, true)
  7058. }
  7059. func Decimal(value float64) float64 {
  7060. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  7061. return value
  7062. }
  7063. func UpdateDailyData(c *gin.Context) {
  7064. appG := app.Gin{C: c}
  7065. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7066. parammaps := gofasion.NewFasion(string(dataByte))
  7067. pid := parammaps.Get("pid").ValueDefaultStr("0")
  7068. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  7069. sort := parammaps.Get("sort").ValueDefaultStr("0")
  7070. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  7071. date := parammaps.Get("date").ValueStr()
  7072. tx := restful.Engine.NewSession()
  7073. defer tx.Close()
  7074. 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()
  7075. if err != nil {
  7076. logs.Error("UpdateDailyData-error-0:", err)
  7077. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7078. return
  7079. }
  7080. if count > 0 {
  7081. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7082. return
  7083. }
  7084. tx.Begin()
  7085. if location == 0 {
  7086. fid := parammaps.Get("fid").ValueStr()
  7087. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  7088. if err != nil {
  7089. logs.Error("UpdateDailyData-error-1:", err)
  7090. tx.Rollback()
  7091. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7092. return
  7093. }
  7094. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7095. if err != nil {
  7096. logs.Error("UpdateDailyData-error-1:", err)
  7097. tx.Rollback()
  7098. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7099. return
  7100. }
  7101. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7102. if err != nil {
  7103. fmt.Println("Error:", err)
  7104. return
  7105. }
  7106. actualWeight := weight - num
  7107. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7108. if err != nil {
  7109. logs.Error("UpdateDailyData-error-2:", err)
  7110. tx.Rollback()
  7111. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7112. return
  7113. }
  7114. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7115. if err != nil {
  7116. logs.Error("UpdateDailyData-error-3:", err)
  7117. tx.Rollback()
  7118. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7119. return
  7120. }
  7121. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7122. if err != nil {
  7123. logs.Error("UpdateDailyData-error-4:", err)
  7124. tx.Rollback()
  7125. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7126. return
  7127. }
  7128. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7129. if err != nil {
  7130. logs.Error("UpdateDailyData-error-5:", err)
  7131. tx.Rollback()
  7132. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7133. return
  7134. }
  7135. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7136. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7137. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7138. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7139. if err != nil {
  7140. fmt.Println("Error:", err)
  7141. return
  7142. }
  7143. // actual := actualWeight / float64(len(downloadedplanList))
  7144. for _, item := range downloadedplanList {
  7145. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7146. if err != nil {
  7147. fmt.Println("Error:", err)
  7148. return
  7149. }
  7150. actual := itemLweight / lweight * actualWeight
  7151. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7152. if err != nil {
  7153. logs.Error("UpdateDailyData-error-6:", err)
  7154. tx.Rollback()
  7155. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7156. return
  7157. }
  7158. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7159. if err != nil {
  7160. logs.Error("UpdateDailyData-error-7:", err)
  7161. tx.Rollback()
  7162. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7163. return
  7164. }
  7165. _, 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()
  7166. if err != nil {
  7167. logs.Error("UpdateDailyData-error-8:", err)
  7168. tx.Rollback()
  7169. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7170. return
  7171. }
  7172. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7173. if err != nil {
  7174. logs.Error("UpdateDailyData-error-9:", err)
  7175. tx.Rollback()
  7176. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7177. return
  7178. }
  7179. }
  7180. } else {
  7181. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7182. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7183. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7184. // if err != nil {
  7185. // fmt.Println("Error:", err)
  7186. // return
  7187. // }
  7188. for _, item := range downloadedplanList {
  7189. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7190. if err != nil {
  7191. logs.Error("UpdateDailyData-error-6:", err)
  7192. tx.Rollback()
  7193. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7194. return
  7195. }
  7196. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7197. item["lweight"], actualWeight, item["id"]).Execute()
  7198. if err != nil {
  7199. logs.Error("UpdateDailyData-error-7:", err)
  7200. tx.Rollback()
  7201. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7202. return
  7203. }
  7204. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7205. where pid = ?`, item["id"]).Execute()
  7206. if err != nil {
  7207. logs.Error("UpdateDailyData-error-8:", err)
  7208. tx.Rollback()
  7209. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7210. return
  7211. }
  7212. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7213. if err != nil {
  7214. logs.Error("UpdateDailyData-error-9:", err)
  7215. tx.Rollback()
  7216. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7217. return
  7218. }
  7219. }
  7220. }
  7221. } else {
  7222. fbarid := parammaps.Get("fbarid").ValueStr()
  7223. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7224. if err != nil {
  7225. logs.Error("UpdateDailyData-error-10:", err)
  7226. tx.Rollback()
  7227. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7228. return
  7229. }
  7230. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7231. if err != nil {
  7232. logs.Error("UpdateDailyData-error-1:", err)
  7233. tx.Rollback()
  7234. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7235. return
  7236. }
  7237. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7238. if err != nil {
  7239. fmt.Println("Error:", err)
  7240. return
  7241. }
  7242. actualWeight := weight - num
  7243. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7244. if err != nil {
  7245. logs.Error("UpdateDailyData-error-11:", err)
  7246. tx.Rollback()
  7247. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7248. return
  7249. }
  7250. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  7251. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7252. if err != nil {
  7253. logs.Error("UpdateDailyData-error-12:", err)
  7254. tx.Rollback()
  7255. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7256. return
  7257. }
  7258. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7259. where pid = ? `, pid).Execute()
  7260. if err != nil {
  7261. logs.Error("UpdateDailyData-error-13:", err)
  7262. tx.Rollback()
  7263. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7264. return
  7265. }
  7266. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7267. if err != nil {
  7268. logs.Error("UpdateDailyData-error-14:", err)
  7269. tx.Rollback()
  7270. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7271. return
  7272. }
  7273. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7274. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7275. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7276. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7277. if err != nil {
  7278. fmt.Println("Error:", err)
  7279. return
  7280. }
  7281. for _, item := range downloadedplanList {
  7282. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7283. if err != nil {
  7284. fmt.Println("Error:", err)
  7285. return
  7286. }
  7287. actual := itemLweight / lweight * actualWeight
  7288. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7289. if err != nil {
  7290. logs.Error("UpdateDailyData-error-6:", err)
  7291. tx.Rollback()
  7292. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7293. return
  7294. }
  7295. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7296. if err != nil {
  7297. logs.Error("UpdateDailyData-error-7:", err)
  7298. tx.Rollback()
  7299. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7300. return
  7301. }
  7302. _, 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()
  7303. if err != nil {
  7304. logs.Error("UpdateDailyData-error-8:", err)
  7305. tx.Rollback()
  7306. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7307. return
  7308. }
  7309. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7310. if err != nil {
  7311. logs.Error("UpdateDailyData-error-9:", err)
  7312. tx.Rollback()
  7313. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7314. return
  7315. }
  7316. }
  7317. } else {
  7318. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7319. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7320. for _, item := range downloadedplanList {
  7321. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7322. // if err != nil {
  7323. // fmt.Println("Error:", err)
  7324. // return
  7325. // }
  7326. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7327. if err != nil {
  7328. logs.Error("UpdateDailyData-error-6:", err)
  7329. tx.Rollback()
  7330. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7331. return
  7332. }
  7333. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7334. item["lweight"], actualWeight, item["id"]).Execute()
  7335. if err != nil {
  7336. logs.Error("UpdateDailyData-error-7:", err)
  7337. tx.Rollback()
  7338. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7339. return
  7340. }
  7341. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7342. where pid = ?`, item["id"]).Execute()
  7343. if err != nil {
  7344. logs.Error("UpdateDailyData-error-8:", err)
  7345. tx.Rollback()
  7346. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7347. return
  7348. }
  7349. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7350. if err != nil {
  7351. logs.Error("UpdateDailyData-error-9:", err)
  7352. tx.Rollback()
  7353. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7354. return
  7355. }
  7356. }
  7357. }
  7358. }
  7359. err = tx.Commit()
  7360. if err != nil {
  7361. logs.Error("UpdateDailyData-error-20:", err)
  7362. tx.Rollback()
  7363. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7364. return
  7365. }
  7366. appG.Response(http.StatusOK, e.SUCCESS, true)
  7367. }
  7368. func GetFormulaStatistics(c *gin.Context) {
  7369. appG := app.Gin{C: c}
  7370. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7371. parammaps := gofasion.NewFasion(string(dataByte))
  7372. startTime := parammaps.Get("startTime").ValueStr()
  7373. endTime := parammaps.Get("endTime").ValueStr()
  7374. pastureId := parammaps.Get("pastureId").ValueStr()
  7375. tx := restful.Engine.NewSession()
  7376. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7377. if err != nil {
  7378. logs.Error("GetFormulaStatistics-error-1:", err)
  7379. tx.Rollback()
  7380. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7381. return
  7382. }
  7383. var feedtemplet, dateList []string
  7384. for _, f := range feedtempletList {
  7385. feedtemplet = append(feedtemplet, f["tname"].(string))
  7386. }
  7387. layout := "2006-01-02"
  7388. // s := "2023-05-01"
  7389. // e := "2023-05-23"
  7390. start, err := time.Parse(layout, startTime)
  7391. if err != nil {
  7392. fmt.Println(err)
  7393. return
  7394. }
  7395. end, err := time.Parse(layout, endTime)
  7396. if err != nil {
  7397. fmt.Println(err)
  7398. return
  7399. }
  7400. end = end.AddDate(0, 0, 1)
  7401. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7402. dateList = append(dateList, d.Format("2006-01-02"))
  7403. }
  7404. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7405. 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= ?
  7406. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7407. if err != nil {
  7408. logs.Error("GetFormulaStatistics-error-2:", err)
  7409. tx.Rollback()
  7410. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7411. return
  7412. }
  7413. var data2 [][]interface{}
  7414. for _, f := range feedtemplet {
  7415. var data1 []interface{}
  7416. for _, date := range dateList {
  7417. exist := false
  7418. for _, item := range downloadedplanList {
  7419. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7420. data1 = append(data1, item["total"])
  7421. exist = true
  7422. break
  7423. }
  7424. }
  7425. if !exist {
  7426. data1 = append(data1, 0)
  7427. }
  7428. }
  7429. data2 = append(data2, data1)
  7430. }
  7431. //前端让加的
  7432. feedtemplet = append(feedtemplet, "")
  7433. {
  7434. var data1 []interface{}
  7435. for _, f := range dateList {
  7436. // f = f + "\n"
  7437. fmt.Println(f)
  7438. data1 = append(data1, 0)
  7439. }
  7440. data2 = append(data2, data1)
  7441. }
  7442. resp := make(map[string]interface{}, 0)
  7443. resp["xdata"] = dateList
  7444. resp["data1"] = feedtemplet
  7445. resp["data2"] = data2
  7446. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7447. }
  7448. func GetPlanData(c *gin.Context) {
  7449. appG := app.Gin{C: c}
  7450. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7451. fsion := gofasion.NewFasion(string(dataByte))
  7452. sqlnamestr := fsion.Get("name").ValueStr()
  7453. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7454. offset := fsion.Get("offset").ValueDefaultInt(0)
  7455. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7456. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7457. month := fsion.Get("month").ValueDefaultStr("map")
  7458. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7459. tx := restful.Engine.NewSession()
  7460. err := tx.Begin()
  7461. defer func() {
  7462. switch {
  7463. case err != nil:
  7464. if tx != nil {
  7465. tx.Rollback()
  7466. }
  7467. default:
  7468. if tx != nil {
  7469. err = tx.Commit()
  7470. }
  7471. }
  7472. if tx != nil {
  7473. tx.Close()
  7474. }
  7475. }()
  7476. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7477. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7478. if sql != "" {
  7479. s_params := make([]interface{}, 0)
  7480. if fsion.HasKey("parammaps") {
  7481. parammaps := fsion.Get("parammaps")
  7482. paramslist := strings.Split(p, ",")
  7483. if len(paramslist) > 0 && p != "" {
  7484. for _, value := range paramslist {
  7485. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7486. if tempv, exists := c.Get("jwt_username"); exists {
  7487. s_params = append(s_params, tempv.(string))
  7488. } else {
  7489. s_params = append(s_params, "")
  7490. }
  7491. } else {
  7492. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7493. }
  7494. }
  7495. }
  7496. }
  7497. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7498. if err != nil {
  7499. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7500. } else {
  7501. paramslist1 := strings.Split(p1, ",")
  7502. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7503. s_params1 := make([]interface{}, 0)
  7504. if len(paramslist1) > 0 && p1 != "" {
  7505. for _, v := range paramslist1 {
  7506. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7507. }
  7508. }
  7509. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7510. for _, item := range arr {
  7511. trgaddressList := []string{}
  7512. if _, ok := item["trgaddress"]; ok {
  7513. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7514. for _, str := range trgaddressList1 {
  7515. if str != "" {
  7516. trgaddressList = append(trgaddressList, str)
  7517. }
  7518. }
  7519. }
  7520. item["trgaddressList"] = trgaddressList
  7521. }
  7522. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7523. }
  7524. // var wg sync.WaitGroup
  7525. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7526. // wg.Add(1)
  7527. // go func(value map[string]interface{}) {
  7528. // defer wg.Done()
  7529. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7530. // }(value)
  7531. // }
  7532. // wg.Wait()
  7533. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7534. }
  7535. } else {
  7536. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7537. }
  7538. }
  7539. func PostPlanData(c *gin.Context) {
  7540. appG := app.Gin{C: c}
  7541. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7542. fsion := gofasion.NewFasion(string(dataByte))
  7543. logging.Info("PostRJSBData err: ", string(dataByte))
  7544. s_params := make([]interface{}, 0)
  7545. tx := restful.Engine.NewSession()
  7546. err := tx.Begin()
  7547. defer func() {
  7548. switch {
  7549. case err != nil:
  7550. if tx != nil {
  7551. tx.Rollback()
  7552. }
  7553. default:
  7554. if tx != nil {
  7555. err = tx.Commit()
  7556. }
  7557. }
  7558. if tx != nil {
  7559. tx.Close()
  7560. }
  7561. }()
  7562. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7563. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7564. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7565. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7566. if !fsion.HasKey("parammaps") {
  7567. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7568. return
  7569. }
  7570. parammaps := fsion.Get("parammaps")
  7571. // paramslist := strings.Split(p, ",")
  7572. // if len(paramslist) > 0 && p != "" {
  7573. // for _, value := range paramslist {
  7574. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7575. // }
  7576. // }
  7577. // _, err = tx.SQL(sql, s_params...).Execute()
  7578. // if err != nil {
  7579. // logging.Error("PostRJSBData err: ", err)
  7580. // msg := geterrmsg(err.Error())
  7581. // appG.Response(http.StatusOK, e.ERROR, msg)
  7582. // return
  7583. // }
  7584. s_params = make([]interface{}, 0)
  7585. paramslist := strings.Split(p1, ",")
  7586. if len(paramslist) > 0 && p1 != "" {
  7587. for _, value := range paramslist {
  7588. // if value == "ID" {
  7589. // id := parammaps.Get("ID").ValueStr()
  7590. // pastureid := parammaps.Get("pastureid").ValueStr()
  7591. // 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
  7592. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7593. // if err != nil {
  7594. // logging.Error("PostRJSBData err: ", err)
  7595. // msg := geterrmsg(err.Error())
  7596. // appG.Response(http.StatusOK, e.ERROR, msg)
  7597. // return
  7598. // }
  7599. // for _, item := range datalist {
  7600. // id = item["id"]
  7601. // }
  7602. // s_params = append(s_params, id)
  7603. // } else {
  7604. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7605. // }
  7606. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7607. }
  7608. }
  7609. _, err = tx.SQL(sql1, s_params...).Execute()
  7610. if err != nil {
  7611. logging.Error("PostRJSBData1 err: ", err)
  7612. msg := geterrmsg(err.Error())
  7613. appG.Response(http.StatusOK, e.ERROR, msg)
  7614. return
  7615. }
  7616. s_params = make([]interface{}, 0)
  7617. paramslist = strings.Split(p2, ",")
  7618. if len(paramslist) > 0 && p2 != "" {
  7619. for _, value := range paramslist {
  7620. if value == "ID" {
  7621. id := parammaps.Get("ID").ValueStr()
  7622. pastureid := parammaps.Get("pastureid").ValueStr()
  7623. 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
  7624. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7625. if err != nil {
  7626. logging.Error("PostRJSBData err: ", err)
  7627. msg := geterrmsg(err.Error())
  7628. appG.Response(http.StatusOK, e.ERROR, msg)
  7629. return
  7630. }
  7631. for _, item := range datalist {
  7632. id = item["id"]
  7633. }
  7634. s_params = append(s_params, id)
  7635. } else {
  7636. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7637. }
  7638. }
  7639. }
  7640. _, err = tx.SQL(sql2, s_params...).Execute()
  7641. if err != nil {
  7642. logging.Error("PostRJSBData2 err: ", err)
  7643. msg := geterrmsg(err.Error())
  7644. appG.Response(http.StatusOK, e.ERROR, msg)
  7645. return
  7646. }
  7647. s_params = make([]interface{}, 0)
  7648. paramslist = strings.Split(p3, ",")
  7649. if len(paramslist) > 0 && p3 != "" {
  7650. for _, value := range paramslist {
  7651. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7652. }
  7653. }
  7654. _, err = tx.SQL(sql3, s_params...).Execute()
  7655. if err != nil {
  7656. logging.Error("PostRJSBData3 err: ", err)
  7657. msg := geterrmsg(err.Error())
  7658. appG.Response(http.StatusOK, e.ERROR, msg)
  7659. return
  7660. }
  7661. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7662. }
  7663. func CheckFeedTrgaddress(c *gin.Context) {
  7664. appG := app.Gin{C: c}
  7665. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7666. fsion := gofasion.NewFasion(string(dataByte))
  7667. fclassid := fsion.Get("fclassid").ValueStr()
  7668. feedId := fsion.Get("feedId").ValueStr()
  7669. backup1 := fsion.Get("backup1").ValueStr()
  7670. backup1List := strings.Split(backup1, ",")
  7671. tx := restful.Engine.NewSession()
  7672. defer tx.Close()
  7673. // if backup1 != "" {
  7674. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7675. for _, feed := range feedList {
  7676. if feed["backup1"] == "" {
  7677. continue
  7678. }
  7679. feedbackupList := strings.Split(feed["backup1"], ",")
  7680. for _, feedbackup := range feedbackupList {
  7681. for _, backup := range backup1List {
  7682. if feedbackup == backup {
  7683. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7684. return
  7685. }
  7686. }
  7687. }
  7688. }
  7689. // }
  7690. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7691. }
  7692. func ThiGetDataByName(c *gin.Context) {
  7693. appG := app.Gin{C: c}
  7694. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7695. fsion := gofasion.NewFasion(string(dataByte))
  7696. sqlnamestr := fsion.Get("name").ValueStr()
  7697. offset := fsion.Get("offset").ValueDefaultInt(0)
  7698. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7699. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7700. tx := restful.Engine.NewSession()
  7701. err := tx.Begin()
  7702. defer func() {
  7703. switch {
  7704. case err != nil:
  7705. logging.Error("tx.Begin 事务启动失败__error:", err)
  7706. if tx != nil {
  7707. tx.Rollback()
  7708. }
  7709. default:
  7710. if tx != nil {
  7711. err = tx.Commit()
  7712. }
  7713. }
  7714. if tx != nil {
  7715. tx.Close()
  7716. }
  7717. }()
  7718. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7719. if sql != "" {
  7720. s_params := make([]interface{}, 0)
  7721. if fsion.HasKey("parammaps") {
  7722. parammaps := fsion.Get("parammaps")
  7723. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7724. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7725. }
  7726. paramslist := strings.Split(p, ",")
  7727. if len(paramslist) > 0 && p != "" {
  7728. for _, value := range paramslist {
  7729. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7730. if tempv, exists := c.Get("jwt_username"); exists {
  7731. s_params = append(s_params, tempv.(string))
  7732. } else {
  7733. s_params = append(s_params, "")
  7734. }
  7735. } else {
  7736. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7737. }
  7738. }
  7739. }
  7740. } else if fsion.HasKey("params") {
  7741. params := fsion.Get("params").Array()
  7742. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7743. for _, v_params := range params {
  7744. s_params = append(s_params, v_params.ValueStr())
  7745. }
  7746. }
  7747. if returntype == "xlsx" {
  7748. var xlsxfile *xlsx.File
  7749. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7750. //c.File("c:/dd.xlsx")
  7751. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7752. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7753. c.Header("Content-Transfer-Encoding", "binary")
  7754. _ = xlsxfile.Write(c.Writer)
  7755. } else {
  7756. if sqlnamestr == "getHomepageStr" {
  7757. parammaps := fsion.Get("parammaps")
  7758. pastureid := parammaps.Get("pastureid").ValueStr()
  7759. var montimeList []float64
  7760. var montime float64
  7761. var wg sync.WaitGroup
  7762. now := time.Now()
  7763. for i := 0; i < 30; i++ {
  7764. wg.Add(1)
  7765. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7766. go func(nowstr string) {
  7767. defer wg.Done()
  7768. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7769. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7770. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7771. montimeList = append(montimeList, m)
  7772. }(nowstr)
  7773. }
  7774. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7775. if err != nil {
  7776. logging.Error("GetDataByName err: ", err)
  7777. msg := geterrmsg(err.Error())
  7778. appG.Response(http.StatusOK, e.ERROR, msg)
  7779. }
  7780. wg.Wait()
  7781. for _, m := range montimeList {
  7782. montime += m
  7783. }
  7784. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7785. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7786. return
  7787. }
  7788. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7789. if err != nil {
  7790. logging.Error("GetDataByName err: ", err)
  7791. msg := geterrmsg(err.Error())
  7792. appG.Response(http.StatusOK, e.ERROR, msg)
  7793. } else {
  7794. if sqlnamestr == "getFeedTrgaddressList" {
  7795. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7796. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7797. trgaddressList := []string{}
  7798. for _, str := range trgaddressList1 {
  7799. if str != "" {
  7800. trgaddressList = append(trgaddressList, str)
  7801. }
  7802. }
  7803. item["trgaddressList"] = trgaddressList
  7804. }
  7805. }
  7806. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7807. }
  7808. }
  7809. } else {
  7810. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7811. }
  7812. }
  7813. // func ToggleCcount(c *gin.Context) {
  7814. // appG := app.Gin{C: c}
  7815. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7816. // fsion := gofasion.NewFasion(string(dataByte))
  7817. // // 0 实际 1 软件
  7818. // status := fsion.Get("status").ValueDefaultInt64(0)
  7819. // pastureId := fsion.Get("pastureId").ValueStr()
  7820. // tx := restful.Engine.NewSession()
  7821. // err := tx.Begin()
  7822. // defer func() {
  7823. // switch {
  7824. // case err != nil:
  7825. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7826. // if tx != nil {
  7827. // tx.Rollback()
  7828. // }
  7829. // default:
  7830. // if tx != nil {
  7831. // err = tx.Commit()
  7832. // }
  7833. // }
  7834. // if tx != nil {
  7835. // tx.Close()
  7836. // }
  7837. // }()
  7838. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7839. // if err != nil {
  7840. // logs.Error(err)
  7841. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7842. // return
  7843. // }
  7844. // for _, bar := range barList {
  7845. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7846. // if err != nil {
  7847. // logs.Error(err)
  7848. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7849. // return
  7850. // }
  7851. // if !exist {
  7852. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7853. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7854. // if err != nil {
  7855. // logs.Error(err)
  7856. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7857. // return
  7858. // }
  7859. // }
  7860. // }
  7861. // if status == 0 {
  7862. // tx.Exec(`update feedp set ccount = actualcount `)
  7863. // }else{
  7864. // tx.Exec(`update feedp set ccount = softccount `)
  7865. // }
  7866. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7867. // if err != nil {
  7868. // logs.Error(err)
  7869. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7870. // return
  7871. // }
  7872. // for _, feedpData :=range feedpList{
  7873. // var feedpargs []interface{}
  7874. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7875. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7876. // if _, ok := feedpData["ftname"]; ok {
  7877. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7878. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7879. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7880. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7881. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7882. // } else {
  7883. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7884. // }
  7885. // if _, ok := feedpData["ptsfname"]; ok {
  7886. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7887. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7888. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7889. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7890. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7891. // } else {
  7892. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7893. // }
  7894. // upFeedpSql += " where barname = ? and pastureid = ? "
  7895. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7896. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7897. // if err != nil {
  7898. // logs.Error(err)
  7899. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7900. // return
  7901. // }
  7902. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7903. // if err != nil {
  7904. // logs.Error(err)
  7905. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7906. // return
  7907. // }
  7908. // if !exist1 {
  7909. // _, 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) `,
  7910. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7911. // if err != nil {
  7912. // logs.Error(err)
  7913. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7914. // return
  7915. // }
  7916. // }
  7917. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7918. // if err != nil {
  7919. // logs.Error(err)
  7920. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7921. // return
  7922. // }
  7923. // if !exist2 {
  7924. // _, 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) `,
  7925. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7926. // if err != nil {
  7927. // logs.Error(err)
  7928. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7929. // return
  7930. // }
  7931. // }
  7932. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7933. // if err != nil {
  7934. // logs.Error(err)
  7935. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7936. // return
  7937. // }
  7938. // if !exist3 {
  7939. // _, 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) `,
  7940. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7941. // if err != nil {
  7942. // logs.Error(err)
  7943. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7944. // return
  7945. // }
  7946. // }
  7947. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7948. // if err != nil {
  7949. // logs.Error(err)
  7950. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7951. // return
  7952. // }
  7953. // if !exist4 {
  7954. // _, 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) `,
  7955. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7956. // if err != nil {
  7957. // logs.Error(err)
  7958. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7959. // return
  7960. // }
  7961. // }
  7962. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7963. // if err != nil {
  7964. // logs.Error(err)
  7965. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7966. // return
  7967. // }
  7968. // if !exist5 {
  7969. // _, 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) `,
  7970. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7971. // if err != nil {
  7972. // logs.Error(err)
  7973. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7974. // return
  7975. // }
  7976. // }
  7977. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7978. // if err != nil {
  7979. // logs.Error(err)
  7980. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7981. // return
  7982. // }
  7983. // if !exist6 {
  7984. // _, 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) `,
  7985. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7986. // if err != nil {
  7987. // logs.Error(err)
  7988. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7989. // return
  7990. // }
  7991. // }
  7992. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7993. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7994. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7995. // and pastureid = ? and times = ?`
  7996. // var fpdargs1 []interface{}
  7997. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7998. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7999. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8000. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8001. // if err != nil {
  8002. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8003. // return
  8004. // }
  8005. // var fpdargs2 []interface{}
  8006. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8007. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8008. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8009. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8010. // if err != nil {
  8011. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8012. // return
  8013. // }
  8014. // var fpdargs3 []interface{}
  8015. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8016. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8017. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8018. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8019. // if err != nil {
  8020. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8021. // return
  8022. // }
  8023. // var fpdargs4 []interface{}
  8024. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8025. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8026. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8027. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8028. // if err != nil {
  8029. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8030. // return
  8031. // }
  8032. // var fpdargs5 []interface{}
  8033. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8034. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8035. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8036. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8037. // if err != nil {
  8038. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8039. // return
  8040. // }
  8041. // var fpdargs6 []interface{}
  8042. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8043. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8044. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8045. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8046. // if err != nil {
  8047. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8048. // return
  8049. // }
  8050. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8051. // 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()
  8052. // if err != nil {
  8053. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8054. // return
  8055. // }
  8056. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8057. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8058. // upFpdetailList := make([]*upFpdetail, 0)
  8059. // for _, newfpd := range newList {
  8060. // for _, oldfpd := range oldFpdList {
  8061. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8062. // var oldweight, newweight float64
  8063. // if oldfpd["weight"] != nil {
  8064. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8065. // }
  8066. // if newfpd["weight"] != nil {
  8067. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8068. // }
  8069. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8070. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  8071. // Old: oldweight,
  8072. // New: newweight,
  8073. // Times: newfpd["times"].(int64),
  8074. // Ptid: newfpd["ptid"].(int64),
  8075. // Fweight: fweight,
  8076. // Id: oldfpd["id"].(int64),
  8077. // })
  8078. // break
  8079. // }
  8080. // }
  8081. // }
  8082. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8083. // }
  8084. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8085. // }
  8086. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8087. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8088. if err != nil {
  8089. return err
  8090. }
  8091. for _, item := range feedpList {
  8092. // if item["ftid"].(string) != data["ftid"].(string) {
  8093. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8094. if err != nil {
  8095. return err
  8096. }
  8097. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8098. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8099. if err != nil {
  8100. return err
  8101. }
  8102. // }
  8103. }
  8104. return nil
  8105. }
  8106. func PostPlanDatas(c *gin.Context) {
  8107. appG := app.Gin{C: c}
  8108. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8109. fsions := gofasion.NewFasion(string(dataByte))
  8110. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8111. tx := restful.Engine.NewSession()
  8112. err := tx.Begin()
  8113. defer func() {
  8114. switch {
  8115. case err != nil:
  8116. if tx != nil {
  8117. tx.Rollback()
  8118. }
  8119. default:
  8120. if tx != nil {
  8121. err = tx.Commit()
  8122. }
  8123. }
  8124. if tx != nil {
  8125. tx.Close()
  8126. }
  8127. }()
  8128. pastureId := fsions.Get("pastureid").ValueStr()
  8129. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8130. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8131. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8132. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8133. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8134. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8135. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8136. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8137. for _, parammaps := range fsions.Get("arrList").Array() {
  8138. fmt.Println(parammaps.Json())
  8139. if parammaps.Json() == "null" {
  8140. continue
  8141. }
  8142. // if !fsion.HasKey("arrList") {
  8143. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8144. // return
  8145. // continue
  8146. // }
  8147. // parammaps := fsion.Get("arrList")
  8148. s_params := make([]interface{}, 0)
  8149. // paramslist := strings.Split(p, ",")
  8150. // if len(paramslist) > 0 && p != "" {
  8151. // for _, value := range paramslist {
  8152. // if value == "pastureid" {
  8153. // s_params = append(s_params, pastureId)
  8154. // } else {
  8155. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8156. // }
  8157. // }
  8158. // }
  8159. // _, err = tx.SQL(sql, s_params...).Execute()
  8160. // if err != nil {
  8161. // logging.Error("PostRJSBData err: ", err)
  8162. // msg := geterrmsg(err.Error())
  8163. // appG.Response(http.StatusOK, e.ERROR, msg)
  8164. // return
  8165. // }
  8166. s_params = make([]interface{}, 0)
  8167. paramslist := strings.Split(p1, ",")
  8168. if len(paramslist) > 0 && p1 != "" {
  8169. for _, value := range paramslist {
  8170. // if value == "ID" {
  8171. // id := parammaps.Get("ID").ValueStr()
  8172. // pastureid := parammaps.Get("pastureid").ValueStr()
  8173. // 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
  8174. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8175. // if err != nil {
  8176. // logging.Error("PostRJSBData err: ", err)
  8177. // msg := geterrmsg(err.Error())
  8178. // appG.Response(http.StatusOK, e.ERROR, msg)
  8179. // return
  8180. // }
  8181. // for _, item := range datalist {
  8182. // id = item["id"]
  8183. // }
  8184. // s_params = append(s_params, id)
  8185. // } else {
  8186. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8187. // }
  8188. if value == "pastureid" {
  8189. s_params = append(s_params, pastureId)
  8190. } else {
  8191. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8192. }
  8193. }
  8194. }
  8195. _, err = tx.SQL(sql1, s_params...).Execute()
  8196. if err != nil {
  8197. logging.Error("PostRJSBData1 err: ", err)
  8198. msg := geterrmsg(err.Error())
  8199. appG.Response(http.StatusOK, e.ERROR, msg)
  8200. return
  8201. }
  8202. s_params = make([]interface{}, 0)
  8203. paramslist = strings.Split(p2, ",")
  8204. if len(paramslist) > 0 && p2 != "" {
  8205. for _, value := range paramslist {
  8206. if value == "ID" {
  8207. id := parammaps.Get("ID").ValueStr()
  8208. pastureid := parammaps.Get("pastureid").ValueStr()
  8209. 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
  8210. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8211. if err != nil {
  8212. logging.Error("PostRJSBData err: ", err)
  8213. msg := geterrmsg(err.Error())
  8214. appG.Response(http.StatusOK, e.ERROR, msg)
  8215. return
  8216. }
  8217. for _, item := range datalist {
  8218. id = item["id"]
  8219. }
  8220. s_params = append(s_params, id)
  8221. } else if value == "pastureid" {
  8222. s_params = append(s_params, pastureId)
  8223. } else {
  8224. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8225. }
  8226. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8227. }
  8228. }
  8229. _, err = tx.SQL(sql2, s_params...).Execute()
  8230. if err != nil {
  8231. logging.Error("PostRJSBData2 err: ", err)
  8232. msg := geterrmsg(err.Error())
  8233. appG.Response(http.StatusOK, e.ERROR, msg)
  8234. return
  8235. }
  8236. s_params = make([]interface{}, 0)
  8237. paramslist = strings.Split(p3, ",")
  8238. if len(paramslist) > 0 && p3 != "" {
  8239. for _, value := range paramslist {
  8240. if value == "pastureid" {
  8241. s_params = append(s_params, pastureId)
  8242. } else {
  8243. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8244. }
  8245. }
  8246. }
  8247. _, err = tx.SQL(sql3, s_params...).Execute()
  8248. if err != nil {
  8249. logging.Error("PostRJSBData3 err: ", err)
  8250. msg := geterrmsg(err.Error())
  8251. appG.Response(http.StatusOK, e.ERROR, msg)
  8252. return
  8253. }
  8254. }
  8255. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8256. }
  8257. func FpdBatchEdit(c *gin.Context) {
  8258. appG := app.Gin{C: c}
  8259. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8260. fsions := gofasion.NewFasion(string(dataByte))
  8261. barList := fsions.Get("barList").Array()
  8262. pastureid := fsions.Get("pastureId").ValueStr()
  8263. tx := restful.Engine.NewSession()
  8264. defer tx.Close()
  8265. 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
  8266. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8267. if err != nil {
  8268. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8269. return
  8270. }
  8271. for _, barFsions := range barList {
  8272. dataexcel := make(map[string]interface{}, 0)
  8273. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8274. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8275. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8276. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8277. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8278. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8279. continue
  8280. }
  8281. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8282. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8283. // if err != nil {
  8284. // logs.Error(err)
  8285. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8286. // return
  8287. // }
  8288. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8289. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8290. // if err != nil {
  8291. // logs.Error(err)
  8292. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8293. // return
  8294. // }
  8295. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8296. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8297. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8298. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8299. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8300. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8301. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8302. if err != nil {
  8303. logs.Error(err)
  8304. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8305. return
  8306. }
  8307. if !ftexist {
  8308. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8309. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8310. if err != nil {
  8311. logs.Error(err)
  8312. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8313. return
  8314. }
  8315. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8316. if err != nil {
  8317. logs.Error(err)
  8318. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8319. return
  8320. }
  8321. }
  8322. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8323. if err != nil {
  8324. logs.Error(err)
  8325. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8326. return
  8327. }
  8328. if !exist {
  8329. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8330. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8331. if err != nil {
  8332. logs.Error(err)
  8333. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8334. return
  8335. }
  8336. }
  8337. var feedpargs []interface{}
  8338. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8339. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8340. if _, ok := dataexcel["ftname"]; ok {
  8341. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8342. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8343. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8344. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8345. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8346. } else {
  8347. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8348. }
  8349. if _, ok := dataexcel["ptsfname"]; ok {
  8350. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8351. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8352. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8353. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8354. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8355. } else {
  8356. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8357. }
  8358. upFeedpSql += " where barname = ? and pastureid = ? "
  8359. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8360. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8361. if err != nil {
  8362. logs.Error(err)
  8363. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8364. return
  8365. }
  8366. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8367. if err != nil {
  8368. logs.Error(err)
  8369. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8370. return
  8371. }
  8372. if !exist1 {
  8373. _, 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) `,
  8374. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8375. if err != nil {
  8376. logs.Error(err)
  8377. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8378. return
  8379. }
  8380. }
  8381. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8382. if err != nil {
  8383. logs.Error(err)
  8384. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8385. return
  8386. }
  8387. if !exist2 {
  8388. _, 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) `,
  8389. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8390. if err != nil {
  8391. logs.Error(err)
  8392. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8393. return
  8394. }
  8395. }
  8396. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8397. if err != nil {
  8398. logs.Error(err)
  8399. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8400. return
  8401. }
  8402. if !exist3 {
  8403. _, 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) `,
  8404. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8405. if err != nil {
  8406. logs.Error(err)
  8407. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8408. return
  8409. }
  8410. }
  8411. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8412. if err != nil {
  8413. logs.Error(err)
  8414. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8415. return
  8416. }
  8417. if !exist4 {
  8418. _, 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) `,
  8419. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8420. if err != nil {
  8421. logs.Error(err)
  8422. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8423. return
  8424. }
  8425. }
  8426. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8427. if err != nil {
  8428. logs.Error(err)
  8429. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8430. return
  8431. }
  8432. if !exist5 {
  8433. _, 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) `,
  8434. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8435. if err != nil {
  8436. logs.Error(err)
  8437. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8438. return
  8439. }
  8440. }
  8441. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8442. if err != nil {
  8443. logs.Error(err)
  8444. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8445. return
  8446. }
  8447. if !exist6 {
  8448. _, 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) `,
  8449. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8450. if err != nil {
  8451. logs.Error(err)
  8452. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8453. return
  8454. }
  8455. }
  8456. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8457. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8458. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8459. and pastureid = ? and times = ?`
  8460. var fpdargs1 []interface{}
  8461. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8462. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8463. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8464. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8465. if err != nil {
  8466. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8467. return
  8468. }
  8469. var fpdargs2 []interface{}
  8470. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8471. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8472. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8473. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8474. if err != nil {
  8475. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8476. return
  8477. }
  8478. var fpdargs3 []interface{}
  8479. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8480. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8481. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8482. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8483. if err != nil {
  8484. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8485. return
  8486. }
  8487. var fpdargs4 []interface{}
  8488. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8489. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8490. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8491. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8492. if err != nil {
  8493. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8494. return
  8495. }
  8496. var fpdargs5 []interface{}
  8497. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8498. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8499. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8500. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8501. if err != nil {
  8502. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8503. return
  8504. }
  8505. var fpdargs6 []interface{}
  8506. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8507. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8508. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8509. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8510. if err != nil {
  8511. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8512. return
  8513. }
  8514. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8515. 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()
  8516. if err != nil {
  8517. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8518. return
  8519. }
  8520. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8521. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8522. upFpdetailList := make([]*upFpdetail, 0)
  8523. for _, newfpd := range newList {
  8524. for _, oldfpd := range oldFpdList {
  8525. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8526. var oldweight, newweight float64
  8527. if oldfpd["weight"] != nil {
  8528. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8529. }
  8530. if newfpd["weight"] != nil {
  8531. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8532. }
  8533. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8534. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8535. Old: oldweight,
  8536. New: newweight,
  8537. Times: newfpd["times"].(int64),
  8538. Ptid: newfpd["ptid"].(int64),
  8539. Fweight: fweight,
  8540. Id: oldfpd["id"].(int64),
  8541. })
  8542. break
  8543. }
  8544. }
  8545. }
  8546. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8547. }
  8548. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8549. }
  8550. func UdBarSync(c *gin.Context) {
  8551. appG := app.Gin{C: c}
  8552. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8553. fsions := gofasion.NewFasion(string(dataByte))
  8554. pastureid := fsions.Get("pastureId").ValueStr()
  8555. tx := restful.Engine.NewSession()
  8556. defer tx.Close()
  8557. pastureinfo := new(udPastureInfo)
  8558. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8559. if err != nil {
  8560. logs.Error(err)
  8561. return
  8562. }
  8563. // gm.UdBarSync(pastureid, pastureinfo.Werks)
  8564. jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8565. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8566. }
  8567. func UdFeedSync(c *gin.Context) {
  8568. appG := app.Gin{C: c}
  8569. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8570. fsions := gofasion.NewFasion(string(dataByte))
  8571. pastureid := fsions.Get("pastureId").ValueStr()
  8572. tx := restful.Engine.NewSession()
  8573. defer tx.Close()
  8574. pastureinfo := new(udPastureInfo)
  8575. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8576. if err != nil {
  8577. logs.Error(err)
  8578. return
  8579. }
  8580. // gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8581. jpud.UdFeedSync(pastureid, pastureinfo.Werks)
  8582. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8583. }
  8584. func UdFeedtempletPush(c *gin.Context) {
  8585. appG := app.Gin{C: c}
  8586. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8587. fsions := gofasion.NewFasion(string(dataByte))
  8588. pastureid := fsions.Get("pastureId").ValueStr()
  8589. date := fsions.Get("date").ValueStr()
  8590. tx := restful.Engine.NewSession()
  8591. defer tx.Close()
  8592. pastureinfo := new(udPastureInfo)
  8593. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8594. if err != nil {
  8595. logs.Error(err)
  8596. return
  8597. }
  8598. // gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8599. jpud.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8600. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8601. }
  8602. func UdUtirPush(c *gin.Context) {
  8603. appG := app.Gin{C: c}
  8604. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8605. fsions := gofasion.NewFasion(string(dataByte))
  8606. pastureid := fsions.Get("pastureId").ValueStr()
  8607. date := fsions.Get("date").ValueStr()
  8608. tx := restful.Engine.NewSession()
  8609. defer tx.Close()
  8610. pastureinfo := new(udPastureInfo)
  8611. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8612. if err != nil {
  8613. logs.Error(err)
  8614. return
  8615. }
  8616. // gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8617. jpud.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8618. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8619. }
  8620. func UdBarFeedRemainPush(c *gin.Context) {
  8621. appG := app.Gin{C: c}
  8622. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8623. fsions := gofasion.NewFasion(string(dataByte))
  8624. pastureid := fsions.Get("pastureId").ValueStr()
  8625. date := fsions.Get("date").ValueStr()
  8626. tx := restful.Engine.NewSession()
  8627. defer tx.Close()
  8628. pastureinfo := new(udPastureInfo)
  8629. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8630. if err != nil {
  8631. logs.Error(err)
  8632. return
  8633. }
  8634. // gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8635. jpud.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8636. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8637. }
  8638. func UdMaterialIssuePush(c *gin.Context) {
  8639. appG := app.Gin{C: c}
  8640. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8641. fsions := gofasion.NewFasion(string(dataByte))
  8642. pastureid := fsions.Get("pastureId").ValueStr()
  8643. date := fsions.Get("date").ValueStr()
  8644. tx := restful.Engine.NewSession()
  8645. defer tx.Close()
  8646. pastureinfo := new(udPastureInfo)
  8647. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8648. if err != nil {
  8649. logs.Error(err)
  8650. return
  8651. }
  8652. // gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8653. jpud.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8654. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8655. }
  8656. //搅拌
  8657. func YmyUtirPush(c *gin.Context) {
  8658. appG := app.Gin{C: c}
  8659. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8660. fsions := gofasion.NewFasion(string(dataByte))
  8661. pastureid := fsions.Get("pastureId").ValueStr()
  8662. date := fsions.Get("date").ValueStr()
  8663. tx := restful.Engine.NewSession()
  8664. defer tx.Close()
  8665. pastureinfo := new(udPastureInfo)
  8666. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8667. if err != nil {
  8668. logs.Error(err)
  8669. return
  8670. }
  8671. ymy.YmyUtirPush(pastureid, pastureinfo.Werks, date)
  8672. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8673. }
  8674. //撒料
  8675. func YmyMaterialIssuePush(c *gin.Context) {
  8676. appG := app.Gin{C: c}
  8677. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8678. fsions := gofasion.NewFasion(string(dataByte))
  8679. pastureid := fsions.Get("pastureId").ValueStr()
  8680. date := fsions.Get("date").ValueStr()
  8681. tx := restful.Engine.NewSession()
  8682. defer tx.Close()
  8683. pastureinfo := new(udPastureInfo)
  8684. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8685. if err != nil {
  8686. logs.Error(err)
  8687. return
  8688. }
  8689. ymy.YmyMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8690. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8691. }
  8692. func YmyFeedtempletPush(c *gin.Context) {
  8693. appG := app.Gin{C: c}
  8694. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8695. fsions := gofasion.NewFasion(string(dataByte))
  8696. pastureid := fsions.Get("pastureId").ValueStr()
  8697. date := fsions.Get("date").ValueStr()
  8698. tx := restful.Engine.NewSession()
  8699. defer tx.Close()
  8700. pastureinfo := new(udPastureInfo)
  8701. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8702. if err != nil {
  8703. logs.Error(err)
  8704. return
  8705. }
  8706. ymy.YmyFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8707. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8708. }
  8709. //饲料
  8710. func YmySyncFeed(c *gin.Context) {
  8711. appG := app.Gin{C: c}
  8712. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8713. fsions := gofasion.NewFasion(string(dataByte))
  8714. pastureid := fsions.Get("pastureId").ValueStr()
  8715. // date := fsions.Get("date").ValueStr()
  8716. tx := restful.Engine.NewSession()
  8717. defer tx.Close()
  8718. ymy.YmySyncFeed(pastureid)
  8719. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8720. }
  8721. // 栏舍
  8722. func YmySyncBar(c *gin.Context) {
  8723. appG := app.Gin{C: c}
  8724. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8725. fsions := gofasion.NewFasion(string(dataByte))
  8726. pastureid := fsions.Get("pastureId").ValueStr()
  8727. // date := fsions.Get("date").ValueStr()
  8728. tx := restful.Engine.NewSession()
  8729. defer tx.Close()
  8730. pastureinfo := new(udPastureInfo)
  8731. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8732. if err != nil {
  8733. logs.Error(err)
  8734. return
  8735. }
  8736. ymy.YmySyncBar(pastureinfo.Werks, pastureid)
  8737. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8738. }
  8739. func DelFeedTemplet(c *gin.Context) {
  8740. appG := app.Gin{C: c}
  8741. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8742. fsions := gofasion.NewFasion(string(dataByte))
  8743. ftId := fsions.Get("ftId").ValueStr()
  8744. // userId := fsions.Get("userId").ValueStr()
  8745. tx := restful.Engine.NewSession()
  8746. defer tx.Close()
  8747. _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
  8748. if err != nil {
  8749. logs.Error(err)
  8750. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8751. return
  8752. }
  8753. /*
  8754. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8755. if err != nil {
  8756. logs.Error(err)
  8757. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8758. return
  8759. }
  8760. */
  8761. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8762. if err != nil {
  8763. logs.Error(err)
  8764. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8765. return
  8766. }
  8767. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8768. if err != nil {
  8769. logs.Error(err)
  8770. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8771. return
  8772. }
  8773. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8774. if count > 0 {
  8775. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8776. if err != nil {
  8777. logs.Error(err)
  8778. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8779. return
  8780. }
  8781. }
  8782. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8783. if err != nil {
  8784. logs.Error(err)
  8785. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8786. return
  8787. }
  8788. // var barIdStr []string
  8789. // for _, bar := range barIdList {
  8790. // barIdStr = append(barIdStr, bar["barid"])
  8791. // }
  8792. // if len(barIdStr) > 0 {
  8793. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8794. // if err != nil {
  8795. // logs.Error(err)
  8796. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8797. // return
  8798. // }
  8799. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8800. // if err != nil {
  8801. // logs.Error(err)
  8802. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8803. // return
  8804. // }
  8805. // now := time.Now()
  8806. // for _, newFpd := range newFpdDataList {
  8807. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8808. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8809. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8810. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8811. // if err != nil {
  8812. // logs.Error(err)
  8813. // appG.Response(http.StatusOK, e.ERROR, false)
  8814. // return
  8815. // }
  8816. // }
  8817. // for _, newFeedp := range newFeedpList {
  8818. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8819. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8820. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8821. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8822. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8823. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8824. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8825. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8826. // if err != nil {
  8827. // logs.Error(err)
  8828. // appG.Response(http.StatusOK, e.ERROR, false)
  8829. // return
  8830. // }
  8831. // }
  8832. // }
  8833. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8834. }
  8835. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8836. data := fasion["parammaps"].(map[string]interface{})
  8837. plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(0,1,2) ").Count()
  8838. fmt.Println(err)
  8839. plancount1, err := tx.SQL(`SELECT
  8840. count( 1 )
  8841. FROM
  8842. (
  8843. SELECT
  8844. d.id
  8845. FROM
  8846. downloadedplan d
  8847. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  8848. JOIN downloadplandtl1_exec d1e ON d1e.pid = d.id
  8849. JOIN downloadplandtl2 d2 ON d2.pid = d.id
  8850. WHERE
  8851. d.mydate = ?
  8852. AND d.havebutton = 0
  8853. AND lpplantype IN ( 0, 1, 2 )
  8854. AND ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id and dd2.fname = d2.fname) =
  8855. ( 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 )
  8856. GROUP BY
  8857. d.id
  8858. ) d
  8859. `,
  8860. data["startTime"]).Count()
  8861. fmt.Println(err)
  8862. if plancount != plancount1 && number < 10 {
  8863. number++
  8864. ExecDataParam(fasion, CommonParamMap, ParamMap, nil, nil, tx)
  8865. checkPlan(tx, fasion, CommonParamMap, ParamMap, number)
  8866. }
  8867. }
  8868. func EditPlanSort(c *gin.Context) {
  8869. appG := app.Gin{C: c}
  8870. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8871. fsions := gofasion.NewFasion(string(dataByte))
  8872. planIdStr := fsions.Get("planId").ValueStr()
  8873. mydate := fsions.Get("mydate").ValueStr()
  8874. sort := fsions.Get("sort").ValueStr()
  8875. tx := restful.Engine.NewSession()
  8876. defer tx.Close()
  8877. tx.Begin()
  8878. type downloadedplan struct {
  8879. Id int64 `xorm:"id"`
  8880. Sort int `xorm:"sort"`
  8881. Pid int64 `xorm:"pid"`
  8882. }
  8883. planInfo := new(downloadedplan)
  8884. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  8885. if err != nil {
  8886. logs.Error(err)
  8887. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8888. tx.Rollback()
  8889. return
  8890. }
  8891. sort1, _ := strconv.Atoi(sort)
  8892. if sort1 == planInfo.Sort {
  8893. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  8894. tx.Rollback()
  8895. return
  8896. }
  8897. 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()
  8898. if err != nil {
  8899. logs.Error(err)
  8900. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8901. tx.Rollback()
  8902. return
  8903. }
  8904. if count1 == 0 {
  8905. tx.Rollback()
  8906. logs.Error(err)
  8907. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  8908. return
  8909. }
  8910. 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()
  8911. if err != nil {
  8912. logs.Error(err)
  8913. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8914. tx.Rollback()
  8915. return
  8916. }
  8917. if count > 0 {
  8918. tx.Rollback()
  8919. logs.Error(err)
  8920. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  8921. return
  8922. }
  8923. if planInfo.Sort > sort1 {
  8924. 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()
  8925. if err != nil {
  8926. logs.Error(err)
  8927. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8928. tx.Rollback()
  8929. return
  8930. }
  8931. var minSort, pidCount int
  8932. for _, sort := range minSortList {
  8933. minSort, _ = strconv.Atoi(sort["sort"])
  8934. }
  8935. planList := make([]*downloadedplan, 0)
  8936. 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)
  8937. if err != nil {
  8938. logs.Error(err)
  8939. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8940. tx.Rollback()
  8941. return
  8942. }
  8943. planPid := planInfo.Pid
  8944. planList1 := make([]*downloadedplan, 0)
  8945. planList2 := make([]*downloadedplan, 0)
  8946. for _, plan := range planList {
  8947. if plan.Pid == planPid {
  8948. pidCount++
  8949. planList1 = append(planList1, plan)
  8950. } else {
  8951. planList2 = append(planList2, plan)
  8952. }
  8953. }
  8954. planList1 = append(planList1, planList2...)
  8955. for i, plan := range planList1 {
  8956. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  8957. if err != nil {
  8958. logs.Error(err)
  8959. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8960. tx.Rollback()
  8961. return
  8962. }
  8963. }
  8964. } else {
  8965. 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()
  8966. if err != nil {
  8967. logs.Error(err)
  8968. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8969. tx.Rollback()
  8970. return
  8971. }
  8972. var maxSort int
  8973. for _, sort := range maxSortList {
  8974. maxSort, _ = strconv.Atoi(sort["sort"])
  8975. }
  8976. planList := make([]*downloadedplan, 0)
  8977. 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)
  8978. if err != nil {
  8979. logs.Error(err)
  8980. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8981. tx.Rollback()
  8982. return
  8983. }
  8984. planPid := planInfo.Pid
  8985. planList1 := make([]*downloadedplan, 0)
  8986. planList2 := make([]*downloadedplan, 0)
  8987. for _, plan := range planList {
  8988. if plan.Pid == planPid {
  8989. // pidCount++
  8990. planList1 = append(planList1, plan)
  8991. } else {
  8992. planList2 = append(planList2, plan)
  8993. }
  8994. }
  8995. planList2 = append(planList2, planList1...)
  8996. for i, plan := range planList2 {
  8997. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  8998. if err != nil {
  8999. logs.Error(err)
  9000. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9001. tx.Rollback()
  9002. return
  9003. }
  9004. }
  9005. }
  9006. err = tx.Commit()
  9007. if err != nil {
  9008. logs.Error(err)
  9009. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9010. tx.Rollback()
  9011. return
  9012. }
  9013. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9014. }
  9015. func EditDownloadedplanArtificial(c *gin.Context) {
  9016. appG := app.Gin{C: c}
  9017. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9018. fsions := gofasion.NewFasion(string(dataByte))
  9019. planIdStr := fsions.Get("planId").ValueStr()
  9020. tx := restful.Engine.NewSession()
  9021. defer tx.Close()
  9022. tx.Begin()
  9023. planIdList := strings.Split(planIdStr, ",")
  9024. for _, planId := range planIdList {
  9025. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? `, planId)
  9026. if err != nil {
  9027. logs.Error(err)
  9028. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9029. tx.Rollback()
  9030. return
  9031. }
  9032. }
  9033. err := tx.Commit()
  9034. if err != nil {
  9035. logs.Error(err)
  9036. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9037. tx.Rollback()
  9038. return
  9039. }
  9040. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9041. }
  9042. type PlanRFID struct {
  9043. RFID string `json:"RFID"`
  9044. Lweight string `json:"lweight"`
  9045. Gear string `json:"gear"`
  9046. Speed string `json:"speed"`
  9047. }
  9048. func GetPlanRFID(c *gin.Context) {
  9049. appG := app.Gin{C: c}
  9050. RFIDStr := c.Query("RFID")
  9051. planRFIDList := make([]*PlanRFID, 0)
  9052. planRFIDList = append(planRFIDList, &PlanRFID{
  9053. RFID: RFIDStr,
  9054. Lweight: "1411.1",
  9055. Gear: "1",
  9056. Speed: "10",
  9057. })
  9058. planRFIDList = append(planRFIDList, &PlanRFID{
  9059. RFID: RFIDStr,
  9060. Lweight: "1322.1",
  9061. Gear: "1",
  9062. Speed: "10",
  9063. })
  9064. planRFIDList = append(planRFIDList, &PlanRFID{
  9065. RFID: RFIDStr,
  9066. Lweight: "1904.1",
  9067. Gear: "1",
  9068. Speed: "10",
  9069. })
  9070. planRFIDList = append(planRFIDList, &PlanRFID{
  9071. RFID: RFIDStr,
  9072. Lweight: "1870.1",
  9073. Gear: "1",
  9074. Speed: "10",
  9075. })
  9076. planRFIDList = append(planRFIDList, &PlanRFID{
  9077. RFID: RFIDStr,
  9078. Lweight: "2041.1",
  9079. Gear: "1",
  9080. Speed: "10",
  9081. })
  9082. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  9083. }
  9084. type tmrEquipmentMuster struct {
  9085. A string
  9086. N string
  9087. }
  9088. func GetTmrEquipmentMuster(c *gin.Context) {
  9089. appG := app.Gin{C: c}
  9090. id := c.Query("id")
  9091. tx := restful.Engine.NewSession()
  9092. defer tx.Close()
  9093. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  9094. if err != nil {
  9095. logs.Error(err)
  9096. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9097. return
  9098. }
  9099. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  9100. for _, data := range dataList {
  9101. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  9102. for _, g := range tmrEquipmentMusterList {
  9103. a, _ := strconv.ParseFloat(g.A, 64)
  9104. n, _ := strconv.ParseFloat(g.N, 64)
  9105. a1, n1 := ddmmtoddd(a, n)
  9106. g.A = fmt.Sprintf("%f", n1)
  9107. g.N = fmt.Sprintf("%f", a1)
  9108. }
  9109. }
  9110. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  9111. }
  9112. func ddmmtoddd(lng, lat float64) (float64, float64) {
  9113. lngDegree := fmt.Sprintf("%f", lng/100)
  9114. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  9115. lngDegreeInt := int(lngDegreefloat * 1000000)
  9116. dd := lngDegreeInt / 100 * 100 / 60
  9117. fmt.Println(dd)
  9118. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  9119. latDegree := fmt.Sprintf("%f", lat/100)
  9120. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  9121. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  9122. latDegreeInt := int(latDegreefloat * 1000000)
  9123. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  9124. a, _ := strconv.ParseFloat(lngStr, 64)
  9125. b, _ := strconv.ParseFloat(latStr, 64)
  9126. return coordtransform.WGS84toGCJ02(b, a)
  9127. }
  9128. func EditDownloadedplanExecWeight(c *gin.Context) {
  9129. appG := app.Gin{C: c}
  9130. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9131. fsions := gofasion.NewFasion(string(dataByte))
  9132. pid := fsions.Get("pid").ValueStr()
  9133. sort := fsions.Get("sort").ValueStr()
  9134. weight := fsions.Get("weight").ValueStr()
  9135. userId := fsions.Get("userId").ValueStr()
  9136. tx := restful.Engine.NewSession()
  9137. defer tx.Close()
  9138. tx.Begin()
  9139. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  9140. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  9141. pid, sort, pid, sort, weight, userId)
  9142. if err != nil {
  9143. logs.Error(err)
  9144. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9145. tx.Rollback()
  9146. return
  9147. }
  9148. _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9149. if err != nil {
  9150. logs.Error(err)
  9151. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9152. tx.Rollback()
  9153. return
  9154. }
  9155. _, 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)
  9156. if err != nil {
  9157. logs.Error(err)
  9158. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9159. tx.Rollback()
  9160. return
  9161. }
  9162. err = tx.Commit()
  9163. if err != nil {
  9164. logs.Error(err)
  9165. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9166. tx.Rollback()
  9167. return
  9168. }
  9169. appG.Response(http.StatusOK, e.SUCCESS, true)
  9170. }
  9171. func EditDownloadplandtl2Weight(c *gin.Context) {
  9172. appG := app.Gin{C: c}
  9173. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9174. fsions := gofasion.NewFasion(string(dataByte))
  9175. pid := fsions.Get("pid").ValueStr()
  9176. sort := fsions.Get("sort").ValueStr()
  9177. weight := fsions.Get("weight").ValueStr()
  9178. userId := fsions.Get("userId").ValueStr()
  9179. tx := restful.Engine.NewSession()
  9180. defer tx.Close()
  9181. tx.Begin()
  9182. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9183. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9184. pid, sort, pid, sort, weight, userId)
  9185. if err != nil {
  9186. logs.Error(err)
  9187. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9188. tx.Rollback()
  9189. return
  9190. }
  9191. _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9192. if err != nil {
  9193. logs.Error(err)
  9194. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9195. tx.Rollback()
  9196. return
  9197. }
  9198. err = tx.Commit()
  9199. if err != nil {
  9200. logs.Error(err)
  9201. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9202. tx.Rollback()
  9203. return
  9204. }
  9205. appG.Response(http.StatusOK, e.SUCCESS, true)
  9206. }
  9207. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9208. params := fasion.Get("parammaps")
  9209. surplus := params.Get("surplus").ValueStr()
  9210. surplusId := params.Get("surplusId").ValueStr()
  9211. tx := restful.Engine.NewSession()
  9212. defer tx.Close()
  9213. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9214. if surplusId != "0" {
  9215. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9216. if err != nil {
  9217. log.Println("PostDataByName-error-1: ", err)
  9218. return errors.New("配方修改失败!")
  9219. }
  9220. type ftdetail struct {
  9221. Id string
  9222. Fname string
  9223. Sort int64
  9224. }
  9225. ftList := make([]*ftdetail, 0)
  9226. for _, data := range dataList {
  9227. ft := new(ftdetail)
  9228. ft.Fname = data["fname"]
  9229. ft.Id = data["id"]
  9230. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9231. if err != nil {
  9232. log.Println("PostDataByName-error-2: ", err)
  9233. return err
  9234. }
  9235. ft.Sort = sort
  9236. ftList = append(ftList, ft)
  9237. }
  9238. if surplus == "日粮" {
  9239. for _, ft := range ftList {
  9240. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9241. }
  9242. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9243. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9244. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9245. fmt.Println(err)
  9246. } else {
  9247. var sort int64
  9248. for _, ft := range ftList {
  9249. if ft.Fname == surplus {
  9250. sort = ft.Sort
  9251. break
  9252. }
  9253. }
  9254. if sort == 0 {
  9255. for _, ft := range ftList {
  9256. ft.Sort = ft.Sort + 1
  9257. }
  9258. } else {
  9259. for _, ft := range ftList {
  9260. if ft.Sort >= sort {
  9261. ft.Sort = ft.Sort + 1
  9262. }
  9263. }
  9264. }
  9265. for _, ft := range ftList {
  9266. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9267. }
  9268. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9269. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9270. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9271. if err != nil {
  9272. log.Println("PostDataByName-error-1: ", err)
  9273. fmt.Println(err)
  9274. return errors.New("配方修改失败!")
  9275. }
  9276. }
  9277. }
  9278. return nil
  9279. }
  9280. func FeedSurplus(fasion *gofasion.Fasion) {
  9281. tx := restful.Engine.NewSession()
  9282. defer tx.Close()
  9283. params := fasion.Get("parammaps")
  9284. feedId := params.Get("id").ValueStr()
  9285. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9286. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9287. }
  9288. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9289. // params := fasion.Get("parammaps")
  9290. // surplus := params.Get("surplus").ValueStr()
  9291. // surplusId := params.Get("surplusId").ValueStr()
  9292. tx := restful.Engine.NewSession()
  9293. defer tx.Close()
  9294. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9295. if surplusId != "0" {
  9296. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9297. if err != nil {
  9298. log.Println("PostDataByName-error-1: ", err)
  9299. return errors.New("配方修改失败!")
  9300. }
  9301. type ftdetail struct {
  9302. Id string
  9303. Fname string
  9304. Sort int64
  9305. }
  9306. ftList := make([]*ftdetail, 0)
  9307. for _, data := range dataList {
  9308. ft := new(ftdetail)
  9309. ft.Fname = data["fname"]
  9310. ft.Id = data["id"]
  9311. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9312. if err != nil {
  9313. log.Println("PostDataByName-error-2: ", err)
  9314. return err
  9315. }
  9316. ft.Sort = sort
  9317. ftList = append(ftList, ft)
  9318. }
  9319. if surplus == "日粮" {
  9320. for _, ft := range ftList {
  9321. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9322. }
  9323. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9324. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9325. pastureId, id, surplusId, surplusId, surplusId)
  9326. fmt.Println(err)
  9327. } else {
  9328. var sort int64
  9329. for _, ft := range ftList {
  9330. if ft.Fname == surplus {
  9331. sort = ft.Sort
  9332. break
  9333. }
  9334. }
  9335. if sort == 0 {
  9336. for _, ft := range ftList {
  9337. ft.Sort = ft.Sort + 1
  9338. }
  9339. } else {
  9340. for _, ft := range ftList {
  9341. if ft.Sort >= sort {
  9342. ft.Sort = ft.Sort + 1
  9343. }
  9344. }
  9345. }
  9346. for _, ft := range ftList {
  9347. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9348. }
  9349. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9350. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9351. id, surplusId, surplusId, sort, surplusId, pastureId)
  9352. if err != nil {
  9353. log.Println("PostDataByName-error-1: ", err)
  9354. fmt.Println(err)
  9355. return errors.New("配方修改失败!")
  9356. }
  9357. }
  9358. }
  9359. return nil
  9360. }
  9361. func GetLanguageStatus() string {
  9362. tx := restful.Engine.NewSession()
  9363. defer tx.Close()
  9364. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9365. if err != nil {
  9366. log.Println(err)
  9367. return "0"
  9368. }
  9369. return dataList[0]["inforvalue"]
  9370. }
  9371. func EditLanguage(c *gin.Context) {
  9372. appG := app.Gin{C: c}
  9373. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9374. fsions := gofasion.NewFasion(string(dataByte))
  9375. language := fsions.Get("language").ValueStr()
  9376. tx := restful.Engine.NewSession()
  9377. defer tx.Close()
  9378. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9379. if err != nil {
  9380. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9381. return
  9382. }
  9383. if language == "0" {
  9384. _, err := tx.Exec(`delete from dictlist `)
  9385. if err != nil {
  9386. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9387. return
  9388. }
  9389. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9390. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9391. if err != nil {
  9392. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9393. return
  9394. }
  9395. } else {
  9396. _, err := tx.Exec(`delete from dictlist `)
  9397. if err != nil {
  9398. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9399. return
  9400. }
  9401. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9402. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9403. if err != nil {
  9404. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9405. return
  9406. }
  9407. }
  9408. appG.Response(http.StatusOK, e.SUCCESS, true)
  9409. }
  9410. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9411. tx := restful.Engine.NewSession()
  9412. defer tx.Close()
  9413. 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
  9414. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9415. if err != nil {
  9416. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9417. return
  9418. }
  9419. for _, dataexcel := range barList {
  9420. // dataexcel := make(map[string]interface{}, 0)
  9421. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9422. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9423. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9424. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9425. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9426. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9427. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9428. // if err != nil {
  9429. // logs.Error(err)
  9430. // return
  9431. // }
  9432. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9433. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9434. // if err != nil {
  9435. // logs.Error(err)
  9436. // return
  9437. // }
  9438. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9439. continue
  9440. }
  9441. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9442. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9443. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9444. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9445. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9446. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9447. // /*
  9448. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  9449. if err != nil {
  9450. logs.Error(err)
  9451. return
  9452. }
  9453. if !ftexist {
  9454. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  9455. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9456. if err != nil {
  9457. logs.Error(err)
  9458. return
  9459. }
  9460. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9461. if err != nil {
  9462. logs.Error(err)
  9463. return
  9464. }
  9465. }
  9466. // */
  9467. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9468. if err != nil {
  9469. logs.Error(err)
  9470. return
  9471. }
  9472. if !exist {
  9473. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9474. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9475. if err != nil {
  9476. logs.Error(err)
  9477. return
  9478. }
  9479. }
  9480. var feedpargs []interface{}
  9481. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9482. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9483. if _, ok := dataexcel["ftname"]; ok {
  9484. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9485. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9486. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9487. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9488. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9489. } else {
  9490. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9491. }
  9492. if _, ok := dataexcel["ptsfname"]; ok {
  9493. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9494. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9495. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9496. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9497. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9498. } else {
  9499. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9500. }
  9501. upFeedpSql += " where barname = ? and pastureid = ? "
  9502. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9503. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9504. if err != nil {
  9505. logs.Error(err)
  9506. return
  9507. }
  9508. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9509. if err != nil {
  9510. logs.Error(err)
  9511. return
  9512. }
  9513. if !exist1 {
  9514. _, 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) `,
  9515. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9516. if err != nil {
  9517. logs.Error(err)
  9518. return
  9519. }
  9520. }
  9521. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9522. if err != nil {
  9523. logs.Error(err)
  9524. return
  9525. }
  9526. if !exist2 {
  9527. _, 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) `,
  9528. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9529. if err != nil {
  9530. logs.Error(err)
  9531. return
  9532. }
  9533. }
  9534. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9535. if err != nil {
  9536. logs.Error(err)
  9537. return
  9538. }
  9539. if !exist3 {
  9540. _, 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) `,
  9541. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9542. if err != nil {
  9543. logs.Error(err)
  9544. return
  9545. }
  9546. }
  9547. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9548. if err != nil {
  9549. logs.Error(err)
  9550. return
  9551. }
  9552. if !exist4 {
  9553. _, 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) `,
  9554. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9555. if err != nil {
  9556. logs.Error(err)
  9557. return
  9558. }
  9559. }
  9560. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9561. if err != nil {
  9562. logs.Error(err)
  9563. return
  9564. }
  9565. if !exist5 {
  9566. _, 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) `,
  9567. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9568. if err != nil {
  9569. logs.Error(err)
  9570. return
  9571. }
  9572. }
  9573. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9574. if err != nil {
  9575. logs.Error(err)
  9576. return
  9577. }
  9578. if !exist6 {
  9579. _, 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) `,
  9580. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9581. if err != nil {
  9582. logs.Error(err)
  9583. return
  9584. }
  9585. }
  9586. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9587. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9588. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9589. and pastureid = ? and times = ?`
  9590. var fpdargs1 []interface{}
  9591. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9592. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9593. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9594. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9595. if err != nil {
  9596. fmt.Println(err)
  9597. return
  9598. }
  9599. var fpdargs2 []interface{}
  9600. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9601. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9602. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9603. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9604. if err != nil {
  9605. fmt.Println(err)
  9606. return
  9607. }
  9608. var fpdargs3 []interface{}
  9609. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9610. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9611. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9612. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9613. if err != nil {
  9614. fmt.Println(err)
  9615. return
  9616. }
  9617. var fpdargs4 []interface{}
  9618. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9619. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9620. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9621. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9622. if err != nil {
  9623. fmt.Println(err)
  9624. return
  9625. }
  9626. var fpdargs5 []interface{}
  9627. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9628. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9629. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9630. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9631. if err != nil {
  9632. fmt.Println(err)
  9633. return
  9634. }
  9635. var fpdargs6 []interface{}
  9636. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  9637. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9638. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  9639. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  9640. if err != nil {
  9641. fmt.Println(err)
  9642. return
  9643. }
  9644. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  9645. 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()
  9646. if err != nil {
  9647. return
  9648. }
  9649. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9650. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9651. upFpdetailList := make([]*upFpdetail, 0)
  9652. for _, newfpd := range newList {
  9653. for _, oldfpd := range oldFpdList {
  9654. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  9655. var oldweight, newweight float64
  9656. if oldfpd["weight"] != nil {
  9657. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  9658. }
  9659. if newfpd["weight"] != nil {
  9660. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  9661. }
  9662. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  9663. upFpdetailList = append(upFpdetailList, &upFpdetail{
  9664. Old: oldweight,
  9665. New: newweight,
  9666. Times: newfpd["times"].(int64),
  9667. Ptid: newfpd["ptid"].(int64),
  9668. Fweight: fweight,
  9669. Id: oldfpd["id"].(int64),
  9670. })
  9671. break
  9672. }
  9673. }
  9674. }
  9675. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  9676. }
  9677. }
  9678. func AddXxwFtdetail(c *gin.Context) {
  9679. appG := app.Gin{C: c}
  9680. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  9681. c.Bind(&xxwFtdetailList)
  9682. tx := restful.Engine.NewSession()
  9683. defer tx.Close()
  9684. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  9685. if err != nil {
  9686. logs.Error(err)
  9687. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9688. }
  9689. _, err = tx.Insert(xxwFtdetailList)
  9690. if err != nil {
  9691. logs.Error(err)
  9692. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9693. }
  9694. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  9695. appG.Response(http.StatusOK, e.SUCCESS, true)
  9696. }
  9697. func AddXxwFeedtemplet(c *gin.Context) {
  9698. appG := app.Gin{C: c}
  9699. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  9700. c.Bind(&xxwFeedtempletList)
  9701. tx := restful.Engine.NewSession()
  9702. defer tx.Close()
  9703. pastureinfo := new(udPastureInfo)
  9704. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  9705. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  9706. if err != nil {
  9707. logs.Error(err)
  9708. return
  9709. }
  9710. for _, ft := range xxwFeedtempletList {
  9711. ids, err := setting.SnowIds.NextId()
  9712. if err != nil {
  9713. ids = time.Now().UnixNano()
  9714. logging.Info("create SnowIds err", err)
  9715. }
  9716. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  9717. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  9718. ft.RecipeobjName, ft.RecipeobjName)
  9719. if err != nil {
  9720. logs.Error(err)
  9721. return
  9722. }
  9723. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  9724. _, 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')),
  9725. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  9726. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  9727. if err != nil {
  9728. logs.Error(err)
  9729. return
  9730. }
  9731. }
  9732. appG.Response(http.StatusOK, e.SUCCESS, true)
  9733. }
  9734. func ProcessExcel(c *gin.Context) {
  9735. appG := app.Gin{C: c}
  9736. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9737. fasion := gofasion.NewFasion(string(dataByte))
  9738. params := fasion.Get("parammaps")
  9739. pastureid := params.Get("pastureid").ValueStr()
  9740. startTime := params.Get("startTime").ValueStr()
  9741. stopTime := params.Get("stopTime").ValueStr()
  9742. iscompleted := params.Get("iscompleted").ValueStr()
  9743. lpplantype := params.Get("lpplantype").ValueStr()
  9744. error := params.Get("error").ValueStr()
  9745. hlwc1 := params.Get("hlwc1").ValueStr()
  9746. hlwc2 := params.Get("hlwc2").ValueStr()
  9747. slwc1 := params.Get("slwc1").ValueStr()
  9748. slwc2 := params.Get("slwc2").ValueStr()
  9749. hlzq1 := params.Get("hlzq1").ValueStr()
  9750. hlzq2 := params.Get("hlzq2").ValueStr()
  9751. slzq1 := params.Get("slzq1").ValueStr()
  9752. slzq2 := params.Get("slzq2").ValueStr()
  9753. fclassid := params.Get("fclassid").ValueStr()
  9754. minproesstime := params.Get("minproesstime").ValueStr()
  9755. maxproesstime := params.Get("maxproesstime").ValueStr()
  9756. tx := restful.Engine.NewSession()
  9757. defer tx.Close()
  9758. planList, err := tx.SQL(`SELECT
  9759. 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
  9760. FROM downloadedplan d
  9761. join pasture p on p.pastureid = d.pastureid
  9762. WHERE d.pastureid= ? and d.intime IS NOT NULL
  9763. AND mydate >= ? AND mydate <= ?
  9764. AND (iscompleted=? or ?='')
  9765. AND (lpplantype = ? or ? = '')
  9766. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  9767. 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
  9768. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  9769. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  9770. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  9771. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  9772. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  9773. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  9774. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  9775. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  9776. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  9777. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  9778. 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,
  9779. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  9780. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  9781. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  9782. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9783. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  9784. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  9785. or (?= '' and ? = '' ))
  9786. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  9787. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  9788. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  9789. maxproesstime, minproesstime, maxproesstime).QueryString()
  9790. if err != nil {
  9791. logs.Error(err)
  9792. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9793. return
  9794. }
  9795. planExecList, err := tx.SQL(`SELECT
  9796. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9797. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  9798. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  9799. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  9800. ) proesstime,
  9801. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9802. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  9803. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  9804. sumproesstime, d1.pid,
  9805. d1.sort,
  9806. d1.fname,
  9807. d1.lweight,
  9808. d1.actualweightminus,
  9809. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  9810. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  9811. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  9812. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  9813. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  9814. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  9815. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  9816. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  9817. d1.begintime stoptime,
  9818. d1.lastactualweight,
  9819. d1.actualweight,
  9820. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  9821. case d1.buttontype
  9822. when 1 then '自动'
  9823. when 2 then '手动'
  9824. when 3 then '手动'
  9825. end,
  9826. case d1.buttontype
  9827. when 1 then 'Automatic'
  9828. when 2 then 'Manual'
  9829. when 3 then 'Manual'
  9830. end
  9831. ) buttontype
  9832. FROM
  9833. downloadplandtl1_exec d1
  9834. WHERE d1.date between ? and ?
  9835. ORDER BY sort
  9836. `, startTime, stopTime).QueryString()
  9837. if err != nil {
  9838. logs.Error(err)
  9839. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9840. return
  9841. }
  9842. planExec2, err := tx.SQL(`SELECT
  9843. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  9844. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  9845. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9846. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  9847. ) proesstime,
  9848. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  9849. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9850. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  9851. d1.sort,
  9852. d1.fname,
  9853. d1.lweight,
  9854. d1.actualweightminus,
  9855. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  9856. ABS(d1.lweight- d1.actualweightminus) diff,
  9857. 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,
  9858. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  9859. d1.begintime stoptime,
  9860. d1.lastactualweight,
  9861. d1.actualweight,d1.pid
  9862. FROM
  9863. downloadplandtl2 d1
  9864. WHERE d1.date between ? and ?
  9865. ORDER BY sort`, startTime, stopTime).QueryString()
  9866. if err != nil {
  9867. logs.Error(err)
  9868. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9869. return
  9870. }
  9871. // 创建一个新的 Excel 文件
  9872. f := excelizexuri.NewFile()
  9873. // 创建工作表名称
  9874. sheetName := "Sheet1"
  9875. border := []excelizexuri.Border{
  9876. {Type: "left", Color: "000000", Style: 1},
  9877. {Type: "right", Color: "000000", Style: 1},
  9878. {Type: "top", Color: "000000", Style: 1},
  9879. {Type: "bottom", Color: "000000", Style: 1},
  9880. }
  9881. // 创建新的样式
  9882. style := &excelizexuri.Style{
  9883. // Border: border,
  9884. Alignment: &excelizexuri.Alignment{
  9885. Vertical: "center",
  9886. Horizontal: "center",
  9887. ShrinkToFit: true,
  9888. WrapText: true,
  9889. },
  9890. }
  9891. styleTitle := &excelizexuri.Style{
  9892. // Border: border,
  9893. Font: &excelizexuri.Font{
  9894. Bold: true, // 加粗
  9895. Size: 24, // 字体大小
  9896. // Name: "宋体", // 字体名称
  9897. // WrapText :true,
  9898. Color: "000000", // 字体颜色(黑色)
  9899. },
  9900. Alignment: &excelizexuri.Alignment{
  9901. Vertical: "center", // 垂直居中
  9902. Horizontal: "center", // 水平居中
  9903. ShrinkToFit: true,
  9904. WrapText: true,
  9905. },
  9906. }
  9907. // 创建样式 ID
  9908. styleTitleId, err := f.NewStyle(styleTitle)
  9909. if err != nil {
  9910. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  9911. return
  9912. }
  9913. // 创建样式 ID
  9914. styleID, err := f.NewStyle(style)
  9915. if err != nil {
  9916. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  9917. return
  9918. }
  9919. // 合并单元格并设置内容
  9920. f.MergeCell(sheetName, "A1", "K1")
  9921. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  9922. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  9923. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  9924. planExecMap := make(map[string][]map[string]string, 0)
  9925. for _, planExec := range planExecList {
  9926. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  9927. }
  9928. plan2Map := make(map[string][]map[string]string, 0)
  9929. for _, plan2 := range planExec2 {
  9930. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  9931. }
  9932. num := 2
  9933. var notBorder []int
  9934. for _, plan := range planList {
  9935. fmt.Println(plan)
  9936. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  9937. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  9938. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  9939. for i, header := range headers {
  9940. // 从 A2 开始
  9941. if header == "开始日期" {
  9942. cell := "%" + fmt.Sprintf("c%d", num)
  9943. cell = fmt.Sprintf(cell, 'A'+i+1)
  9944. f.SetCellValue(sheetName, cell, header)
  9945. f.SetCellStyle(sheetName, cell, cell, styleID)
  9946. continue
  9947. }
  9948. cell := "%" + fmt.Sprintf("c%d", num)
  9949. cell = fmt.Sprintf(cell, 'A'+i)
  9950. f.SetCellValue(sheetName, cell, header)
  9951. f.SetCellStyle(sheetName, cell, cell, styleID)
  9952. }
  9953. num += 1
  9954. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  9955. cell := "%" + fmt.Sprintf("c%d", num)
  9956. cell = fmt.Sprintf(cell, 'A'+0)
  9957. f.SetCellValue(sheetName, cell, plan["pastureName"])
  9958. f.SetCellStyle(sheetName, cell, cell, styleID)
  9959. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  9960. cell = "%" + fmt.Sprintf("c%d", num)
  9961. cell = fmt.Sprintf(cell, 'A'+1)
  9962. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  9963. f.SetCellStyle(sheetName, cell, cell, styleID)
  9964. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  9965. cell = "%" + fmt.Sprintf("c%d", num)
  9966. cell = fmt.Sprintf(cell, 'A'+2)
  9967. f.SetCellValue(sheetName, cell, plan["projname"])
  9968. f.SetCellStyle(sheetName, cell, cell, styleID)
  9969. cell = "%" + fmt.Sprintf("c%d", num)
  9970. cell = fmt.Sprintf(cell, 'A'+3)
  9971. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  9972. f.SetCellValue(sheetName, cell, plan["mydate"])
  9973. f.SetCellStyle(sheetName, cell, cell, styleID)
  9974. cell = "%" + fmt.Sprintf("c%d", num)
  9975. cell = fmt.Sprintf(cell, 'A'+6)
  9976. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  9977. f.SetCellValue(sheetName, cell, plan["intime"])
  9978. f.SetCellStyle(sheetName, cell, cell, styleID)
  9979. num += 1
  9980. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  9981. for i, header := range headers1 {
  9982. cell = "%" + fmt.Sprintf("c%d", num)
  9983. cell = fmt.Sprintf(cell, 'C'+i)
  9984. f.SetCellValue(sheetName, cell, header)
  9985. f.SetCellStyle(sheetName, cell, cell, styleID)
  9986. // maxWidth := len(header)
  9987. // colName := string('C' + i)
  9988. // f.SetColWidth(sheetName, colName, colName, 20)
  9989. f.SetColWidth(sheetName, header, header, 40)
  9990. }
  9991. num += 1
  9992. for _, planExec := range planExecMap[plan["id"]] {
  9993. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  9994. sort, _ := strconv.Atoi(planExec["sort"])
  9995. f.SetCellValue(sheetName, cell, sort)
  9996. f.SetCellStyle(sheetName, cell, cell, styleID)
  9997. cell = fmt.Sprintf("D%d", num)
  9998. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  9999. f.SetCellValue(sheetName, cell, lweight)
  10000. f.SetCellStyle(sheetName, cell, cell, styleID)
  10001. cell = fmt.Sprintf("E%d", num)
  10002. if _, ok := planExec["actualweightminus"]; ok {
  10003. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  10004. f.SetCellValue(sheetName, cell, actualweightminus)
  10005. f.SetCellStyle(sheetName, cell, cell, styleID)
  10006. } else {
  10007. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  10008. f.SetCellStyle(sheetName, cell, cell, styleID)
  10009. }
  10010. cell = fmt.Sprintf("F%d", num)
  10011. f.SetCellValue(sheetName, cell, planExec["fname"])
  10012. f.SetCellStyle(sheetName, cell, cell, styleID)
  10013. cell = fmt.Sprintf("G%d", num)
  10014. if _, ok := planExec["diff"]; ok {
  10015. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  10016. f.SetCellValue(sheetName, cell, diff)
  10017. f.SetCellStyle(sheetName, cell, cell, styleID)
  10018. } else {
  10019. f.SetCellValue(sheetName, cell, planExec["diff"])
  10020. f.SetCellStyle(sheetName, cell, cell, styleID)
  10021. }
  10022. cell = fmt.Sprintf("H%d", num)
  10023. if _, ok := planExec["diffRate"]; ok {
  10024. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  10025. f.SetCellValue(sheetName, cell, diffRate)
  10026. f.SetCellStyle(sheetName, cell, cell, styleID)
  10027. } else {
  10028. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  10029. f.SetCellStyle(sheetName, cell, cell, styleID)
  10030. }
  10031. cell = fmt.Sprintf("I%d", num)
  10032. f.SetCellValue(sheetName, cell, planExec["intime"])
  10033. f.SetCellStyle(sheetName, cell, cell, styleID)
  10034. cell = fmt.Sprintf("J%d", num)
  10035. if _, ok := planExec["lastactualweight"]; ok {
  10036. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  10037. f.SetCellValue(sheetName, cell, lastactualweight)
  10038. f.SetCellStyle(sheetName, cell, cell, styleID)
  10039. } else {
  10040. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  10041. f.SetCellStyle(sheetName, cell, cell, styleID)
  10042. }
  10043. cell = fmt.Sprintf("K%d", num)
  10044. if _, ok := planExec["actualweight"]; ok {
  10045. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  10046. f.SetCellValue(sheetName, cell, actualweight)
  10047. f.SetCellStyle(sheetName, cell, cell, styleID)
  10048. } else {
  10049. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  10050. f.SetCellStyle(sheetName, cell, cell, styleID)
  10051. }
  10052. num += 1
  10053. }
  10054. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10055. for i, header := range headers2 {
  10056. cell := "%" + fmt.Sprintf("c%d", num)
  10057. cell = fmt.Sprintf(cell, 'C'+i)
  10058. f.SetCellValue(sheetName, cell, header)
  10059. f.SetCellStyle(sheetName, cell, cell, styleID)
  10060. maxWidth := len(header)
  10061. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  10062. }
  10063. num += 1
  10064. for _, plan2 := range plan2Map[plan["id"]] {
  10065. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10066. sort, _ := strconv.Atoi(plan2["sort"])
  10067. f.SetCellValue(sheetName, cell, sort)
  10068. f.SetCellStyle(sheetName, cell, cell, styleID)
  10069. cell = fmt.Sprintf("D%d", num)
  10070. f.SetCellValue(sheetName, cell, plan2["fname"])
  10071. f.SetCellStyle(sheetName, cell, cell, styleID)
  10072. cell = fmt.Sprintf("E%d", num)
  10073. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  10074. f.SetCellValue(sheetName, cell, lweight)
  10075. f.SetCellStyle(sheetName, cell, cell, styleID)
  10076. cell = fmt.Sprintf("F%d", num)
  10077. if _, ok := plan2["actualweightminus"]; ok {
  10078. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  10079. f.SetCellValue(sheetName, cell, actualweightminus)
  10080. f.SetCellStyle(sheetName, cell, cell, styleID)
  10081. } else {
  10082. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  10083. f.SetCellStyle(sheetName, cell, cell, styleID)
  10084. }
  10085. cell = fmt.Sprintf("G%d", num)
  10086. if _, ok := plan2["diff"]; ok {
  10087. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  10088. f.SetCellValue(sheetName, cell, diff)
  10089. f.SetCellStyle(sheetName, cell, cell, styleID)
  10090. } else {
  10091. f.SetCellValue(sheetName, cell, plan2["diff"])
  10092. f.SetCellStyle(sheetName, cell, cell, styleID)
  10093. }
  10094. cell = fmt.Sprintf("H%d", num)
  10095. if _, ok := plan2["diffRate"]; ok {
  10096. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  10097. f.SetCellValue(sheetName, cell, diffRate)
  10098. f.SetCellStyle(sheetName, cell, cell, styleID)
  10099. } else {
  10100. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  10101. f.SetCellStyle(sheetName, cell, cell, styleID)
  10102. }
  10103. cell = fmt.Sprintf("I%d", num)
  10104. f.SetCellValue(sheetName, cell, plan2["intime"])
  10105. f.SetCellStyle(sheetName, cell, cell, styleID)
  10106. cell = fmt.Sprintf("J%d", num)
  10107. if _, ok := plan2["lastactualweight"]; ok {
  10108. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  10109. f.SetCellValue(sheetName, cell, lastactualweight)
  10110. f.SetCellStyle(sheetName, cell, cell, styleID)
  10111. } else {
  10112. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  10113. f.SetCellStyle(sheetName, cell, cell, styleID)
  10114. }
  10115. cell = fmt.Sprintf("K%d", num)
  10116. if _, ok := plan2["lastactualweight"]; ok {
  10117. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  10118. f.SetCellValue(sheetName, cell, actualweight)
  10119. f.SetCellStyle(sheetName, cell, cell, styleID)
  10120. } else {
  10121. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  10122. f.SetCellStyle(sheetName, cell, cell, styleID)
  10123. }
  10124. num += 1
  10125. }
  10126. num += 1
  10127. notBorder = append(notBorder, num)
  10128. }
  10129. for i := 2; i < num; i++ {
  10130. exist := false
  10131. for _, n := range notBorder {
  10132. if i+1 == n {
  10133. exist = true
  10134. break
  10135. }
  10136. }
  10137. if !exist {
  10138. // 为 A-K 列设置边框
  10139. for col := 'A'; col <= 'K'; col++ {
  10140. cellName := fmt.Sprintf("%c%d", col, i)
  10141. style, _ := f.NewStyle(&excelizexuri.Style{
  10142. Border: border, Alignment: &excelizexuri.Alignment{
  10143. Vertical: "center",
  10144. Horizontal: "center",
  10145. ShrinkToFit: true,
  10146. WrapText: true,
  10147. },
  10148. })
  10149. f.SetCellStyle(sheetName, cellName, cellName, style)
  10150. }
  10151. }
  10152. }
  10153. for col := 'A'; col <= 'K'; col++ {
  10154. colName := string(col)
  10155. switch colName {
  10156. case "A", "B": // 牧场名称、TMR列
  10157. f.SetColWidth(sheetName, colName, colName, 10)
  10158. case "C": // 操作编号列
  10159. f.SetColWidth(sheetName, colName, colName, 10)
  10160. case "D", "E": // 计划重量、实际重量列
  10161. f.SetColWidth(sheetName, colName, colName, 12)
  10162. case "F": // 代表成分/投料位置列
  10163. f.SetColWidth(sheetName, colName, colName, 20)
  10164. case "G", "H": // 误差数、准确率列
  10165. f.SetColWidth(sheetName, colName, colName, 12)
  10166. case "I": // 完成时间列
  10167. f.SetColWidth(sheetName, colName, colName, 15)
  10168. case "J", "K": // 起始读数重量、完成读数重量列
  10169. f.SetColWidth(sheetName, colName, colName, 15)
  10170. }
  10171. }
  10172. // 设置响应头
  10173. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10174. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10175. c.Header("Content-Transfer-Encoding", "binary")
  10176. // 写入 Excel 文件到响应
  10177. if err := f.Write(c.Writer); err != nil {
  10178. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10179. return
  10180. }
  10181. }
  10182. func RestartMqtt(c *gin.Context) {
  10183. appG := app.Gin{C: c}
  10184. // 发送 GET 请求到 MQTT 重启接口
  10185. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10186. if err != nil {
  10187. logging.Error("RestartMqtt request failed:", err)
  10188. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10189. return
  10190. }
  10191. defer resp.Body.Close()
  10192. // 读取响应内容f
  10193. body, err := ioutil.ReadAll(resp.Body)
  10194. if err != nil {
  10195. logging.Error("RestartMqtt read response failed:", err)
  10196. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10197. return
  10198. }
  10199. // 检查响应状态码
  10200. if resp.StatusCode != http.StatusOK {
  10201. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10202. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10203. return
  10204. }
  10205. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10206. }
  10207. func FpdBatchEditByWeight(c *gin.Context) {
  10208. appG := app.Gin{C: c}
  10209. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10210. fsions := gofasion.NewFasion(string(dataByte))
  10211. barList := fsions.Get("barList").Array()
  10212. pastureid := fsions.Get("pastureId").ValueStr()
  10213. tx := restful.Engine.NewSession()
  10214. defer tx.Close()
  10215. 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
  10216. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10217. if err != nil {
  10218. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10219. return
  10220. }
  10221. for _, barFsions := range barList {
  10222. dataexcel := make(map[string]interface{}, 0)
  10223. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10224. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10225. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10226. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10227. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10228. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10229. continue
  10230. }
  10231. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10232. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10233. // if err != nil {
  10234. // logs.Error(err)
  10235. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10236. // return
  10237. // }
  10238. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10239. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10240. // if err != nil {
  10241. // logs.Error(err)
  10242. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10243. // return
  10244. // }
  10245. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10246. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10247. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10248. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10249. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10250. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10251. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10252. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10253. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10254. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10255. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10256. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10257. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10258. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10259. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10260. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10261. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10262. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10263. if err != nil {
  10264. logs.Error(err)
  10265. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10266. return
  10267. }
  10268. if !ftexist {
  10269. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10270. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10271. if err != nil {
  10272. logs.Error(err)
  10273. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10274. return
  10275. }
  10276. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10277. if err != nil {
  10278. logs.Error(err)
  10279. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10280. return
  10281. }
  10282. }
  10283. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10284. if err != nil {
  10285. logs.Error(err)
  10286. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10287. return
  10288. }
  10289. if !exist {
  10290. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10291. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10292. if err != nil {
  10293. logs.Error(err)
  10294. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10295. return
  10296. }
  10297. }
  10298. var feedpargs []interface{}
  10299. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10300. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10301. if _, ok := dataexcel["ftname"]; ok {
  10302. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10303. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10304. // upFeedpSql += `,ftweight = ? `
  10305. // feedpargs = append(feedpargs, weight)
  10306. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10307. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10308. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10309. } else {
  10310. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10311. }
  10312. // if _, ok := dataexcel["ptsfname"]; ok {
  10313. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10314. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10315. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10316. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10317. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10318. // } else {
  10319. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10320. // }
  10321. upFeedpSql += " where barname = ? and pastureid = ? "
  10322. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10323. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10324. if err != nil {
  10325. logs.Error(err)
  10326. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10327. return
  10328. }
  10329. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10330. if err != nil {
  10331. logs.Error(err)
  10332. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10333. return
  10334. }
  10335. if !exist1 {
  10336. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10337. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10338. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10339. if err != nil {
  10340. logs.Error(err)
  10341. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10342. return
  10343. }
  10344. }
  10345. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10346. if err != nil {
  10347. logs.Error(err)
  10348. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10349. return
  10350. }
  10351. if !exist2 {
  10352. _, 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) `,
  10353. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10354. if err != nil {
  10355. logs.Error(err)
  10356. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10357. return
  10358. }
  10359. }
  10360. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10361. if err != nil {
  10362. logs.Error(err)
  10363. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10364. return
  10365. }
  10366. if !exist3 {
  10367. _, 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) `,
  10368. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10369. if err != nil {
  10370. logs.Error(err)
  10371. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10372. return
  10373. }
  10374. }
  10375. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10376. if err != nil {
  10377. logs.Error(err)
  10378. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10379. return
  10380. }
  10381. if !exist4 {
  10382. _, 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) `,
  10383. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10384. if err != nil {
  10385. logs.Error(err)
  10386. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10387. return
  10388. }
  10389. }
  10390. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  10391. if err != nil {
  10392. logs.Error(err)
  10393. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10394. return
  10395. }
  10396. if !exist5 {
  10397. _, 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) `,
  10398. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10399. if err != nil {
  10400. logs.Error(err)
  10401. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10402. return
  10403. }
  10404. }
  10405. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  10406. if err != nil {
  10407. logs.Error(err)
  10408. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10409. return
  10410. }
  10411. if !exist6 {
  10412. _, 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) `,
  10413. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10414. if err != nil {
  10415. logs.Error(err)
  10416. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10417. return
  10418. }
  10419. }
  10420. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10421. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10422. and pastureid = ? and times = ?`
  10423. var fpdargs1 []interface{}
  10424. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10425. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10426. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10427. if err != nil {
  10428. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10429. return
  10430. }
  10431. var fpdargs2 []interface{}
  10432. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10433. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10434. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10435. if err != nil {
  10436. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10437. return
  10438. }
  10439. var fpdargs3 []interface{}
  10440. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10441. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10442. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10443. if err != nil {
  10444. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10445. return
  10446. }
  10447. var fpdargs4 []interface{}
  10448. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10449. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10450. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10451. if err != nil {
  10452. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10453. return
  10454. }
  10455. var fpdargs5 []interface{}
  10456. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10457. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10458. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10459. if err != nil {
  10460. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10461. return
  10462. }
  10463. var fpdargs6 []interface{}
  10464. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10465. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10466. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10467. if err != nil {
  10468. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10469. return
  10470. }
  10471. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10472. 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()
  10473. if err != nil {
  10474. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10475. return
  10476. }
  10477. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10478. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10479. upFpdetailList := make([]*upFpdetail, 0)
  10480. for _, newfpd := range newList {
  10481. for _, oldfpd := range oldFpdList {
  10482. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10483. var oldweight, newweight float64
  10484. if oldfpd["weight"] != nil {
  10485. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10486. }
  10487. if newfpd["weight"] != nil {
  10488. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10489. }
  10490. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10491. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10492. Old: oldweight,
  10493. New: newweight,
  10494. Times: newfpd["times"].(int64),
  10495. Ptid: newfpd["ptid"].(int64),
  10496. Fweight: fweight,
  10497. Id: oldfpd["id"].(int64),
  10498. })
  10499. break
  10500. }
  10501. }
  10502. }
  10503. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10504. }
  10505. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10506. }
  10507. func FtImportExcel(c *gin.Context) {
  10508. appG := app.Gin{C: c}
  10509. inputdata := ""
  10510. c.Request.ParseForm()
  10511. params := c.Request.Form
  10512. file, _, err := c.Request.FormFile("file")
  10513. if err != nil {
  10514. appG.Response(http.StatusOK, e.ERROR, err)
  10515. return
  10516. }
  10517. sqlnamestrs := params.Get("name")
  10518. sheetname := params.Get("sheetname")
  10519. pastureid := params.Get("pastureid")
  10520. //importParams := params.Get("importParams")
  10521. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10522. // 必输项参数 (字符串格式 "field1,field2,field3")
  10523. requiredParams := params.Get("requiredParams")
  10524. // 日期参数
  10525. dateParams := params.Get("dateParams")
  10526. // 数字参数
  10527. numParams := params.Get("numParams")
  10528. //将字符串分割开
  10529. dateParamslist := strings.Split(dateParams, ",")
  10530. requiredParamslist := strings.Split(requiredParams, ",")
  10531. numParamslist := strings.Split(numParams, ",")
  10532. queryData := make([]interface{}, 0)
  10533. sqlslist := strings.Split(sqlnamestrs, ",")
  10534. xlsx1, err := excelize.OpenReader(file)
  10535. if err != nil {
  10536. fmt.Println(err)
  10537. return
  10538. }
  10539. ok := 0
  10540. error := 0
  10541. isdone := true
  10542. rows := xlsx1.GetRows(sheetname)
  10543. // 限制10000条,多余的截取掉
  10544. if len(rows) > 10000 {
  10545. rows = rows[:10000]
  10546. }
  10547. tx := restful.Engine.NewSession()
  10548. ftNameList := make(map[string]interface{})
  10549. var ftNames []interface{}
  10550. for i, row := range rows {
  10551. if i > 0 {
  10552. entry := make(map[string]interface{})
  10553. outentry := make(map[string]interface{})
  10554. for j, colCell := range rows[0] {
  10555. for k, colCell1 := range row {
  10556. if j == k {
  10557. outentry[colCell] = colCell1
  10558. entry[colCell] = colCell1
  10559. }
  10560. }
  10561. }
  10562. inputdata = ""
  10563. a := ""
  10564. fmt.Println(outentry, entry)
  10565. //校验日期格式
  10566. for _, v := range dateParamslist {
  10567. if v == "" {
  10568. continue
  10569. }
  10570. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10571. dtime, err := TransfTime(d.(string))
  10572. if err != nil {
  10573. a = strings.Trim(v, " ")
  10574. break
  10575. }
  10576. outentry[strings.Trim(v, " ")] = dtime
  10577. }
  10578. }
  10579. if a != "" {
  10580. outentry["error_msg"] = a + " 格式错误"
  10581. error++
  10582. queryData = append(queryData, outentry)
  10583. continue
  10584. }
  10585. a = ""
  10586. //校验必填格式
  10587. for _, v := range requiredParamslist {
  10588. if v == "" {
  10589. continue
  10590. }
  10591. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  10592. a = strings.Trim(v, " ")
  10593. break
  10594. }
  10595. }
  10596. if a != "" {
  10597. outentry["error_msg"] = a + " 未填或格式错误"
  10598. error++
  10599. queryData = append(queryData, outentry)
  10600. continue
  10601. }
  10602. a = ""
  10603. //校验数字格式
  10604. for _, v := range numParamslist {
  10605. if v == "" {
  10606. continue
  10607. }
  10608. d, ok := outentry[strings.Trim(v, " ")]
  10609. if !ok || d == "" {
  10610. outentry[strings.Trim(v, " ")] = 0
  10611. } else {
  10612. var fl float64
  10613. switch d.(type) {
  10614. case string:
  10615. fl, err = strconv.ParseFloat(d.(string), 64)
  10616. }
  10617. if err != nil || fl < 0 {
  10618. a = strings.Trim(v, " ")
  10619. break
  10620. }
  10621. }
  10622. }
  10623. if a != "" {
  10624. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  10625. error++
  10626. queryData = append(queryData, outentry)
  10627. continue
  10628. }
  10629. err := tx.Begin()
  10630. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  10631. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  10632. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  10633. }
  10634. for _, sqlnamestr := range sqlslist {
  10635. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  10636. paramslist := strings.Split(paramslists, ",")
  10637. if len(paramslist) > 0 {
  10638. s_params := make([]interface{}, 0)
  10639. for _, value := range paramslist {
  10640. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  10641. if tempv, exists := c.Get("jwt_username"); exists {
  10642. s_params = append(s_params, tempv.(string))
  10643. } else {
  10644. s_params = append(s_params, "")
  10645. }
  10646. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  10647. s_params = append(s_params, pastureid)
  10648. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  10649. ids, err := setting.SnowIds.NextId()
  10650. if err != nil {
  10651. ids = time.Now().UnixNano()
  10652. logging.Info("create SnowIds err", err)
  10653. }
  10654. s_params = append(s_params, ids)
  10655. } else {
  10656. if outentry[strings.Trim(value, " ")] == nil {
  10657. s_params = append(s_params, "")
  10658. } else {
  10659. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  10660. }
  10661. }
  10662. }
  10663. outentry["input"] = inputdata
  10664. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  10665. if err != nil {
  10666. if tx != nil {
  10667. tx.Rollback()
  10668. }
  10669. if tx != nil {
  10670. tx.Close()
  10671. }
  10672. msg := geterrmsg(err.Error())
  10673. outentry["error_msg"] = msg
  10674. error++
  10675. queryData = append(queryData, outentry)
  10676. isdone = true
  10677. break
  10678. } else {
  10679. if len(returnmsgmap1) > 0 {
  10680. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  10681. if tx != nil {
  10682. tx.Rollback()
  10683. }
  10684. if tx != nil {
  10685. tx.Close()
  10686. }
  10687. msg := geterrmsg(va.(string))
  10688. outentry["error_msg"] = msg
  10689. error++
  10690. queryData = append(queryData, outentry)
  10691. isdone = true
  10692. break
  10693. }
  10694. }
  10695. isdone = false
  10696. }
  10697. }
  10698. }
  10699. ftNames = append(ftNames, outentry["配方名称"])
  10700. switch {
  10701. case err != nil:
  10702. if tx != nil {
  10703. tx.Rollback()
  10704. }
  10705. default:
  10706. if tx != nil {
  10707. err = tx.Commit()
  10708. }
  10709. }
  10710. if tx != nil {
  10711. tx.Close()
  10712. }
  10713. }
  10714. if !isdone {
  10715. ok++
  10716. isdone = true
  10717. }
  10718. }
  10719. go ftSync(ftNames, pastureid)
  10720. data := make(map[string]interface{})
  10721. data["result"] = queryData
  10722. data["success"] = ok
  10723. data["err_count"] = error
  10724. appG.Response(http.StatusOK, e.SUCCESS, data)
  10725. }
  10726. func ftSync(ftNameList []interface{}, pastureId string) {
  10727. tx := restful.Engine.NewSession()
  10728. defer tx.Close()
  10729. for _, ftName := range ftNameList {
  10730. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  10731. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  10732. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  10733. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  10734. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  10735. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  10736. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  10737. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  10738. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, ftName).QueryString()
  10739. FpdBatchEditGrfd(pastureId, values1)
  10740. }
  10741. }
  10742. func CopyFeedtemplet(c *gin.Context) {
  10743. appG := app.Gin{C: c}
  10744. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10745. fsion := gofasion.NewFasion(string(dataByte))
  10746. pastureid := fsion.Get("pastureid").ValueStr()
  10747. newName := fsion.Get("newName").ValueStr()
  10748. id := fsion.Get("id").ValueStr()
  10749. tx := restful.Engine.NewSession()
  10750. defer tx.Close()
  10751. count, err := tx.SQL(` select count(1) from feedtemplet where tname = ? `, newName).Count()
  10752. if err != nil {
  10753. appG.Response(http.StatusOK, e.ERROR, err)
  10754. return
  10755. }
  10756. if count > 0 {
  10757. appG.Response(http.StatusOK, e.ERROR, "配方名称重复!")
  10758. return
  10759. }
  10760. type ftCode struct {
  10761. Tcode string `xorm:"tcode"`
  10762. }
  10763. code := new(ftCode)
  10764. err = tx.SQL(`select if(left((select max(tcode) from feedtemplet where pastureid = ?),8) =
  10765. (select DATE_FORMAT(now(),"%Y%m%d")),(select max(tcode)+1 from feedtemplet where pastureid = ?),
  10766. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))) tcode`, pastureid, pastureid).GetFirst(code).Error
  10767. if err != nil {
  10768. appG.Response(http.StatusOK, e.ERROR, err)
  10769. return
  10770. }
  10771. if code.Tcode == "" {
  10772. appG.Response(http.StatusOK, e.ERROR, "配方编码生产失败!")
  10773. return
  10774. }
  10775. _, err = tx.Exec(`INSERT INTO feedtemplet(pastureid,tname,tcode,tcolor,ccid,ccname,fttype,fttypeid,source,
  10776. remark,enable,sort,volume,autozone)
  10777. select pastureid,?,?,tcolor,ccid,ccname,fttype,fttypeid,source,
  10778. remark,enable,sort,volume,autozone from feedtemplet where id = ? `, newName, code.Tcode, id)
  10779. if err != nil {
  10780. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  10781. return
  10782. }
  10783. _, err = tx.Exec(`insert into ftdetail(pastureid,ftid,fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  10784. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry)
  10785. select pastureid,(select id from feedtemplet where tcode = ? ),fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  10786. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry
  10787. from ftdetail where ftid = ? `, code.Tcode, id)
  10788. if err != nil {
  10789. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  10790. return
  10791. }
  10792. appG.Response(http.StatusOK, e.SUCCESS, true)
  10793. }
  10794. func Test(c *gin.Context) {
  10795. appG := app.Gin{C: c}
  10796. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10797. appG.Response(http.StatusOK, e.SUCCESS, string(dataByte))
  10798. }
  10799. func GetPlanDry(c *gin.Context) {
  10800. appG := app.Gin{C: c}
  10801. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10802. fsion := gofasion.NewFasion(string(dataByte))
  10803. date := fsion.Get("date").ValueStr()
  10804. tx := restful.Engine.NewSession()
  10805. defer tx.Close()
  10806. dataList, err := tx.SQL(`SELECT
  10807. t.feedtempletName,
  10808. ifnull(t.feedtempletPrice,0)feedtempletPrice,
  10809. ifnull(t.feedtempletWeight,0)feedtempletWeight,
  10810. ifnull(t.feedtempletDryWeight,0)feedtempletDryWeight,
  10811. t.tmrno,
  10812. t.bname,
  10813. t.barid,
  10814. t.dry,
  10815. t.actualweightminus,
  10816. t.mydate,
  10817. t.pasturename,
  10818. t.endDate,
  10819. t.startDate,
  10820. t.times,
  10821. -- 计算startDate和endDate的中间时间
  10822. ifnull(DATE_FORMAT(
  10823. DATE_ADD(
  10824. t.startDate,
  10825. INTERVAL TIMESTAMPDIFF(SECOND, t.startDate, t.endDate)/2 SECOND
  10826. ),
  10827. '%Y-%m-%d %H:%i:%s'
  10828. ),'') AS midTime
  10829. FROM (
  10830. SELECT
  10831. (SELECT sort FROM downloadedplan WHERE pid = d.pid AND mydate = d.mydate AND lpplantype IN (0,1)) tmrno,
  10832. b.bname,
  10833. b.id barid,
  10834. 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
  10835. JOIN downloadplandtl1 dd1 ON dd.id = dd1.pid
  10836. JOIN feednur fn ON fn.fid = dd1.fid
  10837. WHERE dd.pid = d.pid AND dd.mydate = d.mydate AND lpplantype IN (0,1,4))/100),2) dry,
  10838. 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,
  10839. DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate,
  10840. p.pasture_name pastureName,
  10841. DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endDate,
  10842. DATE_FORMAT(IFNULL(
  10843. (SELECT MAX(intime) FROM downloadplandtl2 d1
  10844. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d1.intime<d2.intime),
  10845. (SELECT MAX(intime) FROM downloadplandtl1_exec de
  10846. WHERE de.date=d2.date AND de.pastureid = d2.pastureid AND de.pid=d2.pid)
  10847. ), '%Y-%m-%d %H:%i:%s') startDate,
  10848. d.times ,
  10849. ( SELECT
  10850. round(SUM(
  10851. IF(ftd.preftid<>0,
  10852. ftd.fweight*IFNULL((SELECT SUM(ftd1.fweight*f1.dry/100)/SUM(ftd1.fweight) FROM ftdetaildate ftd1
  10853. JOIN feednur f1 ON f1.fid= ftd1.fid AND f1.pastureid = ftd1.pastureid
  10854. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  10855. ftd.fweight*f.dry/100)) ,2)
  10856. dryweight
  10857. FROM ftdetaildate ftd
  10858. LEFT JOIN feednur f ON f.fid= ftd.fid AND f.pastureid = ftd.pastureid
  10859. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletDryWeight,(
  10860. select
  10861. sum(ftd.fweight)
  10862. FROM ftdetaildate ftd
  10863. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletWeight,
  10864. ( SELECT
  10865. round(SUM(
  10866. IF(ftd.preftid<>0,
  10867. IFNULL((SELECT SUM(ftd1.fweight*f1.uprice) FROM ftdetaildate ftd1
  10868. JOIN feed f1 ON f1.id= ftd1.fid AND f1.pastureid = ftd1.pastureid
  10869. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  10870. ftd.fweight*f.uprice)) ,2)
  10871. dryweight
  10872. FROM ftdetaildate ftd
  10873. LEFT JOIN feed f ON f.id= ftd.fid AND f.pastureid = ftd.pastureid
  10874. WHERE ftd.ftid = d.tempid and ftd.date = d2.date )
  10875. feedtempletPrice,d.templetname feedtempletName
  10876. FROM downloadedplan d
  10877. JOIN downloadplandtl2 d2 ON d.id=d2.PID
  10878. JOIN bar b ON b.id = d2.fbarid
  10879. JOIN pasture p ON p.pastureid = d.pastureid
  10880. WHERE d.mydate = DATE_FORMAT(?,'%Y-%m-%d')
  10881. AND d2.type = 0
  10882. AND d.havebutton = 1
  10883. ) t
  10884. WHERE 1=1 `, date).QueryString()
  10885. if err != nil {
  10886. logs.Error(err)
  10887. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  10888. return
  10889. }
  10890. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  10891. }
  10892. func GetBar(c *gin.Context) {
  10893. appG := app.Gin{C: c}
  10894. tx := restful.Engine.NewSession()
  10895. defer tx.Close()
  10896. pastureinfo := new(udPastureInfo)
  10897. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  10898. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  10899. if err != nil {
  10900. logs.Error(err)
  10901. return
  10902. }
  10903. dataList, err := tx.SQL(` select id,bname from bar where pastureid = ?`, pastureinfo.Pastureid).QueryString()
  10904. if err != nil {
  10905. logs.Error(err)
  10906. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  10907. return
  10908. }
  10909. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  10910. }
  10911. func GetHomepage(c *gin.Context) {
  10912. appG := app.Gin{C: c}
  10913. tx := restful.Engine.NewSession()
  10914. defer tx.Close()
  10915. dataList, err := tx.SQL(` SELECT
  10916. ifnull((SELECT CONCAT(ROUND(if(SUM(lweight) <= SUM(iweight),SUM(lweight)/SUM(iweight),SUM(iweight)/SUM(lweight))*100,2),'%') yesRateHL
  10917. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  10918. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) ),'0.00%')yesRateHL, -- 昨日混料准确率
  10919. (SELECT CONCAT(ROUND(SUM(iweight)/SUM(lweight)*100,2),'%') yesRateHL
  10920. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  10921. 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日混料准确率
  10922. ifnull((SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  10923. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  10924. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) ),'0.00%')yesRateSL, -- 昨日撒料准确率
  10925. (SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  10926. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  10927. 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日撒料准确率
  10928. 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),'%') -- 正确率
  10929. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  10930. WHERE dt.pastureid = d.pastureid AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')),'0.00%') yesRateSLR, -- 昨日正确率
  10931. (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),'%') -- 正确率
  10932. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  10933. WHERE dt.pastureid = d.pastureid
  10934. 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日正确率
  10935. (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,
  10936. (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,
  10937. 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,
  10938. 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,
  10939. ifnull(round(getSLtimeDiffSINGEL(d.pastureid,d.mydate),2),0.00) temtime,
  10940. ifnull(round(getSLtimeDiffMonth(d.pastureid) ,2),0.00) montime
  10941. FROM
  10942. (SELECT (select column_default as pastureid from information_schema.COLUMNS
  10943. 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()
  10944. if err != nil {
  10945. logs.Error(err)
  10946. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  10947. return
  10948. }
  10949. dataList1, err := tx.SQL(`select
  10950. 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
  10951. LEFT JOIN ftdetail ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1'
  10952. join feed f on f.id = ifnull(ftd.fid,d1.fid) where d1.date = date_format(now(),'%Y-%m-%d') `).QueryString()
  10953. if err != nil {
  10954. logs.Error(err)
  10955. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  10956. return
  10957. }
  10958. for _, data := range dataList {
  10959. for _, data1 := range dataList1 {
  10960. data["totalCost"] = data1["totalCost"]
  10961. data["cost"] = data1["cost"]
  10962. }
  10963. }
  10964. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  10965. }
  10966. func GetFeedingManagement(c *gin.Context) {
  10967. appG := app.Gin{C: c}
  10968. typea := c.Query("typea") // 0 栏舍 1 日期
  10969. startDate := c.Query("startdate")
  10970. endDate := c.Query("enddate")
  10971. tx := restful.Engine.NewSession()
  10972. defer tx.Close()
  10973. if typea == "0" {
  10974. 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
  10975. SUM(
  10976. 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 ,
  10977. 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)*
  10978. 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 )),
  10979. 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)*
  10980. 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 ))
  10981. )
  10982. )actualweightminus ,
  10983. SUM(
  10984. 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 ,
  10985. 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)*
  10986. 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 )),
  10987. 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)*
  10988. 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 ))
  10989. ) * ifnull(fn.dry,0)
  10990. ) dryweight , SUM(
  10991. 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 ,
  10992. 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)*
  10993. 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 )),
  10994. 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)*
  10995. 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 ))
  10996. ) * ifnull(f.uprice,0)
  10997. ) priceweight
  10998. ,(select ccount from feedpdate where date = d1.date and barid = d2.fbarid) ccount,b.bname
  10999. FROM
  11000. downloadedplan d
  11001. JOIN downloadplandtl2 d2
  11002. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11003. JOIN downloadplandtl1 d1
  11004. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11005. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11006. 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
  11007. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11008. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11009. left join feednur fn on fn.fid = f.id
  11010. WHERE d.mydate BETWEEN ? AND ? GROUP BY d2.fbarid ) t `, startDate, endDate).QueryString()
  11011. if err != nil {
  11012. logs.Error(err)
  11013. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11014. return
  11015. }
  11016. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11017. } else {
  11018. 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
  11019. SUM(
  11020. 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 ,
  11021. 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)*
  11022. 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 )),
  11023. 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)*
  11024. 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 ))
  11025. )
  11026. )actualweightminus ,
  11027. SUM(
  11028. 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 ,
  11029. 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)*
  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 ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11031. 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)*
  11032. 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 ))
  11033. ) * ifnull(fn.dry,0)
  11034. ) dryweight , SUM(
  11035. 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 ,
  11036. 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)*
  11037. 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 )),
  11038. 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)*
  11039. 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 ))
  11040. ) * ifnull(f.uprice,0)
  11041. ) priceweight
  11042. ,(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
  11043. FROM
  11044. downloadedplan d
  11045. JOIN downloadplandtl2 d2
  11046. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11047. JOIN downloadplandtl1 d1
  11048. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11049. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11050. 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
  11051. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11052. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11053. left join feednur fn on fn.fid = f.id
  11054. WHERE d.mydate BETWEEN ? AND ?
  11055. GROUP BY d.mydate) t `, startDate, endDate).QueryString()
  11056. if err != nil {
  11057. logs.Error(err)
  11058. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11059. return
  11060. }
  11061. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11062. }
  11063. }
  11064. // doneTimes 完成计划
  11065. // doneWeight 完成重量
  11066. // monRateHL 近三十天混料准确率
  11067. // monRateSL 近三十天撒料准确率
  11068. // monRateSLR 近30天撒料正确率
  11069. // montime 近30天撒料偏差
  11070. // planTimes 计划车次
  11071. // planWeight 计划重量
  11072. // temtime 撒料偏差
  11073. // yesRateHL 混料准确率
  11074. // yesRateSL 撒料准确率
  11075. // yesRateSLR 撒料正确率