ops.go 461 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "math"
  11. "net/http"
  12. "os"
  13. "path"
  14. "regexp"
  15. "sort"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "tmr-watch/conf/setting"
  21. "tmr-watch/http/handle/jpud"
  22. "tmr-watch/http/handle/restful"
  23. "tmr-watch/http/handle/ymy"
  24. "tmr-watch/models"
  25. "tmr-watch/module"
  26. "tmr-watch/pkg/app"
  27. "tmr-watch/pkg/e"
  28. "tmr-watch/pkg/logging"
  29. "github.com/360EntSecGroup-Skylar/excelize"
  30. "github.com/Anderson-Lu/gofasion/gofasion"
  31. "github.com/astaxie/beego/logs"
  32. "github.com/gin-gonic/gin"
  33. "github.com/qichengzx/coordtransform"
  34. "github.com/tealeg/xlsx"
  35. "github.com/xormplus/xorm"
  36. excelizexuri "github.com/xuri/excelize/v2"
  37. )
  38. // @Summary 根据SQL执行得到数据集
  39. // @Tags getData
  40. // @Accept json
  41. // @Produce json
  42. // @Param sql query string true "sql"
  43. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  44. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  45. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  46. // @Router /data/getdata [POST]
  47. func GetData(c *gin.Context) {
  48. appG := app.Gin{C: c}
  49. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  50. fsion := gofasion.NewFasion(string(dataByte))
  51. sqlstr := fsion.Get("sql").ValueStr()
  52. offset := fsion.Get("offset").ValueDefaultInt(0)
  53. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  54. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  55. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  56. if err != nil {
  57. appG.Response(http.StatusOK, e.ERROR, err.Error())
  58. } else {
  59. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  60. }
  61. }
  62. func Testpartitions(c *gin.Context) {
  63. appG := app.Gin{C: c}
  64. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  65. fsion := gofasion.NewFasion(string(dataByte))
  66. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  67. user := fsion.Get("user").ValueStr() //获取新数据库用户
  68. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  69. host := fsion.Get("host").ValueStr() //获取新数据库名称
  70. port := fsion.Get("port").ValueStr() //获取新数据库名称
  71. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  72. if sqls == nil || err1 != nil {
  73. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  74. }
  75. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  76. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  77. mydb, err := sql.Open("mysql", connecting) //连接新连接
  78. if err != nil {
  79. println("err1", err.Error())
  80. }
  81. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  82. if err != nil {
  83. println("err2", err.Error())
  84. }
  85. mydb.Close()
  86. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  87. mydb, err = sql.Open("mysql", connecting)
  88. if err != nil {
  89. println("err3", err.Error())
  90. }
  91. defer mydb.Close()
  92. if err == nil {
  93. mydb.SetMaxOpenConns(10)
  94. mydb.SetMaxIdleConns(10)
  95. }
  96. errmsg := ""
  97. if err == nil {
  98. //tx ,_ :=mydb.Begin()
  99. for _, sqlstr := range sqlstrs {
  100. //println("sqlstr---",sqlstr)
  101. if sqlstr == "" {
  102. continue
  103. }
  104. _, err = mydb.Exec(sqlstr)
  105. if err != nil {
  106. println("err4", err.Error())
  107. errmsg = err.Error()
  108. //err1 :=tx.Rollback()
  109. }
  110. }
  111. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  112. //err =tx.Commit()
  113. }
  114. if errmsg == "" {
  115. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  116. } else {
  117. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  118. }
  119. }
  120. func TestData(c *gin.Context) {
  121. appG := app.Gin{C: c}
  122. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  123. fsion := gofasion.NewFasion(string(dataByte))
  124. sqlstr := fsion.Get("sql").ValueStr()
  125. token := ""
  126. if tempv, exists := c.Get("jwt_username"); exists {
  127. token = tempv.(string)
  128. }
  129. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  130. }
  131. // @Summary 根据APISQL表中SQL执行得到数据集
  132. // @Tags GetDataByName
  133. // @Accept json
  134. // @Produce json
  135. // @Param sqlname body string true "sqlname"
  136. // @Param offset body int true "offset"
  137. // @Param pagecount body int true "pagecount"
  138. // @Param returntype body string true "returntype"
  139. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  140. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  141. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  142. // @Router /data/GetDataByName [POST]
  143. func GetDataByName(c *gin.Context) {
  144. appG := app.Gin{C: c}
  145. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  146. fsion := gofasion.NewFasion(string(dataByte))
  147. sqlnamestr := fsion.Get("name").ValueStr()
  148. offset := fsion.Get("offset").ValueDefaultInt(0)
  149. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  150. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  151. tx := restful.Engine.NewSession()
  152. err := tx.Begin()
  153. defer func() {
  154. switch {
  155. case err != nil:
  156. logging.Error("tx.Begin 事务启动失败__error:", err)
  157. if tx != nil {
  158. tx.Rollback()
  159. }
  160. default:
  161. if tx != nil {
  162. err = tx.Commit()
  163. }
  164. }
  165. if tx != nil {
  166. tx.Close()
  167. }
  168. }()
  169. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  170. if sql != "" {
  171. s_params := make([]interface{}, 0)
  172. if fsion.HasKey("parammaps") {
  173. parammaps := fsion.Get("parammaps")
  174. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  175. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  176. }
  177. paramslist := strings.Split(p, ",")
  178. if len(paramslist) > 0 && p != "" {
  179. for _, value := range paramslist {
  180. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  181. if tempv, exists := c.Get("jwt_username"); exists {
  182. s_params = append(s_params, tempv.(string))
  183. } else {
  184. s_params = append(s_params, "")
  185. }
  186. } else {
  187. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  188. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  189. // tmrNameList := []string{}
  190. // for _, tmr := range tmrArray {
  191. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  192. // }
  193. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  194. // } else {
  195. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  196. // }
  197. }
  198. }
  199. }
  200. } else if fsion.HasKey("params") {
  201. params := fsion.Get("params").Array()
  202. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  203. for _, v_params := range params {
  204. s_params = append(s_params, v_params.ValueStr())
  205. }
  206. }
  207. if returntype == "xlsx" {
  208. var xlsxfile *xlsx.File
  209. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  210. //c.File("c:/dd.xlsx")
  211. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  212. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  213. c.Header("Content-Transfer-Encoding", "binary")
  214. _ = xlsxfile.Write(c.Writer)
  215. } else {
  216. if sqlnamestr == "getHomepageStr" {
  217. parammaps := fsion.Get("parammaps")
  218. pastureid := parammaps.Get("pastureid").ValueStr()
  219. var montimeList []float64
  220. var montime float64
  221. var wg sync.WaitGroup
  222. now := time.Now()
  223. for i := 0; i < 30; i++ {
  224. wg.Add(1)
  225. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  226. go func(nowstr string) {
  227. defer wg.Done()
  228. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  229. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  230. if len(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})) > 0 {
  231. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  232. montimeList = append(montimeList, m)
  233. }
  234. }(nowstr)
  235. }
  236. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  237. if err != nil {
  238. logging.Error("GetDataByName err: ", err)
  239. msg := geterrmsg(err.Error())
  240. appG.Response(http.StatusOK, e.ERROR, msg)
  241. }
  242. wg.Wait()
  243. for _, m := range montimeList {
  244. montime += m
  245. }
  246. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  247. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  248. return
  249. }
  250. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  251. if err != nil {
  252. logging.Error("GetDataByName err: ", err)
  253. msg := geterrmsg(err.Error())
  254. appG.Response(http.StatusOK, e.ERROR, msg)
  255. } else {
  256. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  257. }
  258. }
  259. } else {
  260. appG.Response(http.StatusOK, e.SUCCESS, nil)
  261. }
  262. }
  263. // @Summary 根据APISQL表中SQL执行得到数据集
  264. // @Tags GetDataByName
  265. // @Accept json
  266. // @Produce json
  267. // @Param sqlname body string true "sqlname"
  268. // @Param offset body int true "offset"
  269. // @Param pagecount body int true "pagecount"
  270. // @Param returntype body string true "returntype"
  271. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  272. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  273. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  274. // @Router /data/GetDataByName [POST]
  275. func GetDataBySqlIN(c *gin.Context) {
  276. appG := app.Gin{C: c}
  277. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  278. fsion := gofasion.NewFasion(string(dataByte))
  279. sqlnamestr := fsion.Get("name").ValueStr()
  280. offset := fsion.Get("offset").ValueDefaultInt(0)
  281. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  282. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  283. tx := restful.Engine.NewSession()
  284. err := tx.Begin()
  285. defer func() {
  286. switch {
  287. case err != nil:
  288. logging.Error("tx.Begin 事务启动失败__error:", err)
  289. if tx != nil {
  290. tx.Rollback()
  291. }
  292. default:
  293. if tx != nil {
  294. err = tx.Commit()
  295. }
  296. }
  297. if tx != nil {
  298. tx.Close()
  299. }
  300. }()
  301. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  302. if sql != "" {
  303. s_params := make([]interface{}, 0)
  304. if fsion.HasKey("parammaps") {
  305. parammaps := fsion.Get("parammaps")
  306. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  307. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  308. }
  309. paramslist := strings.Split(p, ",")
  310. if len(paramslist) > 0 && p != "" {
  311. for _, value := range paramslist {
  312. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  313. if tempv, exists := c.Get("jwt_username"); exists {
  314. s_params = append(s_params, tempv.(string))
  315. } else {
  316. s_params = append(s_params, "")
  317. }
  318. } else {
  319. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  320. }
  321. }
  322. }
  323. } else if fsion.HasKey("params") {
  324. params := fsion.Get("params").Array()
  325. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  326. for _, v_params := range params {
  327. s_params = append(s_params, v_params.ValueStr())
  328. }
  329. }
  330. if returntype == "xlsx" {
  331. var xlsxfile *xlsx.File
  332. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  333. //c.File("c:/dd.xlsx")
  334. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  335. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  336. c.Header("Content-Transfer-Encoding", "binary")
  337. _ = xlsxfile.Write(c.Writer)
  338. } else {
  339. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  340. if err != nil {
  341. logging.Error("GetDataByName err: ", err)
  342. msg := geterrmsg(err.Error())
  343. appG.Response(http.StatusOK, e.ERROR, msg)
  344. } else {
  345. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  346. }
  347. }
  348. } else {
  349. appG.Response(http.StatusOK, e.SUCCESS, nil)
  350. }
  351. }
  352. // 错误处理
  353. // 将报错信息处理成汉字
  354. func geterrmsg(errstr string) (msgstr string) {
  355. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  356. rs := []rune(errstr)
  357. if hzRegexp.MatchString(string(rs[0])) {
  358. msgstr = errstr
  359. return
  360. }
  361. if strings.Contains(errstr, "Duplicate entry") {
  362. strs := strings.Split(errstr, ` key '`)
  363. if len(strs) > 1 {
  364. if len(strs[len(strs)-1]) > 1 {
  365. errstr = "Duplicate entry :" + strs[len(strs)-1]
  366. }
  367. }
  368. }
  369. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  370. if err != nil {
  371. msgstr = errstr
  372. return
  373. }
  374. if msg == nil || len(msg) == 0 {
  375. var param []interface{}
  376. param = append(param, errstr, errstr)
  377. go func() {
  378. tx := restful.Engine.NewSession()
  379. err := tx.Begin()
  380. defer func() {
  381. switch {
  382. case err != nil:
  383. logging.Error("tx.Begin 事务启动失败__error:", err)
  384. if tx != nil {
  385. tx.Rollback()
  386. }
  387. default:
  388. if tx != nil {
  389. err = tx.Commit()
  390. }
  391. }
  392. if tx != nil {
  393. tx.Close()
  394. }
  395. }()
  396. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  397. if err != nil {
  398. logging.Error("insert into err_msg(err,msg) err", err)
  399. }
  400. }()
  401. msgstr = errstr
  402. } else {
  403. msgstr = msg[0]["msg"]
  404. }
  405. return
  406. }
  407. // @Summary 根据APISQL表中SQL执行得到数据集
  408. // @Tags GetDataByNameForm
  409. // @Accept json
  410. // @Produce json
  411. // @Param sqlname body json true "sqlname"
  412. // @Param offset query int true "offset"
  413. // @Param pagecount query int true "pagecount"
  414. // @Param returntype query string true "returntype"
  415. // @Param s formData json true "ss"
  416. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  417. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  418. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  419. // @Router /data/GetDataByNameForm [POST]
  420. func GetDataByNameForm(c *gin.Context) {
  421. appG := app.Gin{C: c}
  422. //sqlnamestr := c.PostForm("measureNumber")
  423. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  424. //fsion := gofasion.NewFasion(string(dataByte))
  425. //sqlnamestr := fsion.Get("name").ValueStr()
  426. //offset := fsion.Get("offset").ValueInt()
  427. //pagecount := fsion.Get("pagecount").ValueInt()
  428. //returntype := fsion.Get("returntype").ValueStr()
  429. //params := fsion.Get("params").Array()
  430. c.Request.ParseForm()
  431. params := c.Request.Form
  432. offset := 0
  433. pageSize_ := 0
  434. returntype := params.Get("page")
  435. if returntype == "" {
  436. returntype = "0"
  437. }
  438. if tempv, exists := c.Get("jwt_username"); exists {
  439. params.Set("JwtUserName", tempv.(string))
  440. } else {
  441. params.Set("JwtUserName", "")
  442. }
  443. sqlnamestr := params.Get("name")
  444. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  445. s_params := make([]interface{}, 0)
  446. if returntype == "1" {
  447. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  448. if error != nil {
  449. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  450. }
  451. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  452. if error != nil {
  453. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  454. }
  455. pageSize_ = pageSize
  456. offset = pageNum
  457. }
  458. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  459. paramslist := strings.Split(p, ",")
  460. if len(paramslist) > 0 && p != "" {
  461. for _, value := range paramslist {
  462. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  463. }
  464. }
  465. if sql != "" {
  466. if returntype == "xlsx" {
  467. var xlsxfile *xlsx.File
  468. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  469. c.Header("Content-Type", "application/octet-stream")
  470. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  471. c.Header("Content-Transfer-Encoding", "binary")
  472. _ = xlsxfile.Write(c.Writer)
  473. } else {
  474. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  475. if err != nil {
  476. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  477. } else {
  478. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  479. }
  480. }
  481. } else {
  482. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  483. }
  484. }
  485. // @Summary 递归获取所有
  486. // @Tags menu
  487. // @Accept json
  488. // @Produce json
  489. // @Param Ton query string true "Ton"
  490. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  491. // @Router /authdata/GetRoleMenus [GET]
  492. func GetRecuDataByName(c *gin.Context) {
  493. appG := app.Gin{C: c}
  494. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  495. fsion := gofasion.NewFasion(string(dataByte))
  496. sqlnamestr := fsion.Get("name").ValueStr()
  497. parentidname := fsion.Get("idname").ValueStr()
  498. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  499. params := make(map[string]interface{})
  500. s_params := make([]interface{}, 0)
  501. if fsion.HasKey("params") {
  502. for _, v_params := range fsion.Get("params").Array() {
  503. s_params = append(s_params, v_params.ValueStr())
  504. }
  505. params["params"] = s_params
  506. } else {
  507. jparams := fsion.Get("parammaps")
  508. paramslist := strings.Split(p, ",")
  509. if len(paramslist) > 0 && p != "" {
  510. for _, value := range paramslist {
  511. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  512. if tempv, exists := c.Get("jwt_username"); exists {
  513. params[value] = tempv.(string)
  514. } else {
  515. params[value] = ""
  516. }
  517. } else {
  518. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  519. }
  520. }
  521. }
  522. }
  523. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  524. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  525. if err != nil {
  526. appG.Response(http.StatusOK, e.ERROR, err.Error())
  527. }
  528. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  529. }
  530. // @Summary 根据APISQL表中SQL执行得到数据集
  531. // @Tags GetDataByNames
  532. // @Accept json
  533. // @Produce json
  534. // @RequestBody sqlname query string true "sqlname"
  535. // @Param offset query int true "offset"
  536. // @Param pagecount query int true "pagecount"
  537. // @Param returntype query string true "returntype"
  538. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  539. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  540. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  541. // @Router /data/GetDataByNames [POST]
  542. func GetDataByNames(c *gin.Context) {
  543. appG := app.Gin{C: c}
  544. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  545. fsion := gofasion.NewFasion(string(dataByte))
  546. sqlParams := fsion.Array()
  547. queryData := make(map[string]interface{})
  548. for _, v := range sqlParams {
  549. fsion2 := gofasion.NewFasion(v.Json())
  550. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  551. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  552. if sql == "" {
  553. errorm := make(map[string]interface{})
  554. errorm["code"] = e.ERROR
  555. errorm["message"] = "sql没找到"
  556. queryData[fsion2.Get("name").ValueStr()] = errorm
  557. continue
  558. } else if sql != "" {
  559. offset := fsion2.Get("offset").ValueInt()
  560. pagecount := fsion2.Get("pagecount").ValueInt()
  561. returntype := fsion2.Get("returntype").ValueStr()
  562. s_params := make([]interface{}, 0)
  563. if fsion2.HasKey("parammaps") {
  564. parammaps := fsion2.Get("parammaps")
  565. paramslist := strings.Split(p, ",")
  566. if len(paramslist) > 0 && p != "" {
  567. for _, value := range paramslist {
  568. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  569. if tempv, exists := c.Get("jwt_username"); exists {
  570. s_params = append(s_params, tempv.(string))
  571. } else {
  572. s_params = append(s_params, "")
  573. }
  574. } else {
  575. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  576. }
  577. }
  578. }
  579. } else if fsion2.HasKey("params") {
  580. params := fsion2.Get("params").Array()
  581. for _, v_params := range params {
  582. s_params = append(s_params, v_params.ValueStr())
  583. }
  584. }
  585. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  586. if err != nil {
  587. errorm := make(map[string]interface{})
  588. errorm["code"] = e.ERROR
  589. errorm["message"] = err.Error()
  590. queryData[fsion2.Get("name").ValueStr()] = errorm
  591. logging.Error("GetDataByNames err: ", err)
  592. continue
  593. } else {
  594. queryData[fsion2.Get("name").ValueStr()] = queryData1
  595. }
  596. }
  597. }
  598. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  599. }
  600. // @Summary 根据APISQL表中SQL执行得到数据集
  601. // @Tags PostDataByNameForm
  602. // @Accept json
  603. // @Produce json
  604. // @Param sqlname query string true "sqlname"
  605. // @Param offset query int true "offset"
  606. // @Param pagecount query int true "pagecount"
  607. // @Param returntype query string true "returntype"
  608. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  609. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  610. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  611. // @Router /data/PostDataByNameForm [POST]
  612. func PostDataByNameForm(c *gin.Context) {
  613. appG := app.Gin{C: c}
  614. c.Request.ParseForm()
  615. params := c.Request.Form
  616. sqlnamestr := params.Get("name")
  617. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  618. s_params := make([]interface{}, 0)
  619. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  620. paramslist := strings.Split(p, ",")
  621. if len(paramslist) > 0 {
  622. for _, value := range paramslist {
  623. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  624. }
  625. }
  626. if sql != "" {
  627. queryData, err := execDataBySql(sql, s_params)
  628. if err != nil {
  629. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  630. } else {
  631. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  632. }
  633. } else {
  634. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  635. }
  636. }
  637. // GetReportform 将数据集转换格式
  638. // @Tags PostDataByNameForm
  639. // @Accept json
  640. // @Produce json
  641. // @Param sqlname query string true "sqlname"
  642. // @Param offset query int true "offset"
  643. // @Param pagecount query int true "pagecount"
  644. // @Param returntype query string true "returntype"
  645. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  646. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  647. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  648. func GetReportform(c *gin.Context) {
  649. appG := app.Gin{C: c}
  650. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  651. fsion := gofasion.NewFasion(string(dataByte))
  652. sqlnamestr := fsion.Get("name").ValueStr()
  653. checked := fsion.Get("checked").ValueStr()
  654. offset := fsion.Get("offset").ValueDefaultInt(0)
  655. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  656. parammaps := fsion.Get("parammaps")
  657. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  658. mode := parammaps.Get("mode").ValueDefaultInt(0)
  659. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  660. tx := restful.Engine.NewSession()
  661. err := tx.Begin()
  662. defer func() {
  663. switch {
  664. case err != nil:
  665. if tx != nil {
  666. tx.Rollback()
  667. }
  668. default:
  669. if tx != nil {
  670. err = tx.Commit()
  671. }
  672. }
  673. if tx != nil {
  674. tx.Close()
  675. }
  676. }()
  677. //fmt.Println("***************************************")
  678. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  679. if err != nil {
  680. appG.Response(http.StatusOK, e.ERROR, err.Error())
  681. } else {
  682. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  683. }
  684. }
  685. // GetUpkeepPlan 保养计划
  686. func GetUpkeepPlan(c *gin.Context) {
  687. appG := app.Gin{C: c}
  688. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  689. fsion := gofasion.NewFasion(string(dataByte))
  690. sqlnamestr := fsion.Get("name").ValueStr()
  691. offset := fsion.Get("offset").ValueDefaultInt(0)
  692. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  693. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  694. month := fsion.Get("month").ValueDefaultStr("map")
  695. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  696. tx := restful.Engine.NewSession()
  697. err := tx.Begin()
  698. defer func() {
  699. switch {
  700. case err != nil:
  701. if tx != nil {
  702. tx.Rollback()
  703. }
  704. default:
  705. if tx != nil {
  706. err = tx.Commit()
  707. }
  708. }
  709. if tx != nil {
  710. tx.Close()
  711. }
  712. }()
  713. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  714. if sql != "" {
  715. s_params := make([]interface{}, 0)
  716. if fsion.HasKey("parammaps") {
  717. parammaps := fsion.Get("parammaps")
  718. paramslist := strings.Split(p, ",")
  719. if len(paramslist) > 0 && p != "" {
  720. for _, value := range paramslist {
  721. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  722. if tempv, exists := c.Get("jwt_username"); exists {
  723. s_params = append(s_params, tempv.(string))
  724. } else {
  725. s_params = append(s_params, "")
  726. }
  727. } else {
  728. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  729. }
  730. }
  731. }
  732. } else if fsion.HasKey("params") {
  733. params := fsion.Get("params").Array()
  734. for _, v_params := range params {
  735. s_params = append(s_params, v_params.ValueStr())
  736. }
  737. }
  738. if returntype == "xlsx" {
  739. var xlsxfile *xlsx.File
  740. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  741. //c.File("c:/dd.xlsx")
  742. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  743. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  744. c.Header("Content-Transfer-Encoding", "binary")
  745. _ = xlsxfile.Write(c.Writer)
  746. } else {
  747. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  748. if err != nil {
  749. appG.Response(http.StatusOK, e.ERROR, err.Error())
  750. } else {
  751. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  752. if v, ok := value["id"]; ok {
  753. //month = "2020-03"
  754. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  755. if seviceplans != nil {
  756. for _, va := range seviceplans { //根据保养计划获取保养单
  757. //day,_ :=strconv.Atoi(va["day"])
  758. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  759. //buk := make(map[string]map[string]string)
  760. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  761. jstr := ""
  762. if bu["plantime"][8:9] == "0" {
  763. jstr = "m" + bu["plantime"][9:]
  764. } else {
  765. jstr = "m" + bu["plantime"][8:]
  766. }
  767. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  768. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  769. } else {
  770. if bu["flowCompeleted"] >= "2" {
  771. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  772. } else {
  773. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  774. }
  775. }
  776. }
  777. }
  778. }
  779. }
  780. }
  781. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  782. }
  783. }
  784. } else {
  785. appG.Response(http.StatusOK, e.SUCCESS, nil)
  786. }
  787. }
  788. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  789. // todo 优化性能 children统一查询
  790. // @Tags PostDataByNameForm
  791. // @Accept json
  792. // @Produce json
  793. // @Param sqlname query string true "sqlname"
  794. // @Param offset query int true "offset"
  795. // @Param pagecount query int true "pagecount"
  796. // @Param returntype query string true "returntype"
  797. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  798. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  799. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  800. func GetArrList(c *gin.Context) {
  801. appG := app.Gin{C: c}
  802. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  803. fsion := gofasion.NewFasion(string(dataByte))
  804. sqlnamestr := fsion.Get("name").ValueStr()
  805. sqlnamestr1 := fsion.Get("name1").ValueStr()
  806. offset := fsion.Get("offset").ValueDefaultInt(0)
  807. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  808. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  809. month := fsion.Get("month").ValueDefaultStr("map")
  810. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  811. tx := restful.Engine.NewSession()
  812. err := tx.Begin()
  813. defer func() {
  814. switch {
  815. case err != nil:
  816. if tx != nil {
  817. tx.Rollback()
  818. }
  819. default:
  820. if tx != nil {
  821. err = tx.Commit()
  822. }
  823. }
  824. if tx != nil {
  825. tx.Close()
  826. }
  827. }()
  828. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  829. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  830. if sql != "" {
  831. s_params := make([]interface{}, 0)
  832. if fsion.HasKey("parammaps") {
  833. parammaps := fsion.Get("parammaps")
  834. paramslist := strings.Split(p, ",")
  835. if len(paramslist) > 0 && p != "" {
  836. for _, value := range paramslist {
  837. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  838. if tempv, exists := c.Get("jwt_username"); exists {
  839. s_params = append(s_params, tempv.(string))
  840. } else {
  841. s_params = append(s_params, "")
  842. }
  843. } else {
  844. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  845. }
  846. }
  847. }
  848. }
  849. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  850. if err != nil {
  851. appG.Response(http.StatusOK, e.ERROR, err.Error())
  852. } else {
  853. paramslist1 := strings.Split(p1, ",")
  854. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  855. s_params1 := make([]interface{}, 0)
  856. if len(paramslist1) > 0 && p1 != "" {
  857. for _, v := range paramslist1 {
  858. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  859. }
  860. }
  861. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  862. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  863. }
  864. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  865. }
  866. } else {
  867. appG.Response(http.StatusOK, e.SUCCESS, nil)
  868. }
  869. }
  870. func GetAccount(c *gin.Context) {
  871. appG := app.Gin{C: c}
  872. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  873. fsion := gofasion.NewFasion(string(dataByte))
  874. sqlnamestr := fsion.Get("name").ValueStr()
  875. offset := fsion.Get("offset").ValueDefaultInt(0)
  876. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  877. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  878. tx := restful.Engine.NewSession()
  879. err := tx.Begin()
  880. defer func() {
  881. switch {
  882. case err != nil:
  883. logging.Error("tx.Begin 事务启动失败__error:", err)
  884. if tx != nil {
  885. tx.Rollback()
  886. }
  887. default:
  888. if tx != nil {
  889. err = tx.Commit()
  890. }
  891. }
  892. if tx != nil {
  893. tx.Close()
  894. }
  895. }()
  896. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  897. if sql != "" {
  898. s_params := make([]interface{}, 0)
  899. if fsion.HasKey("parammaps") {
  900. parammaps := fsion.Get("parammaps")
  901. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  902. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  903. }
  904. paramslist := strings.Split(p, ",")
  905. if len(paramslist) > 0 && p != "" {
  906. for _, value := range paramslist {
  907. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  908. if tempv, exists := c.Get("jwt_username"); exists {
  909. s_params = append(s_params, tempv.(string))
  910. } else {
  911. s_params = append(s_params, "")
  912. }
  913. } else {
  914. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  915. }
  916. }
  917. }
  918. } else if fsion.HasKey("params") {
  919. params := fsion.Get("params").Array()
  920. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  921. for _, v_params := range params {
  922. s_params = append(s_params, v_params.ValueStr())
  923. }
  924. }
  925. if returntype == "xlsx" {
  926. var xlsxfile *xlsx.File
  927. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  928. //c.File("c:/dd.xlsx")
  929. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  930. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  931. c.Header("Content-Transfer-Encoding", "binary")
  932. _ = xlsxfile.Write(c.Writer)
  933. } else {
  934. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  935. if err != nil {
  936. logging.Error("GetDataByName err: ", err)
  937. msg := geterrmsg(err.Error())
  938. appG.Response(http.StatusOK, e.ERROR, msg)
  939. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  940. } else {
  941. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  942. }
  943. }
  944. } else {
  945. appG.Response(http.StatusOK, e.SUCCESS, nil)
  946. }
  947. }
  948. // PostDataByName 根据APISQL表中SQL执行得到数据集
  949. // @Accept json
  950. // @Produce json
  951. // @Param sqlname query string true "sqlname"
  952. // @Param offset query int true "offset"
  953. // @Param pagecount query int true "pagecount"
  954. // @Param returntype query string true "returntype"
  955. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  956. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  957. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  958. // @Router /data/PostDataByName [POST]
  959. func PostDataByName(c *gin.Context) {
  960. appG := app.Gin{C: c}
  961. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  962. fsion := gofasion.NewFasion(string(dataByte))
  963. var err error
  964. queryData, err := module.PostDataByName(c, fsion)
  965. if err != nil {
  966. appG.Response(http.StatusOK, e.ERROR, err.Error())
  967. return
  968. }
  969. var (
  970. keyWord string
  971. )
  972. switch fsion.Get("name").ValueStr() {
  973. case "insertFeedclass":
  974. keyWord = "feed"
  975. err = module.GroupCategorySync(keyWord, fsion)
  976. case "deleteFeedclass":
  977. keyWord = "feed_delete"
  978. err = module.GroupCategoryDelete(keyWord, fsion)
  979. case "insertCowclass":
  980. keyWord = "cow"
  981. err = module.GroupCategorySync(keyWord, fsion)
  982. case "deleteCowclass":
  983. keyWord = "cow_delete"
  984. err = module.GroupCategoryDelete(keyWord, fsion)
  985. // case "updateFT":
  986. // FtdetailSurplus(fsion)
  987. // case "updateFeed":
  988. // FeedSurplus(fsion)
  989. default:
  990. }
  991. if err != nil {
  992. logging.Error(keyWord, err)
  993. }
  994. if queryData != nil {
  995. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  996. return
  997. }
  998. appG.Response(http.StatusOK, e.SUCCESS, nil)
  999. }
  1000. //人脸识别/格润富德接口
  1001. func GetRJSBData(c *gin.Context) {
  1002. appG := app.Gin{C: c}
  1003. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1004. fsion := gofasion.NewFasion(string(dataByte))
  1005. sqlnamestr := fsion.Get("name").ValueStr()
  1006. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1007. offset := fsion.Get("offset").ValueDefaultInt(0)
  1008. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1009. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1010. month := fsion.Get("month").ValueDefaultStr("map")
  1011. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1012. pagecount = 1
  1013. tx := restful.Engine.NewSession()
  1014. err := tx.Begin()
  1015. defer func() {
  1016. switch {
  1017. case err != nil:
  1018. if tx != nil {
  1019. tx.Rollback()
  1020. }
  1021. default:
  1022. if tx != nil {
  1023. err = tx.Commit()
  1024. }
  1025. }
  1026. if tx != nil {
  1027. tx.Close()
  1028. }
  1029. }()
  1030. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1031. _, 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 )
  1032. where id = (select tmrid from downloadedplan d where d.pid = (select pid from downloadedplan where lpplantype = 5 and mydate =
  1033. date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted= 0 ) and mydate = date_format(now() ,'%Y-%m-%d')
  1034. and lpplantype in(0,1)) `).Execute()
  1035. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1036. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1037. if sql != "" {
  1038. s_params := make([]interface{}, 0)
  1039. if fsion.HasKey("parammaps") {
  1040. parammaps := fsion.Get("parammaps")
  1041. paramslist := strings.Split(p, ",")
  1042. if len(paramslist) > 0 && p != "" {
  1043. for _, value := range paramslist {
  1044. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1045. if tempv, exists := c.Get("jwt_username"); exists {
  1046. s_params = append(s_params, tempv.(string))
  1047. } else {
  1048. s_params = append(s_params, "")
  1049. }
  1050. } else {
  1051. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1052. }
  1053. }
  1054. }
  1055. }
  1056. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1057. if err != nil {
  1058. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1059. } else {
  1060. paramslist1 := strings.Split(p1, ",")
  1061. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1062. s_params1 := make([]interface{}, 0)
  1063. if len(paramslist1) > 0 && p1 != "" {
  1064. for _, v := range paramslist1 {
  1065. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1066. }
  1067. }
  1068. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1069. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1070. }
  1071. var wg sync.WaitGroup
  1072. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1073. wg.Add(1)
  1074. go func(value map[string]interface{}) {
  1075. defer wg.Done()
  1076. // ,havebutton = 1
  1077. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1078. }(value)
  1079. }
  1080. wg.Wait()
  1081. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1082. }
  1083. fmt.Println("先锋获取数据:", time.Now(), queryData)
  1084. } else {
  1085. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1086. }
  1087. }
  1088. func PostRJSBData(c *gin.Context) {
  1089. appG := app.Gin{C: c}
  1090. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1091. fsion := gofasion.NewFasion(string(dataByte))
  1092. logging.Info("PostRJSBData err: ", string(dataByte))
  1093. s_params := make([]interface{}, 0)
  1094. tx := restful.Engine.NewSession()
  1095. err := tx.Begin()
  1096. defer func() {
  1097. switch {
  1098. case err != nil:
  1099. if tx != nil {
  1100. tx.Rollback()
  1101. }
  1102. default:
  1103. if tx != nil {
  1104. err = tx.Commit()
  1105. }
  1106. }
  1107. if tx != nil {
  1108. tx.Close()
  1109. }
  1110. }()
  1111. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1112. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1113. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1114. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1115. if !fsion.HasKey("parammaps") {
  1116. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1117. return
  1118. }
  1119. parammaps := fsion.Get("parammaps")
  1120. paramslist := strings.Split(p, ",")
  1121. if len(paramslist) > 0 && p != "" {
  1122. for _, value := range paramslist {
  1123. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1124. }
  1125. }
  1126. projuctid := parammaps.Get("projuctid").ValueStr()
  1127. _, err = tx.SQL(`update tmr set concentrate = (select d.id 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)) where id = (select tmrid from downloadedplan d
  1130. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1131. and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1132. if err != nil {
  1133. logging.Error("PostRJSBData-0 err: ", err)
  1134. msg := geterrmsg(err.Error())
  1135. // appG.Response(http.StatusOK, e.ERROR, msg)
  1136. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1137. return
  1138. }
  1139. _, err = tx.SQL(sql, s_params...).Execute()
  1140. if err != nil {
  1141. logging.Error("PostRJSBData err: ", err)
  1142. msg := geterrmsg(err.Error())
  1143. // appG.Response(http.StatusOK, e.ERROR, msg)
  1144. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1145. return
  1146. }
  1147. s_params = make([]interface{}, 0)
  1148. paramslist = strings.Split(p1, ",")
  1149. if len(paramslist) > 0 && p1 != "" {
  1150. for _, value := range paramslist {
  1151. // if value == "ID" {
  1152. // id := parammaps.Get("ID").ValueStr()
  1153. // pastureid := parammaps.Get("pastureid").ValueStr()
  1154. // 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
  1155. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1156. // if err != nil {
  1157. // logging.Error("PostRJSBData err: ", err)
  1158. // msg := geterrmsg(err.Error())
  1159. // appG.Response(http.StatusOK, e.ERROR, msg)
  1160. // return
  1161. // }
  1162. // for _, item := range datalist {
  1163. // id = item["id"]
  1164. // }
  1165. // s_params = append(s_params, id)
  1166. // } else {
  1167. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1168. // }
  1169. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1170. }
  1171. }
  1172. _, err = tx.SQL(sql1, s_params...).Execute()
  1173. if err != nil {
  1174. logging.Error("PostRJSBData1 err: ", err)
  1175. msg := geterrmsg(err.Error())
  1176. appG.Response(http.StatusOK, e.ERROR, msg)
  1177. return
  1178. }
  1179. s_params = make([]interface{}, 0)
  1180. paramslist = strings.Split(p2, ",")
  1181. if len(paramslist) > 0 && p2 != "" {
  1182. for _, value := range paramslist {
  1183. if value == "ID" {
  1184. id := parammaps.Get("ID").ValueStr()
  1185. pastureid := parammaps.Get("pastureid").ValueStr()
  1186. 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
  1187. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1188. if err != nil {
  1189. logging.Error("PostRJSBData err: ", err)
  1190. msg := geterrmsg(err.Error())
  1191. appG.Response(http.StatusOK, e.ERROR, msg)
  1192. return
  1193. }
  1194. for _, item := range datalist {
  1195. id = item["id"]
  1196. }
  1197. s_params = append(s_params, id)
  1198. } else {
  1199. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1200. }
  1201. }
  1202. }
  1203. _, err = tx.SQL(sql2, s_params...).Execute()
  1204. if err != nil {
  1205. logging.Error("PostRJSBData2 err: ", err)
  1206. msg := geterrmsg(err.Error())
  1207. appG.Response(http.StatusOK, e.ERROR, msg)
  1208. return
  1209. }
  1210. s_params = make([]interface{}, 0)
  1211. paramslist = strings.Split(p3, ",")
  1212. if len(paramslist) > 0 && p3 != "" {
  1213. for _, value := range paramslist {
  1214. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1215. }
  1216. }
  1217. _, err = tx.SQL(sql3, s_params...).Execute()
  1218. if err != nil {
  1219. logging.Error("PostRJSBData3 err: ", err)
  1220. msg := geterrmsg(err.Error())
  1221. appG.Response(http.StatusOK, e.ERROR, msg)
  1222. return
  1223. }
  1224. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1225. }
  1226. func PostRJSBDatas(c *gin.Context) {
  1227. appG := app.Gin{C: c}
  1228. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1229. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1230. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1231. fmt.Println("先锋回传数据:", time.Now(), string(dataByte))
  1232. tx := restful.Engine.NewSession()
  1233. err := tx.Begin()
  1234. defer func() {
  1235. switch {
  1236. case err != nil:
  1237. if tx != nil {
  1238. tx.Rollback()
  1239. }
  1240. default:
  1241. if tx != nil {
  1242. err = tx.Commit()
  1243. }
  1244. }
  1245. if tx != nil {
  1246. tx.Close()
  1247. }
  1248. }()
  1249. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1250. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1251. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1252. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1253. for _, fsion := range fsions {
  1254. if !fsion.HasKey("parammaps") {
  1255. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1256. return
  1257. }
  1258. parammaps := fsion.Get("parammaps")
  1259. ID := parammaps.Get("ID").ValueStr()
  1260. if ID == "" {
  1261. continue
  1262. }
  1263. s_params := make([]interface{}, 0)
  1264. paramslist := strings.Split(p, ",")
  1265. if len(paramslist) > 0 && p != "" {
  1266. for _, value := range paramslist {
  1267. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1268. }
  1269. }
  1270. _, err := tx.SQL(sql, s_params...).Execute()
  1271. if err != nil {
  1272. logging.Error("PostRJSBData err: ", err)
  1273. msg := geterrmsg(err.Error())
  1274. // appG.Response(http.StatusOK, e.ERROR, msg)
  1275. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1276. return
  1277. }
  1278. s_params = make([]interface{}, 0)
  1279. paramslist = strings.Split(p1, ",")
  1280. if len(paramslist) > 0 && p1 != "" {
  1281. for _, value := range paramslist {
  1282. // if value == "ID" {
  1283. // id := parammaps.Get("ID").ValueStr()
  1284. // pastureid := parammaps.Get("pastureid").ValueStr()
  1285. // 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
  1286. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1287. // if err != nil {
  1288. // logging.Error("PostRJSBData err: ", err)
  1289. // msg := geterrmsg(err.Error())
  1290. // appG.Response(http.StatusOK, e.ERROR, msg)
  1291. // return
  1292. // }
  1293. // for _, item := range datalist {
  1294. // id = item["id"]
  1295. // }
  1296. // s_params = append(s_params, id)
  1297. // } else {
  1298. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1299. // }
  1300. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1301. }
  1302. }
  1303. _, err = tx.SQL(sql1, s_params...).Execute()
  1304. if err != nil {
  1305. logging.Error("PostRJSBData1 err: ", err)
  1306. msg := geterrmsg(err.Error())
  1307. appG.Response(http.StatusOK, e.ERROR, msg)
  1308. return
  1309. }
  1310. s_params = make([]interface{}, 0)
  1311. paramslist = strings.Split(p2, ",")
  1312. if len(paramslist) > 0 && p2 != "" {
  1313. for _, value := range paramslist {
  1314. if value == "ID" {
  1315. id := parammaps.Get("ID").ValueStr()
  1316. pastureid := parammaps.Get("pastureid").ValueStr()
  1317. 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
  1318. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1319. if err != nil {
  1320. logging.Error("PostRJSBData err: ", err)
  1321. msg := geterrmsg(err.Error())
  1322. appG.Response(http.StatusOK, e.ERROR, msg)
  1323. return
  1324. }
  1325. for _, item := range datalist {
  1326. id = item["id"]
  1327. }
  1328. s_params = append(s_params, id)
  1329. } else {
  1330. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1331. }
  1332. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1333. }
  1334. }
  1335. _, err = tx.SQL(sql2, s_params...).Execute()
  1336. if err != nil {
  1337. logging.Error("PostRJSBData2 err: ", err)
  1338. msg := geterrmsg(err.Error())
  1339. appG.Response(http.StatusOK, e.ERROR, msg)
  1340. return
  1341. }
  1342. s_params = make([]interface{}, 0)
  1343. paramslist = strings.Split(p3, ",")
  1344. if len(paramslist) > 0 && p3 != "" {
  1345. for _, value := range paramslist {
  1346. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1347. }
  1348. }
  1349. _, err = tx.SQL(sql3, s_params...).Execute()
  1350. if err != nil {
  1351. logging.Error("PostRJSBData3 err: ", err)
  1352. msg := geterrmsg(err.Error())
  1353. appG.Response(http.StatusOK, e.ERROR, msg)
  1354. return
  1355. }
  1356. // ALTER TABLE `tmr`
  1357. // ADD COLUMN `concentrate` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 未回传 1 已回传' AFTER `appoint`
  1358. projuctid := parammaps.Get("projuctid").ValueStr()
  1359. _, err = tx.SQL(`update tmr set xianfeng = 0, concentrate = (select d.id 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)) where id = (select tmrid from downloadedplan d
  1362. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1363. and lpplantype in(0,1)) and ( select count(1) from downloadedplan where id = ? and iscompleted = 0 ) = 0 `,
  1364. projuctid, projuctid, projuctid, projuctid, projuctid).Execute()
  1365. if err != nil {
  1366. logging.Error("PostRJSBData-0 err: ", err)
  1367. msg := geterrmsg(err.Error())
  1368. // appG.Response(http.StatusOK, e.ERROR, msg)
  1369. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1370. return
  1371. }
  1372. count, _ := tx.SQL(`select count(1) from downloadedplan where id = ? and iscompleted = 0`, projuctid).Count()
  1373. if count == 0 {
  1374. fmt.Println(projuctid, "先锋回传计划已完成", count, err)
  1375. }
  1376. }
  1377. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1378. }
  1379. // @Summary 根据APISQL表中SQL执行得到数据集
  1380. // @Tags ExecDataByConfig
  1381. // @Accept json
  1382. // @Produce json
  1383. // @Param sqlname query string true "sqlname"
  1384. // @Param offset query int true "offset"
  1385. // @Param pagecount query int true "pagecount"
  1386. // @Param returntype query string true "returntype"
  1387. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1388. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1389. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1390. // @Router /data/PostDataByName [POST]
  1391. func ExecDataByConfig(c *gin.Context) {
  1392. appG := app.Gin{C: c}
  1393. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1394. tempval_ := make(map[string]interface{})
  1395. tempCommon := make(map[string]interface{})
  1396. tempval := make([]map[string]interface{}, 0)
  1397. err := json.Unmarshal(dataByte, &tempval_)
  1398. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1399. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1400. if err != nil {
  1401. } else {
  1402. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1403. tempCommon = v
  1404. }
  1405. if v, ok := tempval_["data"].([]interface{}); ok {
  1406. for _, Tvalue := range v {
  1407. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1408. tempval = append(tempval, v1)
  1409. }
  1410. }
  1411. }
  1412. tx := restful.Engine.NewSession()
  1413. err := tx.Begin()
  1414. if err != nil {
  1415. logging.Error("tx.Begin 事务启动失败__error:", err)
  1416. }
  1417. defer func() {
  1418. switch {
  1419. case err != nil:
  1420. if tx != nil {
  1421. tx.Rollback()
  1422. }
  1423. default:
  1424. if tx != nil {
  1425. err = tx.Commit()
  1426. }
  1427. }
  1428. if tx != nil {
  1429. tx.Close()
  1430. }
  1431. }()
  1432. if err == nil {
  1433. if tempv, exists := c.Get("jwt_username"); exists {
  1434. tempCommon["jwt_username"] = tempv.(string)
  1435. }
  1436. for _, paramvalue := range tempval {
  1437. fmt.Println(paramvalue["name"])
  1438. if paramvalue["name"].(string) == "updateBigFP" {
  1439. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1440. if err != nil {
  1441. msg := geterrmsg(err.Error())
  1442. appG.Response(http.StatusOK, e.ERROR, msg)
  1443. return
  1444. }
  1445. }
  1446. }
  1447. for _, paramvalue := range tempval {
  1448. if _, ok := paramvalue["resultname"]; !ok {
  1449. paramvalue["resultname"] = paramvalue["name"]
  1450. }
  1451. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1452. if err != nil {
  1453. logging.Error("ExecDataParam error:", err)
  1454. break
  1455. }
  1456. if paramvalue["name"].(string) == "createdownloadedplan" {
  1457. checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1458. }
  1459. }
  1460. if err == nil {
  1461. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1462. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1463. } else {
  1464. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1465. }
  1466. } else {
  1467. msg := geterrmsg(err.Error())
  1468. appG.Response(http.StatusOK, e.ERROR, msg)
  1469. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1470. }
  1471. }
  1472. }
  1473. if err != nil {
  1474. msg := geterrmsg(err.Error())
  1475. appG.Response(http.StatusOK, e.ERROR, msg)
  1476. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1477. }
  1478. }
  1479. func interfacetostring(val interface{}) string {
  1480. switch val.(type) {
  1481. case string:
  1482. ss := val.(string)
  1483. return ss
  1484. break
  1485. case int:
  1486. ss := val.(int)
  1487. return strconv.Itoa(ss)
  1488. break
  1489. case int64:
  1490. ss := val.(int64)
  1491. return strconv.FormatInt(ss, 10)
  1492. break
  1493. case float64:
  1494. ss := val.(float64)
  1495. return strconv.FormatFloat(ss, 'E', -1, 32)
  1496. break
  1497. }
  1498. return ""
  1499. }
  1500. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1501. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1502. tempstrb := strings.IndexAny(valuestring, "@")
  1503. tempstre := strings.IndexAny(valuestring, ".")
  1504. if tempstrb > -1 && tempstre > -1 {
  1505. for _, ParamMapList := range ParamMap {
  1506. if v, ok := ParamMapList["resultname"]; ok {
  1507. if v == valuestring[tempstrb+1:tempstre] {
  1508. if v1, ok := ParamMapList["resultmaps"]; ok {
  1509. if newA, ok := v1.([]map[string]interface{}); ok {
  1510. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1511. } else if newA, ok := v1.(map[string]interface{}); ok {
  1512. return interfacetostring(newA[valuestring[tempstre+1:]])
  1513. }
  1514. }
  1515. }
  1516. }
  1517. }
  1518. } else {
  1519. return valuestring
  1520. }
  1521. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1522. return fmt.Sprintf("%f", valuestring)
  1523. }
  1524. return ""
  1525. }
  1526. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1527. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1528. tempstrb := strings.IndexAny(valuestring, "@")
  1529. tempstre := strings.IndexAny(valuestring, ".")
  1530. if tempstrb > -1 && tempstre > -1 {
  1531. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1532. if s, ok := v.(string); ok {
  1533. return s
  1534. } else if s, ok := v.(float64); ok {
  1535. return strconv.FormatFloat(s, 'f', -1, 64)
  1536. // return strconv.FormatInt(int64(s), 10)
  1537. }
  1538. }
  1539. }
  1540. }
  1541. return ""
  1542. }
  1543. 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) {
  1544. sqlname := fasion["name"].(string)
  1545. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1546. if v, ok := fasion["type"]; ok {
  1547. sqltype = v.(string)
  1548. }
  1549. sql := ""
  1550. p := ""
  1551. s_params := make([]interface{}, 0)
  1552. if sqltype != "" {
  1553. sql, p = restful.GetSqlByName(sqlname, tx)
  1554. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1555. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1556. paramslist := strings.Split(p, ",")
  1557. if len(paramslist) > 0 && p != "" {
  1558. for _, value := range paramslist {
  1559. ss := ""
  1560. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1561. ids, err := setting.SnowIds.NextId()
  1562. if err != nil {
  1563. ids = time.Now().UnixNano()
  1564. logging.Info("create SnowIds err", err)
  1565. }
  1566. s_params = append(s_params, ids)
  1567. } else {
  1568. if ss == "" && CommonParamMap != nil {
  1569. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1570. ss = valuestring
  1571. tempstrb := strings.IndexAny(valuestring, "@")
  1572. tempstre := strings.IndexAny(valuestring, ".")
  1573. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1574. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1575. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1576. }
  1577. } else {
  1578. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1579. ss = ""
  1580. }
  1581. }
  1582. }
  1583. }
  1584. if ss == "" && ParentParamMap != nil {
  1585. ss = getParamValue_(v, value, ParentParamMap)
  1586. }
  1587. if ss == "" && sameParamMap != nil {
  1588. ss = getParamValue(v, value, sameParamMap)
  1589. }
  1590. if ss == "" && ParamMap != nil {
  1591. ss = getParamValue(v, value, ParamMap)
  1592. }
  1593. s_params = append(s_params, ss)
  1594. }
  1595. }
  1596. }
  1597. }
  1598. }
  1599. if sql == "" {
  1600. sqltype = ""
  1601. }
  1602. if sqltype == "s1" {
  1603. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1604. if v, ok := tempValParam.(map[string]interface{}); ok {
  1605. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1606. }
  1607. if err != nil {
  1608. return nil, err
  1609. }
  1610. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1611. if err != nil {
  1612. return nil, err
  1613. }
  1614. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1615. } else if sqltype == "sm" {
  1616. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1617. if v, ok := tempValParam.(map[string]interface{}); ok {
  1618. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1619. } else {
  1620. }
  1621. if err != nil {
  1622. return nil, err
  1623. }
  1624. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1625. if err != nil {
  1626. return nil, err
  1627. }
  1628. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1629. } else if sqltype == "v" {
  1630. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1631. if v, ok := tempValParam.(map[string]interface{}); ok {
  1632. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1633. } else {
  1634. }
  1635. if err != nil {
  1636. return nil, err
  1637. }
  1638. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1639. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1640. }
  1641. } else if sqltype == "e" {
  1642. tempVal_arrary := make([]map[string]interface{}, 0)
  1643. tempVal_map := make(map[string]interface{})
  1644. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1645. if err == nil {
  1646. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1647. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1648. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1649. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1650. return tempVal_arrary, err
  1651. }
  1652. return nil, err
  1653. } else {
  1654. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1655. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1656. if err != nil {
  1657. return nil, err
  1658. }
  1659. return nil, err
  1660. }
  1661. }
  1662. return nil, nil
  1663. }
  1664. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1665. var err error
  1666. subarray, ok := fasion["children"]
  1667. if ok {
  1668. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1669. tempVal_arrary := make([]map[string]interface{}, 0)
  1670. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1671. tempVal_ := make(map[string]interface{})
  1672. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1673. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1674. } else {
  1675. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1676. }
  1677. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1678. if err != nil {
  1679. return err
  1680. }
  1681. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1682. }
  1683. v.(map[string]interface{})["children"] = tempVal_arrary
  1684. }
  1685. }
  1686. return nil
  1687. }
  1688. // @Summary 删除图片
  1689. // @Tags RemovePicByName
  1690. // @Accept json
  1691. // @Produce json
  1692. // @Param sqlname query string true "sqlname"
  1693. // @Param offset query int true "offset"
  1694. // @Param pagecount query int true "pagecount"
  1695. // @Param returntype query string true "returntype"
  1696. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1697. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1698. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1699. // @Router /data/PostDataByName [POST]
  1700. func RemovePicByName(c *gin.Context) {
  1701. logging.Info("RemovePicByName ", c.Keys)
  1702. appG := app.Gin{C: c}
  1703. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1704. fsion := gofasion.NewFasion(string(dataByte))
  1705. sqlnamestr := fsion.Get("name").ValueStr()
  1706. picname := fsion.Get("picname").ValueStr()
  1707. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1708. params := fsion.Get("params").Array()
  1709. s_params := make([]interface{}, 0)
  1710. for _, v_params := range params {
  1711. s_params = append(s_params, v_params.ValueStr())
  1712. }
  1713. if sql != "" {
  1714. queryData, err := execDataBySql(sql, s_params)
  1715. if picname != "" {
  1716. // Destination
  1717. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1718. err := os.Remove(distPath) //删除文件test.txt
  1719. if err != nil {
  1720. //如果删除失败则输出 file remove Error!
  1721. fmt.Println("file remove Error!")
  1722. //输出错误详细信息
  1723. fmt.Printf("%s", err)
  1724. } else {
  1725. //如果删除成功则输出 file remove OK!
  1726. fmt.Print("file remove OK!")
  1727. }
  1728. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1729. err = os.Remove(distPath) //删除文件test.txt
  1730. if err != nil {
  1731. //如果删除失败则输出 file remove Error!
  1732. fmt.Println("file remove Error!")
  1733. //输出错误详细信息
  1734. fmt.Printf("%s", err)
  1735. } else {
  1736. //如果删除成功则输出 file remove OK!
  1737. fmt.Print("file remove OK!")
  1738. }
  1739. }
  1740. if err != nil {
  1741. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1742. } else {
  1743. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1744. }
  1745. } else {
  1746. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1747. }
  1748. }
  1749. // @Summary 删除文件
  1750. // @Tags RemoveFileByName
  1751. // @Accept json
  1752. // @Produce json
  1753. // @Param sqlname query string true "sqlname"
  1754. // @Param offset query int true "offset"
  1755. // @Param pagecount query int true "pagecount"
  1756. // @Param returntype query string true "returntype"
  1757. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1758. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1759. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1760. // @Router /data/PostDataByName [POST]
  1761. func RemoveFileByName(c *gin.Context) {
  1762. appG := app.Gin{C: c}
  1763. id := c.Param("id")
  1764. logging.Info("DownloadFile ", c.Keys, id)
  1765. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1766. if eqdoc == nil {
  1767. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1768. return
  1769. }
  1770. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1771. err = os.Remove(distPath) //删除文件test.txt
  1772. if err != nil {
  1773. //如果删除失败则输出 file remove Error!
  1774. fmt.Println("file remove Error!")
  1775. //输出错误详细信息
  1776. fmt.Printf("%s", err)
  1777. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1778. return
  1779. }
  1780. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1781. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1782. }
  1783. // @Summary 根据APISQL表中SQL执行得到数据集
  1784. // @Tags PostDataByName
  1785. // @Accept json
  1786. // @Produce json
  1787. // @Param sqlname query string true "sqlname"
  1788. // @Param offset query int true "offset"
  1789. // @Param pagecount query int true "pagecount"
  1790. // @Param returntype query string true "returntype"
  1791. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1792. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1793. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1794. // @Router /data/PostDataByName [POST]
  1795. func UpdateDataRelation(c *gin.Context) {
  1796. appG := app.Gin{C: c}
  1797. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1798. fsion := gofasion.NewFasion(string(dataByte))
  1799. tablename := fsion.Get("name").ValueStr()
  1800. dataname := fsion.Get("dataname").ValueStr()
  1801. datavalue := fsion.Get("datavalue").ValueStr()
  1802. valuename := fsion.Get("valuename").ValueStr()
  1803. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1804. values := fsion.Get("values").Array()
  1805. tx := restful.Engine.NewSession()
  1806. err := tx.Begin()
  1807. defer func() {
  1808. switch {
  1809. case err != nil:
  1810. if tx != nil {
  1811. tx.Rollback()
  1812. }
  1813. default:
  1814. if tx != nil {
  1815. err = tx.Commit()
  1816. }
  1817. }
  1818. if tx != nil {
  1819. tx.Close()
  1820. }
  1821. }()
  1822. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1823. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1824. d_params := make([]interface{}, 4)
  1825. d_params[0] = datavalue
  1826. s_params := ""
  1827. for _, v_values := range values {
  1828. d_params[1] = v_values.ValueStr()
  1829. if s_params == "" {
  1830. s_params = v_values.ValueStr()
  1831. } else {
  1832. s_params = s_params + "," + v_values.ValueStr()
  1833. }
  1834. d_params[2] = d_params[1]
  1835. d_params[3] = d_params[0]
  1836. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1837. if err != nil {
  1838. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1839. break
  1840. }
  1841. }
  1842. if s_params != "" {
  1843. deleteSqlstr := "delete from " + tablename + " " +
  1844. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1845. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1846. if err != nil {
  1847. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1848. } else if err == nil {
  1849. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1850. }
  1851. } else {
  1852. deleteSqlstr := "delete from " + tablename + " " +
  1853. " where " + dataname + " = " + datavalue
  1854. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1855. if err != nil {
  1856. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1857. } else if err == nil {
  1858. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1859. }
  1860. }
  1861. }
  1862. // @Summary 根据APISQL表中SQL执行得到数据集
  1863. // @Tags PostDatasByName
  1864. // @Accept json
  1865. // @Produce json
  1866. // @Param sqlname query string true "sqlname"
  1867. // @Param offset query int true "offset"
  1868. // @Param pagecount query int true "pagecount"
  1869. // @Param returntype query string true "returntype"
  1870. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1871. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1872. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1873. // @Router /data/PostDatasByName [POST]
  1874. func PostDataByNames(c *gin.Context) {
  1875. appG := app.Gin{C: c}
  1876. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1877. fsion := gofasion.NewFasion(string(dataByte))
  1878. sqlParams := fsion.Get("array").Array()
  1879. queryData := make(map[string]interface{})
  1880. for _, v := range sqlParams {
  1881. fsion2 := gofasion.NewFasion(v.Json())
  1882. ss := fsion2.Get("name")
  1883. aa := fsion2.Get("params")
  1884. fmt.Println(ss, aa)
  1885. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1886. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1887. if sql == "" {
  1888. errorm := make(map[string]interface{})
  1889. errorm["code"] = e.ERROR
  1890. errorm["message"] = "sql没有找到"
  1891. errorm["param"] = ""
  1892. queryData[fsion2.Get("name").ValueStr()] = errorm
  1893. continue
  1894. } else if sql != "" {
  1895. s_params := make([]interface{}, 0)
  1896. if fsion2.HasKey("parammaps") {
  1897. parammaps := fsion2.Get("parammaps")
  1898. paramslist := strings.Split(p, ",")
  1899. if len(paramslist) > 0 && p != "" {
  1900. for _, value := range paramslist {
  1901. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1902. if tempv, exists := c.Get("jwt_username"); exists {
  1903. s_params = append(s_params, tempv.(string))
  1904. } else {
  1905. s_params = append(s_params, "")
  1906. }
  1907. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1908. ids, err := setting.SnowIds.NextId()
  1909. if err != nil {
  1910. ids = time.Now().UnixNano()
  1911. logging.Info("create SnowIds err", err)
  1912. }
  1913. s_params = append(s_params, ids)
  1914. } else {
  1915. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1916. }
  1917. }
  1918. }
  1919. } else if fsion2.HasKey("params") {
  1920. params := fsion2.Get("params").Array()
  1921. //ids,err := setting.SnowIds.NextId()
  1922. //if err !=nil{
  1923. // ids = time.Now().UnixNano()
  1924. // logging.Info("create SnowIds err",err)
  1925. //}
  1926. //s_params = append(s_params, ids)
  1927. for _, v_params := range params {
  1928. s_params = append(s_params, v_params.ValueStr())
  1929. }
  1930. }
  1931. _, err := execDataBySql(sql, s_params)
  1932. if err != nil {
  1933. logging.Error("PostDataByName err: ", err)
  1934. errorm := make(map[string]interface{})
  1935. errorm["code"] = e.ERROR
  1936. errorm["message"] = err.Error()
  1937. errorm["param"] = s_params
  1938. queryData[fsion2.Get("name").ValueStr()] = errorm
  1939. continue
  1940. } else {
  1941. errorm := make(map[string]interface{})
  1942. errorm["code"] = e.SUCCESS
  1943. errorm["message"] = "success"
  1944. queryData[fsion2.Get("name").ValueStr()] = errorm
  1945. continue
  1946. }
  1947. } else {
  1948. errorm := make(map[string]interface{})
  1949. errorm["code"] = e.ERROR
  1950. errorm["message"] = "NO SQL"
  1951. errorm["param"] = ""
  1952. queryData[fsion2.Get("name").ValueStr()] = errorm
  1953. }
  1954. }
  1955. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1956. }
  1957. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1958. if offset > 0 {
  1959. offset = offset - 1
  1960. }
  1961. //if pagecount == 0 {
  1962. // pagecount = setting.AppSetting.PageSize
  1963. //}else if pagecount>setting.AppSetting.PageSize{
  1964. // pagecount = setting.AppSetting.PageSize
  1965. //}
  1966. if returntype == "list" {
  1967. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1968. return queryData, err
  1969. } else if returntype == "listlist" {
  1970. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1971. return queryData, err
  1972. } else {
  1973. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1974. return queryData, err
  1975. }
  1976. }
  1977. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1978. if offset > 0 {
  1979. offset = offset - 1
  1980. }
  1981. //if pagecount == 0 {
  1982. // pagecount = setting.AppSetting.PageSize
  1983. //}else if pagecount>setting.AppSetting.PageSize{
  1984. // pagecount = setting.AppSetting.PageSize
  1985. //}
  1986. if returntype == "list" {
  1987. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1988. return queryData, err
  1989. } else if returntype == "listlist" {
  1990. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1991. return queryData, err
  1992. } else {
  1993. fmt.Println(params)
  1994. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1995. return queryData, err
  1996. }
  1997. }
  1998. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1999. paramslist := strings.Split(Params, ",")
  2000. s_params := make([]interface{}, 0)
  2001. if isList {
  2002. for _, v_params := range thisParams["params"].([]interface{}) {
  2003. s_params = append(s_params, v_params)
  2004. }
  2005. } else {
  2006. paramslist := strings.Split(Params, ",")
  2007. if len(paramslist) > 0 && Params != "" {
  2008. for _, value := range paramslist {
  2009. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2010. }
  2011. }
  2012. }
  2013. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  2014. for _, queryData_ := range queryData {
  2015. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  2016. if isList {
  2017. if queryData_[idname] != nil {
  2018. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  2019. }
  2020. } else {
  2021. if queryData_[idname] != nil {
  2022. thisParams[idname] = queryData_[idname].(interface{})
  2023. }
  2024. if len(paramslist) > 0 && Params != "" {
  2025. s_params = make([]interface{}, 0)
  2026. for _, value := range paramslist {
  2027. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2028. }
  2029. }
  2030. }
  2031. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  2032. } else {
  2033. }
  2034. }
  2035. return queryData, err
  2036. }
  2037. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2038. queryData, err := restful.ExecQuery(sqlstr, params)
  2039. return queryData, err
  2040. }
  2041. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2042. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2043. return queryData, err
  2044. }
  2045. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2046. queryData, err := restful.ExecQuery(sqlstr, params)
  2047. return queryData, err
  2048. }
  2049. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2050. // @Tags ImportExcel
  2051. // @Accept json
  2052. // @Produce json
  2053. // @Param file query string true "文件名"
  2054. // @Param name header string true "执行sql的名字"
  2055. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2056. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2057. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2058. // @Router /data/ImportExcel [POST]
  2059. func ImportExcel(c *gin.Context) {
  2060. appG := app.Gin{C: c}
  2061. inputdata := ""
  2062. c.Request.ParseForm()
  2063. params := c.Request.Form
  2064. file, _, err := c.Request.FormFile("file")
  2065. if err != nil {
  2066. appG.Response(http.StatusOK, e.ERROR, err)
  2067. return
  2068. }
  2069. sqlnamestrs := params.Get("name")
  2070. sheetname := params.Get("sheetname")
  2071. pastureid := params.Get("pastureid")
  2072. //importParams := params.Get("importParams")
  2073. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2074. // 必输项参数 (字符串格式 "field1,field2,field3")
  2075. requiredParams := params.Get("requiredParams")
  2076. // 日期参数
  2077. dateParams := params.Get("dateParams")
  2078. // 数字参数
  2079. numParams := params.Get("numParams")
  2080. //将字符串分割开
  2081. dateParamslist := strings.Split(dateParams, ",")
  2082. requiredParamslist := strings.Split(requiredParams, ",")
  2083. numParamslist := strings.Split(numParams, ",")
  2084. queryData := make([]interface{}, 0)
  2085. sqlslist := strings.Split(sqlnamestrs, ",")
  2086. xlsx1, err := excelize.OpenReader(file)
  2087. if err != nil {
  2088. fmt.Println(err)
  2089. return
  2090. }
  2091. ok := 0
  2092. error := 0
  2093. isdone := true
  2094. rows := xlsx1.GetRows(sheetname)
  2095. // 限制10000条,多余的截取掉
  2096. if len(rows) > 10000 {
  2097. rows = rows[:10000]
  2098. }
  2099. for i, row := range rows {
  2100. if i > 0 {
  2101. entry := make(map[string]interface{})
  2102. outentry := make(map[string]interface{})
  2103. for j, colCell := range rows[0] {
  2104. for k, colCell1 := range row {
  2105. if j == k {
  2106. outentry[colCell] = colCell1
  2107. entry[colCell] = colCell1
  2108. }
  2109. }
  2110. }
  2111. inputdata = ""
  2112. a := ""
  2113. fmt.Println(outentry, entry)
  2114. //校验日期格式
  2115. for _, v := range dateParamslist {
  2116. if v == "" {
  2117. continue
  2118. }
  2119. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2120. dtime, err := TransfTime(d.(string))
  2121. if err != nil {
  2122. a = strings.Trim(v, " ")
  2123. break
  2124. }
  2125. outentry[strings.Trim(v, " ")] = dtime
  2126. }
  2127. }
  2128. if a != "" {
  2129. outentry["error_msg"] = a + " 格式错误"
  2130. error++
  2131. queryData = append(queryData, outentry)
  2132. continue
  2133. }
  2134. a = ""
  2135. //校验必填格式
  2136. for _, v := range requiredParamslist {
  2137. if v == "" {
  2138. continue
  2139. }
  2140. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2141. a = strings.Trim(v, " ")
  2142. break
  2143. }
  2144. }
  2145. if a != "" {
  2146. outentry["error_msg"] = a + " 未填或格式错误"
  2147. error++
  2148. queryData = append(queryData, outentry)
  2149. continue
  2150. }
  2151. a = ""
  2152. //校验数字格式
  2153. for _, v := range numParamslist {
  2154. if v == "" {
  2155. continue
  2156. }
  2157. d, ok := outentry[strings.Trim(v, " ")]
  2158. if !ok || d == "" {
  2159. outentry[strings.Trim(v, " ")] = 0
  2160. } else {
  2161. var fl float64
  2162. switch d.(type) {
  2163. case string:
  2164. fl, err = strconv.ParseFloat(d.(string), 64)
  2165. }
  2166. if err != nil || fl < 0 {
  2167. a = strings.Trim(v, " ")
  2168. break
  2169. }
  2170. }
  2171. }
  2172. if a != "" {
  2173. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2174. error++
  2175. queryData = append(queryData, outentry)
  2176. continue
  2177. }
  2178. tx := restful.Engine.NewSession()
  2179. err := tx.Begin()
  2180. for _, sqlnamestr := range sqlslist {
  2181. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2182. paramslist := strings.Split(paramslists, ",")
  2183. if len(paramslist) > 0 {
  2184. s_params := make([]interface{}, 0)
  2185. for _, value := range paramslist {
  2186. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2187. if tempv, exists := c.Get("jwt_username"); exists {
  2188. s_params = append(s_params, tempv.(string))
  2189. } else {
  2190. s_params = append(s_params, "")
  2191. }
  2192. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2193. s_params = append(s_params, pastureid)
  2194. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2195. ids, err := setting.SnowIds.NextId()
  2196. if err != nil {
  2197. ids = time.Now().UnixNano()
  2198. logging.Info("create SnowIds err", err)
  2199. }
  2200. s_params = append(s_params, ids)
  2201. } else {
  2202. if outentry[strings.Trim(value, " ")] == nil {
  2203. s_params = append(s_params, "")
  2204. } else {
  2205. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2206. }
  2207. }
  2208. }
  2209. outentry["input"] = inputdata
  2210. fmt.Println(sql, s_params)
  2211. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2212. if err != nil {
  2213. if tx != nil {
  2214. tx.Rollback()
  2215. }
  2216. if tx != nil {
  2217. tx.Close()
  2218. }
  2219. msg := geterrmsg(err.Error())
  2220. outentry["error_msg"] = msg
  2221. error++
  2222. queryData = append(queryData, outentry)
  2223. isdone = true
  2224. break
  2225. } else {
  2226. if len(returnmsgmap1) > 0 {
  2227. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2228. if tx != nil {
  2229. tx.Rollback()
  2230. }
  2231. if tx != nil {
  2232. tx.Close()
  2233. }
  2234. msg := geterrmsg(va.(string))
  2235. outentry["error_msg"] = msg
  2236. error++
  2237. queryData = append(queryData, outentry)
  2238. isdone = true
  2239. break
  2240. }
  2241. }
  2242. isdone = false
  2243. }
  2244. }
  2245. }
  2246. switch {
  2247. case err != nil:
  2248. if tx != nil {
  2249. tx.Rollback()
  2250. }
  2251. default:
  2252. if tx != nil {
  2253. err = tx.Commit()
  2254. }
  2255. }
  2256. if tx != nil {
  2257. tx.Close()
  2258. }
  2259. }
  2260. if !isdone {
  2261. ok++
  2262. isdone = true
  2263. }
  2264. }
  2265. data := make(map[string]interface{})
  2266. data["result"] = queryData
  2267. data["success"] = ok
  2268. data["err_count"] = error
  2269. appG.Response(http.StatusOK, e.SUCCESS, data)
  2270. }
  2271. func TransfTime(timestr string) (string, error) {
  2272. if timestr == "" {
  2273. return time.Now().Format("2006-01-02"), nil
  2274. }
  2275. days, err := strconv.Atoi(timestr)
  2276. if err != nil {
  2277. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2278. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2279. }
  2280. _, 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. t, err := time.Parse("2006.01.02", timestr)
  2285. if err != nil {
  2286. return "", err
  2287. } else {
  2288. return t.Format("2006-01-02"), nil
  2289. }
  2290. } else {
  2291. return t.Format("2006-01-02"), nil
  2292. }
  2293. } else {
  2294. return timestr, nil
  2295. }
  2296. }
  2297. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2298. times = times.AddDate(0, 0, days)
  2299. return times.Format("2006-01-02"), nil
  2300. }
  2301. func Createchart(c *gin.Context) {
  2302. appG := app.Gin{C: c}
  2303. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2304. fsion := gofasion.NewFasion(string(dataByte))
  2305. chart_name := fsion.Get("chart_name").ValueStr()
  2306. desc := fsion.Get("desc").ValueStr()
  2307. pastureid := fsion.Get("pastureid").ValueStr()
  2308. source_id := fsion.Get("source_id").ValueStr()
  2309. emp := fsion.Get("emp").ValueStr()
  2310. content := fsion.Get("content").Json()
  2311. var mapResult map[string]interface{}
  2312. err1 := json.Unmarshal([]byte(content), &mapResult)
  2313. if err1 != nil {
  2314. fmt.Println("JsonToMapDemo err: ", err1)
  2315. }
  2316. tx := restful.Engine.NewSession()
  2317. err := tx.Begin()
  2318. defer func() {
  2319. switch {
  2320. case err != nil:
  2321. logging.Error("tx.Begin 事务启动失败__error:", err)
  2322. if tx != nil {
  2323. tx.Rollback()
  2324. }
  2325. default:
  2326. if tx != nil {
  2327. err = tx.Commit()
  2328. }
  2329. }
  2330. if tx != nil {
  2331. tx.Close()
  2332. }
  2333. }()
  2334. ids, err := setting.SnowIds.NextId()
  2335. if err != nil {
  2336. ids = time.Now().UnixNano()
  2337. logging.Info("create SnowIds err", err)
  2338. }
  2339. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2340. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2341. if err != nil {
  2342. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2343. } else {
  2344. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2345. }
  2346. }
  2347. func Updatedashboard(c *gin.Context) {
  2348. appG := app.Gin{C: c}
  2349. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2350. fsion := gofasion.NewFasion(string(dataByte))
  2351. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2352. pastureid := fsion.Get("pastureid").ValueStr()
  2353. content := fsion.Get("content").Json()
  2354. var mapResult map[string]interface{}
  2355. err1 := json.Unmarshal([]byte(content), &mapResult)
  2356. if err1 != nil {
  2357. fmt.Println("JsonToMapDemo err: ", err1)
  2358. }
  2359. layout := mapResult["layout"]
  2360. tx := restful.Engine.NewSession()
  2361. err := tx.Begin()
  2362. defer func() {
  2363. switch {
  2364. case err != nil:
  2365. logging.Error("tx.Begin 事务启动失败__error:", err)
  2366. if tx != nil {
  2367. tx.Rollback()
  2368. }
  2369. default:
  2370. if tx != nil {
  2371. err = tx.Commit()
  2372. }
  2373. }
  2374. if tx != nil {
  2375. tx.Close()
  2376. }
  2377. }()
  2378. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2379. if err != nil {
  2380. println("2", err.Error())
  2381. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2382. } else {
  2383. if exec != nil {
  2384. if exec[0]["content"] == nil {
  2385. mapR := make(map[string]interface{})
  2386. mapR["layout"] = layout
  2387. mjson, _ := json.Marshal(mapR)
  2388. mString := string(mjson)
  2389. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2390. if err3 != nil {
  2391. println("3", err3.Error())
  2392. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2393. } else {
  2394. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2395. }
  2396. } else {
  2397. var mapR map[string]interface{}
  2398. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2399. if err1 != nil {
  2400. fmt.Println("JsonToMapDemo err: ", err2)
  2401. }
  2402. mapR["layout"] = layout
  2403. mjson, _ := json.Marshal(mapR)
  2404. mString := string(mjson)
  2405. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2406. if err3 != nil {
  2407. println("3", err3.Error())
  2408. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2409. } else {
  2410. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2411. }
  2412. }
  2413. } else {
  2414. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2415. }
  2416. }
  2417. }
  2418. func ExecSQL(c *gin.Context) {
  2419. appG := app.Gin{C: c}
  2420. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2421. fsion := gofasion.NewFasion(string(dataByte))
  2422. content := fsion.Get("content").Json()
  2423. pastureid := fsion.Get("pastureid").ValueStr()
  2424. var mapResult map[string]interface{}
  2425. err1 := json.Unmarshal([]byte(content), &mapResult)
  2426. if err1 != nil {
  2427. fmt.Println("JsonToMapDemo err: ", err1)
  2428. }
  2429. sqlstr := "select "
  2430. groupstr := " GROUP BY "
  2431. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2432. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2433. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2434. }
  2435. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2436. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2437. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2438. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2439. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2440. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2441. sqlstr = sqlstr + tem + ","
  2442. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2443. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2444. sqlstr = sqlstr + tem + ","
  2445. } else {
  2446. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2447. sqlstr = sqlstr + tem + ","
  2448. }
  2449. }
  2450. if _, ok := mapResult["selectedCalcul2"]; ok {
  2451. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2452. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2453. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2454. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2455. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2456. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2457. sqlstr = sqlstr + tem + ","
  2458. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2459. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2460. sqlstr = sqlstr + tem + ","
  2461. } else {
  2462. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2463. sqlstr = sqlstr + tem + ","
  2464. }
  2465. }
  2466. }
  2467. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2468. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2469. sqlstr = sqlstr + " where pastureid=" + pastureid
  2470. if len(mapResult["filters"].([]interface{})) > 0 {
  2471. sqlstr = sqlstr + " and "
  2472. }
  2473. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2474. for _, value := range mapResult["filters"].([]interface{}) {
  2475. switch value.(map[string]interface{})["filterOperator"].(string) {
  2476. case ">", "=", "<", ">=", "<=", "!=", "like":
  2477. 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 "
  2478. case "IN":
  2479. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2480. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2481. sqlstr = sqlstr + value1.(string) + ","
  2482. }
  2483. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2484. sqlstr = sqlstr + ")" + " AND "
  2485. case "BETWEEN":
  2486. 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 "
  2487. }
  2488. }
  2489. if len(mapResult["filters"].([]interface{})) > 0 {
  2490. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2491. }
  2492. //
  2493. groupstr = groupstr[0 : len(groupstr)-1]
  2494. sqlstr = sqlstr + groupstr + " "
  2495. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2496. sqlstr = sqlstr + " order by "
  2497. }
  2498. //
  2499. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2500. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2501. sqlstr = sqlstr + value.(string) + " "
  2502. } else {
  2503. sqlstr = sqlstr + value.(string) + ","
  2504. }
  2505. }
  2506. //
  2507. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2508. tx := restful.Engine.NewSession()
  2509. err := tx.Begin()
  2510. defer func() {
  2511. switch {
  2512. case err != nil:
  2513. logging.Error("tx.Begin 事务启动失败__error:", err)
  2514. if tx != nil {
  2515. tx.Rollback()
  2516. }
  2517. default:
  2518. if tx != nil {
  2519. err = tx.Commit()
  2520. }
  2521. }
  2522. if tx != nil {
  2523. tx.Close()
  2524. }
  2525. }()
  2526. exec, err := tx.SQL(sqlstr).Query().List()
  2527. if err != nil {
  2528. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2529. } else {
  2530. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2531. }
  2532. }
  2533. func Dashboards(c *gin.Context) {
  2534. appG := app.Gin{C: c}
  2535. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2536. fsion := gofasion.NewFasion(string(dataByte))
  2537. sqlnamestr := fsion.Get("name").ValueStr()
  2538. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2539. offset := fsion.Get("offset").ValueDefaultInt(0)
  2540. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2541. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2542. month := fsion.Get("month").ValueDefaultStr("map")
  2543. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2544. tx := restful.Engine.NewSession()
  2545. err := tx.Begin()
  2546. defer func() {
  2547. switch {
  2548. case err != nil:
  2549. if tx != nil {
  2550. tx.Rollback()
  2551. }
  2552. default:
  2553. if tx != nil {
  2554. err = tx.Commit()
  2555. }
  2556. }
  2557. if tx != nil {
  2558. tx.Close()
  2559. }
  2560. }()
  2561. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2562. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2563. if sql != "" {
  2564. s_params := make([]interface{}, 0)
  2565. if fsion.HasKey("parammaps") {
  2566. parammaps := fsion.Get("parammaps")
  2567. paramslist := strings.Split(p, ",")
  2568. if len(paramslist) > 0 && p != "" {
  2569. for _, value := range paramslist {
  2570. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2571. if tempv, exists := c.Get("jwt_username"); exists {
  2572. s_params = append(s_params, tempv.(string))
  2573. } else {
  2574. s_params = append(s_params, "")
  2575. }
  2576. } else {
  2577. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2578. }
  2579. }
  2580. }
  2581. }
  2582. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2583. if err != nil {
  2584. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2585. } else {
  2586. //paramslist1 := strings.Split(p1, ",")
  2587. dids := make([]interface{}, 0)
  2588. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2589. var mapResult map[string]interface{}
  2590. dids = append(dids, value["dashboard_id"])
  2591. if value["content"] != nil {
  2592. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2593. if err1 != nil {
  2594. println("JsonToMapDemo1 err: ", err1)
  2595. }
  2596. temap := make(map[string]interface{})
  2597. tem := mapResult["layout"].([]interface{})
  2598. if v, ok := value["chartids"]; ok {
  2599. chartids := strings.Split(v.(string), ",")
  2600. for _, va := range chartids {
  2601. a := false
  2602. for _, v2 := range tem {
  2603. if v2.(map[string]interface{})["id"].(string) == va {
  2604. a = true
  2605. //println("va1======",va)
  2606. }
  2607. }
  2608. if !a {
  2609. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2610. va + "\",\"id\":\"" + va +
  2611. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2612. var mapTem map[string]interface{}
  2613. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2614. if err1 != nil {
  2615. println("JsonToMapDemo err: ", err1)
  2616. }
  2617. tem = append(tem, mapTem)
  2618. }
  2619. }
  2620. temap["layout"] = tem
  2621. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2622. }
  2623. } else {
  2624. temap := make(map[string]interface{})
  2625. tem := make([]interface{}, 0)
  2626. if v, ok := value["chartids"]; ok {
  2627. chartids := strings.Split(v.(string), ",")
  2628. for _, va := range chartids {
  2629. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2630. va + "\",\"id\":\"" + va +
  2631. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2632. var mapTem map[string]interface{}
  2633. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2634. if err1 != nil {
  2635. println("JsonToMapDemo err: ", err1)
  2636. }
  2637. tem = append(tem, mapTem)
  2638. }
  2639. temap["layout"] = tem
  2640. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2641. }
  2642. }
  2643. }
  2644. queryData.(map[string]interface{})["order"] = dids
  2645. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2646. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2647. }
  2648. } else {
  2649. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2650. }
  2651. }
  2652. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2653. fsion := gofasion.NewFasion(parammaps)
  2654. sqlnamestr := fsion.Get("name").ValueStr()
  2655. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2656. offset := fsion.Get("offset").ValueDefaultInt(0)
  2657. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2658. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2659. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2660. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2661. body := []byte("")
  2662. if sql != "" {
  2663. s_params := make([]interface{}, 0)
  2664. if fsion.HasKey("parammaps") {
  2665. parammaps := fsion.Get("parammaps")
  2666. paramslist := strings.Split(p, ",")
  2667. if len(paramslist) > 0 && p != "" {
  2668. for _, value := range paramslist {
  2669. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2670. }
  2671. }
  2672. }
  2673. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2674. if err != nil {
  2675. } else {
  2676. paramslist1 := strings.Split(p1, ",")
  2677. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2678. s_params1 := make([]interface{}, 0)
  2679. if len(paramslist1) > 0 && p1 != "" {
  2680. for _, v := range paramslist1 {
  2681. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2682. }
  2683. }
  2684. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2685. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2686. body, _ = json.Marshal(queryData)
  2687. }
  2688. }
  2689. }
  2690. bs := bytes.NewBuffer(body)
  2691. client := &http.Client{}
  2692. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2693. req, err := http.NewRequest(RequestMethod,
  2694. url,
  2695. bs,
  2696. )
  2697. if err != nil {
  2698. }
  2699. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2700. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2701. if err != nil {
  2702. // handle error
  2703. }
  2704. resp, err := client.Do(req)
  2705. if err != nil {
  2706. return ""
  2707. }
  2708. defer resp.Body.Close()
  2709. result_body, err := ioutil.ReadAll(resp.Body)
  2710. if err != nil {
  2711. return ""
  2712. }
  2713. fmt.Println(string(result_body))
  2714. return ""
  2715. }
  2716. func GetSummary(c *gin.Context) {
  2717. appG := app.Gin{C: c}
  2718. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2719. fsion := gofasion.NewFasion(string(dataByte))
  2720. offset := fsion.Get("offset").ValueDefaultInt(0)
  2721. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2722. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2723. parammaps := fsion.Get("parammaps")
  2724. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2725. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2726. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2727. tx := restful.Engine.NewSession()
  2728. defer tx.Close()
  2729. sqlnamestr := ""
  2730. if genre == "0" {
  2731. if status == "0" {
  2732. sqlnamestr = "getAccuracyJSY"
  2733. } else if status == "1" {
  2734. sqlnamestr = "getAccuracyHFT"
  2735. } else if status == "2" {
  2736. sqlnamestr = "getAccuracyHNS"
  2737. } else if status == "3" {
  2738. sqlnamestr = "getAccuracyHSC"
  2739. } else if status == "4" {
  2740. sqlnamestr = "getAccuracyHCC"
  2741. } else if status == "5" {
  2742. sqlnamestr = "getAccuracyMC"
  2743. } else if status == "6" {
  2744. sqlnamestr = "getAccuracyFeedHL"
  2745. } else if status == "7" {
  2746. sqlnamestr = "getAccuracyRT"
  2747. }
  2748. } else {
  2749. if status == "0" {
  2750. sqlnamestr = "getAccuracySCCJSY"
  2751. } else if status == "1" {
  2752. sqlnamestr = "getAccuracySFT"
  2753. } else if status == "2" {
  2754. sqlnamestr = "getAccuracySNS"
  2755. } else if status == "3" {
  2756. sqlnamestr = "getAccuracySSC"
  2757. } else if status == "4" {
  2758. sqlnamestr = "getAccuracySCC"
  2759. } else if status == "5" {
  2760. sqlnamestr = "getAccuracySLCL"
  2761. } else if status == "7" {
  2762. sqlnamestr = "getAccuracySCCRT"
  2763. }
  2764. }
  2765. if isDate == "1" {
  2766. sqlnamestr += "Date"
  2767. }
  2768. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2769. // fmt.Println(sqlnamestr, sql)
  2770. if sql != "" {
  2771. s_params := make([]interface{}, 0)
  2772. // if fsion.HasKey("parammaps") {
  2773. fmt.Println(s_params, "222", p)
  2774. paramslist := strings.Split(p, ",")
  2775. if len(paramslist) > 0 && p != "" {
  2776. for _, value := range paramslist {
  2777. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2778. if tempv, exists := c.Get("jwt_username"); exists {
  2779. s_params = append(s_params, tempv.(string))
  2780. } else {
  2781. s_params = append(s_params, "")
  2782. }
  2783. } else {
  2784. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2785. }
  2786. }
  2787. }
  2788. if returntype == "xlsx" {
  2789. var xlsxfile *xlsx.File
  2790. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2791. //c.File("c:/dd.xlsx")
  2792. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2793. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2794. c.Header("Content-Transfer-Encoding", "binary")
  2795. _ = xlsxfile.Write(c.Writer)
  2796. } else {
  2797. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2798. if err != nil {
  2799. logging.Error("GetDataByName err: ", err)
  2800. msg := geterrmsg(err.Error())
  2801. appG.Response(http.StatusOK, e.ERROR, msg)
  2802. } else {
  2803. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2804. }
  2805. }
  2806. } else {
  2807. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2808. }
  2809. }
  2810. // type lpplanStruct struct {
  2811. // Id int64 `xorm:"id"`
  2812. // Tmrname string `xorm:"tmrname"`
  2813. // Tmrid int64 `xorm:"tmrid"`
  2814. // Sort int64 `xorm:"sort"`
  2815. // Sel int64 `xorm:"sel"`
  2816. // Times int64 `xorm:"times"`
  2817. // Ftname string `xorm:"ftname"`
  2818. // Ftid int64 `xorm:"ftid"`
  2819. // Maxweight float64 `xorm:"maxweight"`
  2820. // Sumweight float64 `xorm:"sumweight"`
  2821. // Sumcowcount int64 `xorm:"sumcowcount"`
  2822. // Pastureid string `xorm:"pastureid"`
  2823. // Display string `xorm:"display"`
  2824. // Issplit int64 `xorm:"issplit"`
  2825. // BeginTime string `xorm:"begintime"`
  2826. // }
  2827. func UpdateFTdetail(c *gin.Context) {
  2828. appG := app.Gin{C: c}
  2829. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2830. tempval_ := make(map[string]interface{})
  2831. tempCommon := make(map[string]interface{})
  2832. tempval := make([]map[string]interface{}, 0)
  2833. fTChange := make(map[string]interface{}, 0)
  2834. // fpdOldDataList := make([]map[string]interface{}, 0)
  2835. // fpdDataList := make([]map[string]interface{}, 0)
  2836. fsion := gofasion.NewFasion(string(dataByte))
  2837. // parammaps := fsion.Get("parammaps")
  2838. createdate := time.Now().Format("2006-01-02 15:04:05")
  2839. err := json.Unmarshal(dataByte, &tempval_)
  2840. if err != nil {
  2841. appG.Response(http.StatusOK, e.ERROR, false)
  2842. return
  2843. }
  2844. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2845. tx := restful.Engine.NewSession()
  2846. if v, ok := tempval_["data"].([]interface{}); ok {
  2847. for _, Tvalue := range v {
  2848. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2849. if v1["name"] == "updateFPbyFTChange" {
  2850. fTChange = v1
  2851. continue
  2852. }
  2853. tempval = append(tempval, v1)
  2854. }
  2855. }
  2856. }
  2857. parammaps := fTChange["parammaps"].(map[string]interface{})
  2858. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2859. // if err != nil {
  2860. // logs.Error(err)
  2861. // appG.Response(http.StatusOK, e.ERROR, false)
  2862. // return
  2863. // }
  2864. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2865. // if err != nil {
  2866. // logs.Error(err)
  2867. // appG.Response(http.StatusOK, e.ERROR, false)
  2868. // return
  2869. // }
  2870. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2871. // if err != nil {
  2872. // logs.Error(err)
  2873. // appG.Response(http.StatusOK, e.ERROR, false)
  2874. // return
  2875. // }
  2876. err = tx.Begin()
  2877. if err != nil {
  2878. logging.Error("tx.Begin 事务启动失败__error:", err)
  2879. }
  2880. defer func() {
  2881. if err != nil {
  2882. if tx != nil {
  2883. tx.Rollback()
  2884. }
  2885. }
  2886. if tx != nil {
  2887. tx.Close()
  2888. }
  2889. }()
  2890. if err != nil {
  2891. } else {
  2892. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2893. tempCommon = v
  2894. }
  2895. // 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 ,
  2896. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2897. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2898. // UNION
  2899. // 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 ,
  2900. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2901. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2902. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2903. if err == nil {
  2904. if tempv, exists := c.Get("jwt_username"); exists {
  2905. tempCommon["jwt_username"] = tempv.(string)
  2906. }
  2907. for _, paramvalue := range tempval {
  2908. if _, ok := paramvalue["resultname"]; !ok {
  2909. paramvalue["resultname"] = paramvalue["name"]
  2910. }
  2911. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2912. if err != nil {
  2913. logging.Error("ExecDataParam error:", err)
  2914. break
  2915. }
  2916. }
  2917. if err != nil {
  2918. msg := geterrmsg(err.Error())
  2919. appG.Response(http.StatusOK, e.ERROR, msg)
  2920. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2921. }
  2922. }
  2923. }
  2924. tx.Commit()
  2925. // go func() {
  2926. if fTChange != nil {
  2927. parammaps := fTChange["parammaps"].(map[string]interface{})
  2928. if parammaps["type"].(float64) == 1 {
  2929. _, err = tx.SQL(`UPDATE feedp fp
  2930. set
  2931. ccountratio = ccount *(ratio /100 ),
  2932. fp.ftweight= IFNULL(IF(
  2933. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2934. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2935. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2936. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2937. ),0),fp.feedweight = IFNULL(IF(
  2938. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2939. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2940. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2941. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2942. ),0) +ifnull(fp.supplyweight,0)
  2943. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2944. _, err = tx.SQL(`UPDATE fpdetail fpd
  2945. INNER JOIN feedp fp
  2946. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2947. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2948. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2949. } else {
  2950. _, err = tx.SQL(`UPDATE feedp fp
  2951. SET ccountratio = ccount *(ratio /100 ),
  2952. fp.supplyweight= IFNULL(IF(
  2953. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2954. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2955. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2956. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2957. ),0),fp.feedweight = IFNULL(IF(
  2958. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2959. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2960. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2961. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2962. ),0) +ifnull(fp.supplyweight,0)
  2963. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2964. _, err = tx.SQL(`UPDATE fpdetail fpd
  2965. INNER JOIN feedp fp
  2966. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2967. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2968. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2969. }
  2970. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  2971. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  2972. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  2973. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  2974. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  2975. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  2976. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  2977. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  2978. join feedtemplet ft on ft.id = fp.ftid where ft.id = ?`, parammaps["ftid"]).QueryString()
  2979. // fmt.Println(ftId)
  2980. FpdBatchEditGrfd(fmt.Sprintf("%v", parammaps["pastureid"]), values1)
  2981. // 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 ,
  2982. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2983. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2984. // UNION
  2985. // 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 ,
  2986. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2987. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2988. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2989. // lpplanList := make([]*lpplanStruct, 0)
  2990. // err = tx.SQL(`select id,times,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpplan.pastureid ) = 0 ,
  2991. // ifnull((select maxstirfeed from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),100000),(select ifnull(volume,0) from tmr where id = lpplan.tmrid ) *
  2992. // (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)
  2993. // if err != nil {
  2994. // logs.Error(err, 1)
  2995. // return
  2996. // }
  2997. // lppidlist := []string{}
  2998. // for _, lpp := range lpplanList {
  2999. // lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  3000. // }
  3001. // if len(lppidlist) <= 0 {
  3002. // appG.Response(http.StatusOK, e.SUCCESS, true)
  3003. // return
  3004. // }
  3005. // lpplandtl1AllList := make([]*lpplandtl1, 0)
  3006. // err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  3007. // order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  3008. // if err != nil {
  3009. // // tx.Rollback()
  3010. // logs.Error(err, 2, parammaps["pastureid"])
  3011. // return
  3012. // }
  3013. // for _, lpp := range lpplandtl1AllList {
  3014. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  3015. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  3016. // if err != nil {
  3017. // logs.Error(err)
  3018. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3019. // return
  3020. // }
  3021. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3022. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  3023. // if err != nil {
  3024. // logs.Error(err)
  3025. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3026. // return
  3027. // }
  3028. // }
  3029. // var wg sync.WaitGroup
  3030. // for _, old := range fpdOldDataList {
  3031. // for _, fpd := range fpdDataList {
  3032. // wg.Add(1)
  3033. // go func(old, fpd map[string]interface{}) {
  3034. // updateLppandList := make([]*lpplandtl1, 0)
  3035. // defer wg.Done()
  3036. // if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3037. // fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3038. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3039. // oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3040. // // if weight > oldweight {
  3041. // // return
  3042. // // }
  3043. // var w float64
  3044. // var status int
  3045. // if weight < oldweight {
  3046. // if weight >= 0 {
  3047. // return
  3048. // }
  3049. // w = weight
  3050. // status = 0
  3051. // } else {
  3052. // if oldweight > 0 {
  3053. // return
  3054. // }
  3055. // w = weight
  3056. // status = 1
  3057. // }
  3058. // // fweight = w
  3059. // for _, lpp := range lpplanList {
  3060. // var fweight float64
  3061. // var lweight float64
  3062. // lpplandtl1List := make([]*lpplandtl1, 0)
  3063. // fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3064. // for _, lppland := range lpplandtl1AllList {
  3065. // if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3066. // lpplandtl1List = append(lpplandtl1List, lppland)
  3067. // }
  3068. // }
  3069. // if len(lpplandtl1List) == 0 {
  3070. // continue
  3071. // }
  3072. // for _, lppland := range lpplandtl1List {
  3073. // lweight += lppland.Lweight
  3074. // }
  3075. // if status == 0 {
  3076. // if lweight <= 0 {
  3077. // continue
  3078. // }
  3079. // } else {
  3080. // if lpp.Maxweight <= lweight {
  3081. // continue
  3082. // }
  3083. // }
  3084. // for _, lppland := range lpplandtl1List {
  3085. // if fpdid == lppland.Fpdid {
  3086. // if status == 1 {
  3087. // // if w <= lppland.Lweight {
  3088. // if lpp.Maxweight <= lweight {
  3089. // continue
  3090. // }
  3091. // if w+lweight <= lpp.Maxweight {
  3092. // lppland.Lweight += w
  3093. // lweight += w
  3094. // fweight += w
  3095. // w = 0
  3096. // } else {
  3097. // w = w - (lpp.Maxweight - lweight)
  3098. // n := (lpp.Maxweight - lweight)
  3099. // lppland.Lweight = lppland.Lweight + n
  3100. // lweight += n
  3101. // fweight += n
  3102. // }
  3103. // } else {
  3104. // if lppland.Lweight == 0 {
  3105. // continue
  3106. // }
  3107. // if w+lppland.Lweight >= 0 {
  3108. // lppland.Lweight = lppland.Lweight + w
  3109. // lweight = lweight + w
  3110. // fweight = fweight + w
  3111. // w = 0
  3112. // } else {
  3113. // w = w + lppland.Lweight
  3114. // lweight = lweight - lppland.Lweight
  3115. // fweight = fweight - lppland.Lweight
  3116. // lppland.Lweight = 0
  3117. // }
  3118. // }
  3119. // updateLppandList = append(updateLppandList, lppland)
  3120. // break
  3121. // }
  3122. // }
  3123. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3124. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3125. // WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3126. // if err != nil {
  3127. // // tx.Rollback()
  3128. // logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3129. // return
  3130. // }
  3131. // for _, lppland := range updateLppandList {
  3132. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3133. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3134. // if err != nil {
  3135. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3136. // // tx.Rollback()
  3137. // logs.Error(err, 3)
  3138. // return
  3139. // }
  3140. // // defer wg.Done()
  3141. // }
  3142. // updateLppandList = []*lpplandtl1{}
  3143. // if w == 0 {
  3144. // break
  3145. // }
  3146. // }
  3147. // }
  3148. // }(old, fpd)
  3149. // }
  3150. // }
  3151. // wg.Wait()
  3152. }
  3153. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3154. if err != nil {
  3155. logs.Error(err)
  3156. appG.Response(http.StatusOK, e.ERROR, false)
  3157. return
  3158. }
  3159. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3160. if err != nil {
  3161. logs.Error(err)
  3162. appG.Response(http.StatusOK, e.ERROR, false)
  3163. return
  3164. }
  3165. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3166. if err != nil {
  3167. logs.Error(err)
  3168. appG.Response(http.StatusOK, e.ERROR, false)
  3169. return
  3170. }
  3171. now := createdate
  3172. // for _, oldFpd := range oldFpdDataList {
  3173. for _, newFpd := range newFpdDataList {
  3174. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3175. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3176. // go func() {
  3177. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3178. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3179. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3180. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3181. if err != nil {
  3182. logs.Error(err)
  3183. appG.Response(http.StatusOK, e.ERROR, false)
  3184. return
  3185. }
  3186. // }()
  3187. }
  3188. // break
  3189. // }
  3190. // }
  3191. // }
  3192. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3193. for _, newLpplandtl1 := range newLpplandtl1List {
  3194. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3195. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3196. // go func() {
  3197. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3198. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3199. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3200. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3201. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3202. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3203. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3204. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3205. if err != nil {
  3206. logs.Error(err)
  3207. appG.Response(http.StatusOK, e.ERROR, false)
  3208. return
  3209. }
  3210. // }()
  3211. // }
  3212. // break
  3213. // }
  3214. // }
  3215. }
  3216. // for _, oldFeedp := range oldFeedpList {
  3217. for _, newFeedp := range newFeedpList {
  3218. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3219. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3220. // go func() {
  3221. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3222. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3223. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3224. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3225. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3226. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3227. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3228. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3229. if err != nil {
  3230. logs.Error(err)
  3231. appG.Response(http.StatusOK, e.ERROR, false)
  3232. return
  3233. }
  3234. }
  3235. // ,,parammaps["ftid"])
  3236. // surplus, surplusId, id, pastureId string
  3237. // FtdetailSurplusFt(parammaps["ftid"].)
  3238. ftList1, err := tx.SQL(` SELECT
  3239. f.id,
  3240. f.surplus surplusId,
  3241. f.pastureid,
  3242. s.surplus
  3243. FROM
  3244. feedtemplet f
  3245. JOIN surplus s ON s.id = f.surplus
  3246. WHERE
  3247. f.id = ?`, parammaps["ftid"]).QueryString()
  3248. for _, ft := range ftList1 {
  3249. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3250. }
  3251. appG.Response(http.StatusOK, e.SUCCESS, true)
  3252. }
  3253. type lpplandtlInfo struct {
  3254. Id int64 `xorm:"id"`
  3255. Pastureid int64 `xorm:"pastureid"`
  3256. Lppid int64 `xorm:"lppid"`
  3257. Barid int64 `xorm:"barid"`
  3258. Barname string `xorm:"barname"`
  3259. Fpdid int64 `xorm:"fpdid"`
  3260. Fttype int64 `xorm:"fttype"`
  3261. Lweight float64 `xorm:"lweight"`
  3262. Sort int64 `xorm:"sort"`
  3263. Tmrid int64 `xorm:"tmrid"`
  3264. Tmrname string `xorm:"tmrname"`
  3265. Cowcount int64 `xorm:"cowcount"`
  3266. Ccountradio float64 `xorm:"ccountradio"`
  3267. Background string `xorm:"background"`
  3268. Lweighthis float64 `xorm:"lweighthis"`
  3269. Maxweight float64 `xorm:"maxweight"`
  3270. }
  3271. func UpdateFpdetailBar(c *gin.Context) {
  3272. appG := app.Gin{C: c}
  3273. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3274. fsion := gofasion.NewFasion(string(dataByte))
  3275. pastureid := fsion.Get("pastureid").ValueStr()
  3276. id := fsion.Get("id").ValueStr()
  3277. tx := restful.Engine.NewSession()
  3278. tx.Begin()
  3279. 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 `,
  3280. pastureid, id).Query().List()
  3281. if err != nil {
  3282. logs.Error(err)
  3283. }
  3284. for _, fpd := range fpdList {
  3285. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3286. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3287. pastureid, fpd["id"]).Query().List()
  3288. if err != nil {
  3289. tx.Rollback()
  3290. logs.Error(err)
  3291. appG.Response(http.StatusOK, e.ERROR, false)
  3292. return
  3293. }
  3294. var lweight float64
  3295. for _, lppland := range lpplandList {
  3296. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3297. lweight += lweight1
  3298. }
  3299. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3300. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3301. if fpdweight >= ptuse && lweight == ptuse {
  3302. continue
  3303. } else {
  3304. if lweight <= fpdweight {
  3305. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3306. if err != nil {
  3307. tx.Rollback()
  3308. logs.Error(err)
  3309. appG.Response(http.StatusOK, e.ERROR, false)
  3310. return
  3311. }
  3312. } else {
  3313. weight := fpdweight - lweight
  3314. for _, lppland := range lpplandList {
  3315. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3316. if weight >= lpplandlweight {
  3317. weight = weight - lpplandlweight
  3318. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3319. if err != nil {
  3320. tx.Rollback()
  3321. logs.Error(err)
  3322. appG.Response(http.StatusOK, e.ERROR, false)
  3323. return
  3324. }
  3325. } else {
  3326. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3327. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3328. // if err != nil {
  3329. // tx.Rollback()
  3330. // logs.Error(err)
  3331. // appG.Response(http.StatusOK, e.ERROR, false)
  3332. // return
  3333. // }
  3334. weight = 0
  3335. break
  3336. }
  3337. }
  3338. }
  3339. }
  3340. }
  3341. fsionData := fsion.Get("data").Array()
  3342. for _, list := range fsionData {
  3343. ftmap := make(map[string]interface{})
  3344. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3345. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3346. ftmap["times"] = list.Get("times").ValueInt64()
  3347. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3348. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3349. // fmt.Println(ftmap)
  3350. // /*
  3351. count, err := tx.SQL(` select count(1) from lpplandtl1 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 = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3353. if count == 1 {
  3354. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3355. and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3356. if err != nil {
  3357. tx.Rollback()
  3358. logs.Error(err)
  3359. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3360. return
  3361. }
  3362. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3363. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3364. if err != nil {
  3365. tx.Rollback()
  3366. logs.Error(err)
  3367. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3368. return
  3369. }
  3370. }
  3371. // */
  3372. fpdDataList, err := tx.SQL(`
  3373. 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 ,
  3374. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3375. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3376. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3377. if err != nil {
  3378. tx.Rollback()
  3379. logs.Error(err)
  3380. }
  3381. for _, fpd := range fpdDataList {
  3382. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3383. fttype := -1
  3384. if fpd["fttype"].(string) == "1" {
  3385. fttype = 1
  3386. }
  3387. var fweight float64
  3388. var lweight float64
  3389. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3390. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  3391. t.maxstirfeed,(select ifnull(volume,0) from tmr where id = lpp.tmrid ) *
  3392. (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  3393. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3394. join tmr t on t.id = lpp.tmrid
  3395. where lppland.fpdid =?
  3396. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3397. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3398. if err != nil {
  3399. tx.Rollback()
  3400. logs.Error(err)
  3401. }
  3402. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3403. var w float64
  3404. var status int
  3405. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3406. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3407. if weight >= 0 {
  3408. continue
  3409. }
  3410. w = weight
  3411. status = 0
  3412. } else {
  3413. // continue
  3414. if weight <= 0 {
  3415. continue
  3416. }
  3417. w = weight
  3418. status = 1
  3419. }
  3420. // for _, lppland := range lpplandtl1List {
  3421. // lweight += lppland.Lweight
  3422. // }
  3423. for _, lppland := range lpplandtl1List {
  3424. lpplandInfo := new(lpplandtlInfo)
  3425. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3426. lweight = lpplandInfo.Lweight
  3427. if status == 1 {
  3428. // if w <= lppland.Lweight {
  3429. if lppland.Maxweight <= lweight {
  3430. continue
  3431. }
  3432. if w+lweight <= lppland.Maxweight {
  3433. lppland.Lweight += w
  3434. lweight += w
  3435. fweight += w
  3436. w = 0
  3437. } else {
  3438. w = w - (lppland.Maxweight - lweight)
  3439. n := (lppland.Maxweight - lweight)
  3440. lppland.Lweight = lppland.Lweight + n
  3441. lweight += n
  3442. fweight += n
  3443. }
  3444. } else {
  3445. if lppland.Lweight == 0 {
  3446. continue
  3447. }
  3448. if w+lppland.Lweight >= 0 {
  3449. lppland.Lweight = lppland.Lweight + w
  3450. lweight = lweight + w
  3451. fweight = fweight + w
  3452. w = 0
  3453. } else {
  3454. w = w + lppland.Lweight
  3455. lweight = lweight - lppland.Lweight
  3456. fweight = fweight - lppland.Lweight
  3457. lppland.Lweight = 0
  3458. }
  3459. }
  3460. if lppland.Lweight > 0 {
  3461. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3462. if err != nil {
  3463. tx.Rollback()
  3464. logs.Error(err)
  3465. return
  3466. }
  3467. } else {
  3468. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3469. if err != nil {
  3470. tx.Rollback()
  3471. logs.Error(err)
  3472. return
  3473. }
  3474. }
  3475. if w == 0 {
  3476. break
  3477. }
  3478. // break
  3479. }
  3480. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3481. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3482. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3483. if err != nil {
  3484. tx.Rollback()
  3485. logs.Error(err)
  3486. }
  3487. if w == 0 {
  3488. break
  3489. }
  3490. }
  3491. }
  3492. }
  3493. tx.Commit()
  3494. now := time.Now()
  3495. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3496. if err != nil {
  3497. logs.Error(err)
  3498. appG.Response(http.StatusOK, e.ERROR, false)
  3499. return
  3500. }
  3501. for _, newLpplandtl1 := range newLpplandtl1List {
  3502. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3503. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3504. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3505. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3506. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3507. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3508. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3509. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3510. if err != nil {
  3511. logs.Error(err)
  3512. appG.Response(http.StatusOK, e.ERROR, false)
  3513. return
  3514. }
  3515. }
  3516. appG.Response(http.StatusOK, e.SUCCESS, true)
  3517. }
  3518. func GetProcessAnalysis(c *gin.Context) {
  3519. appG := app.Gin{C: c}
  3520. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3521. fsion := gofasion.NewFasion(string(dataByte))
  3522. sqlnamestr := fsion.Get("name").ValueStr()
  3523. offset := fsion.Get("offset").ValueDefaultInt(0)
  3524. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3525. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3526. parammaps := fsion.Get("parammaps")
  3527. tx := restful.Engine.NewSession()
  3528. err := tx.Begin()
  3529. defer func() {
  3530. switch {
  3531. case err != nil:
  3532. logging.Error("tx.Begin 事务启动失败__error:", err)
  3533. if tx != nil {
  3534. tx.Rollback()
  3535. }
  3536. default:
  3537. if tx != nil {
  3538. err = tx.Commit()
  3539. }
  3540. }
  3541. if tx != nil {
  3542. tx.Close()
  3543. }
  3544. }()
  3545. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3546. s_params := make([]interface{}, 0)
  3547. paramslist := strings.Split(p, ",")
  3548. if len(paramslist) > 0 && p != "" {
  3549. for _, value := range paramslist {
  3550. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3551. if tempv, exists := c.Get("jwt_username"); exists {
  3552. s_params = append(s_params, tempv.(string))
  3553. } else {
  3554. s_params = append(s_params, "")
  3555. }
  3556. } else {
  3557. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3558. }
  3559. }
  3560. }
  3561. tmrtnameStr := ""
  3562. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3563. if len(tmrtnameStr) == 0 {
  3564. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3565. } else {
  3566. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3567. }
  3568. }
  3569. if len(tmrtnameStr) > 0 {
  3570. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3571. }
  3572. sql += " ORDER BY d.intime"
  3573. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3574. if err != nil {
  3575. logging.Error("GetDataByName err: ", err)
  3576. msg := geterrmsg(err.Error())
  3577. appG.Response(http.StatusOK, e.ERROR, msg)
  3578. } else {
  3579. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3580. }
  3581. }
  3582. func UpdateFeedtempletStatus(c *gin.Context) {
  3583. appG := app.Gin{C: c}
  3584. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3585. fsion := gofasion.NewFasion(string(dataByte))
  3586. parammaps := fsion.Get("parammaps")
  3587. tx := restful.Engine.NewSession()
  3588. tx.Begin()
  3589. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3590. if err != nil {
  3591. tx.Rollback()
  3592. logs.Error(err)
  3593. appG.Response(http.StatusOK, e.ERROR, err)
  3594. return
  3595. }
  3596. tx.Commit()
  3597. appG.Response(http.StatusOK, e.SUCCESS, true)
  3598. }
  3599. func AddFtdry(c *gin.Context) {
  3600. appG := app.Gin{C: c}
  3601. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3602. fsion := gofasion.NewFasion(string(dataByte))
  3603. sqlnamestr := fsion.Get("name").ValueStr()
  3604. s_params := make([]interface{}, 0)
  3605. tx := restful.Engine.NewSession()
  3606. err := tx.Begin()
  3607. defer func() {
  3608. switch {
  3609. case err != nil:
  3610. if tx != nil {
  3611. tx.Rollback()
  3612. }
  3613. default:
  3614. if tx != nil {
  3615. err = tx.Commit()
  3616. }
  3617. }
  3618. if tx != nil {
  3619. tx.Close()
  3620. }
  3621. }()
  3622. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3623. if sql != "" {
  3624. parammaps := fsion.Get("parammaps")
  3625. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3626. paramslist := strings.Split(p, ",")
  3627. if len(paramslist) > 0 && p != "" {
  3628. for _, value := range paramslist {
  3629. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3630. if tempv, exists := c.Get("jwt_username"); exists {
  3631. s_params = append(s_params, tempv.(string))
  3632. } else {
  3633. s_params = append(s_params, "")
  3634. }
  3635. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3636. ids, err := setting.SnowIds.NextId()
  3637. if err != nil {
  3638. ids = time.Now().UnixNano()
  3639. logging.Info("create SnowIds err", err)
  3640. }
  3641. s_params = append(s_params, ids)
  3642. } else {
  3643. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3644. }
  3645. }
  3646. }
  3647. var actweight float64
  3648. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3649. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3650. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3651. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3652. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3653. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3654. 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()
  3655. if err != nil {
  3656. logging.Error("AddFtdry err: ", err)
  3657. msg := geterrmsg(err.Error())
  3658. appG.Response(http.StatusOK, e.ERROR, msg)
  3659. }
  3660. if len(actweightList) > 0 {
  3661. for _, item := range actweightList {
  3662. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3663. if err != nil {
  3664. logging.Error("AddFtdry err: ", err)
  3665. msg := geterrmsg(err.Error())
  3666. appG.Response(http.StatusOK, e.ERROR, msg)
  3667. }
  3668. actweight = fl
  3669. }
  3670. } else {
  3671. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3672. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3673. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3674. if err != nil {
  3675. logging.Error("AddFtdry err: ", err)
  3676. msg := geterrmsg(err.Error())
  3677. appG.Response(http.StatusOK, e.ERROR, msg)
  3678. }
  3679. for _, item := range dryList {
  3680. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3681. if err != nil {
  3682. logging.Error("AddFtdry err: ", err)
  3683. msg := geterrmsg(err.Error())
  3684. appG.Response(http.StatusOK, e.ERROR, msg)
  3685. }
  3686. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3687. }
  3688. }
  3689. if sqlnamestr == "insertFtdry" {
  3690. s_params = append(s_params, actweight)
  3691. } else if sqlnamestr == "updateFtdry" {
  3692. sql = fmt.Sprintf(sql, actweight)
  3693. }
  3694. queryData, err := execDataBySqlT(sql, s_params, tx)
  3695. if err != nil {
  3696. logging.Error("AddFtdry err: ", err)
  3697. msg := geterrmsg(err.Error())
  3698. appG.Response(http.StatusOK, e.ERROR, msg)
  3699. } else {
  3700. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3701. }
  3702. } else {
  3703. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3704. }
  3705. }
  3706. func CheckDates(c *gin.Context) {
  3707. tx := restful.Engine.NewSession()
  3708. defer tx.Close()
  3709. appG := app.Gin{C: c}
  3710. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3711. tempval_ := make(map[string]interface{})
  3712. tempCommon := make(map[string]interface{})
  3713. tempval := make([]map[string]interface{}, 0)
  3714. err := json.Unmarshal(dataByte, &tempval_)
  3715. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3716. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3717. if err != nil {
  3718. } else {
  3719. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3720. tempCommon = v
  3721. }
  3722. if v, ok := tempval_["data"].([]interface{}); ok {
  3723. for _, Tvalue := range v {
  3724. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3725. tempval = append(tempval, v1)
  3726. }
  3727. }
  3728. }
  3729. if err == nil {
  3730. if tempv, exists := c.Get("jwt_username"); exists {
  3731. tempCommon["jwt_username"] = tempv.(string)
  3732. }
  3733. for _, paramvalue := range tempval {
  3734. if _, ok := paramvalue["resultname"]; !ok {
  3735. paramvalue["resultname"] = paramvalue["name"]
  3736. }
  3737. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3738. if err != nil {
  3739. logging.Error("ExecDataParam error:", err)
  3740. }
  3741. }
  3742. if err == nil {
  3743. vmsg := ""
  3744. for _, item := range tempval {
  3745. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3746. for _, childrenList := range list.([]interface{}) {
  3747. for k, children := range childrenList.(map[string]interface{}) {
  3748. if k != "children" {
  3749. continue
  3750. }
  3751. for _, v := range children.([]map[string]interface{}) {
  3752. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3753. if k1 == "list" {
  3754. for _, v2 := range v1.([]map[string]interface{}) {
  3755. if v2["vmsg"].(string) != "1" {
  3756. if len(vmsg) == 0 {
  3757. vmsg = v2["vmsg"].(string)
  3758. } else {
  3759. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3760. }
  3761. }
  3762. }
  3763. }
  3764. }
  3765. }
  3766. }
  3767. }
  3768. }
  3769. }
  3770. if len(vmsg) > 0 {
  3771. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3772. } else {
  3773. appG.Response(http.StatusOK, e.SUCCESS, true)
  3774. }
  3775. } else {
  3776. msg := geterrmsg(err.Error())
  3777. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3778. }
  3779. }
  3780. }
  3781. if err != nil {
  3782. msg := geterrmsg(err.Error())
  3783. appG.Response(http.StatusOK, e.ERROR, msg)
  3784. }
  3785. }
  3786. 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) {
  3787. sqlname := fasion["name"].(string)
  3788. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3789. if v, ok := fasion["type"]; ok {
  3790. sqltype = v.(string)
  3791. }
  3792. sql := ""
  3793. p := ""
  3794. s_params := make([]interface{}, 0)
  3795. if sqltype != "" {
  3796. sql, p = restful.GetSqlByName(sqlname, tx)
  3797. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3798. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3799. paramslist := strings.Split(p, ",")
  3800. if len(paramslist) > 0 && p != "" {
  3801. for _, value := range paramslist {
  3802. ss := ""
  3803. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3804. ids, err := setting.SnowIds.NextId()
  3805. if err != nil {
  3806. ids = time.Now().UnixNano()
  3807. logging.Info("create SnowIds err", err)
  3808. }
  3809. s_params = append(s_params, ids)
  3810. } else {
  3811. if ss == "" && CommonParamMap != nil {
  3812. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3813. ss = valuestring
  3814. tempstrb := strings.IndexAny(valuestring, "@")
  3815. tempstre := strings.IndexAny(valuestring, ".")
  3816. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3817. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3818. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3819. }
  3820. } else {
  3821. ss = ""
  3822. }
  3823. }
  3824. }
  3825. if ss == "" && ParentParamMap != nil {
  3826. ss = getParamValue_(v, value, ParentParamMap)
  3827. }
  3828. if ss == "" && sameParamMap != nil {
  3829. ss = getParamValue(v, value, sameParamMap)
  3830. }
  3831. if ss == "" && ParamMap != nil {
  3832. ss = getParamValue(v, value, ParamMap)
  3833. }
  3834. s_params = append(s_params, ss)
  3835. }
  3836. }
  3837. }
  3838. }
  3839. }
  3840. if sql == "" {
  3841. sqltype = ""
  3842. }
  3843. if sql != "" {
  3844. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3845. if err != nil {
  3846. return nil, err
  3847. }
  3848. // fmt.Println(tempValParam)
  3849. return tempValParam.(map[string]interface{}), nil
  3850. } else {
  3851. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3852. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3853. if err != nil {
  3854. return nil, err
  3855. }
  3856. return nil, err
  3857. }
  3858. }
  3859. return nil, nil
  3860. }
  3861. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3862. var err error
  3863. subarray, ok := fasion["children"]
  3864. if ok {
  3865. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3866. tempVal_arrary := make([]map[string]interface{}, 0)
  3867. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3868. tempVal_ := make(map[string]interface{})
  3869. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3870. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3871. } else {
  3872. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3873. }
  3874. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3875. if err != nil {
  3876. return err
  3877. }
  3878. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3879. }
  3880. v.(map[string]interface{})["children"] = tempVal_arrary
  3881. }
  3882. }
  3883. return nil
  3884. }
  3885. func FpdImportExcel(c *gin.Context) {
  3886. appG := app.Gin{C: c}
  3887. inputdata := ""
  3888. c.Request.ParseForm()
  3889. params := c.Request.Form
  3890. file, _, err := c.Request.FormFile("file")
  3891. if err != nil {
  3892. appG.Response(http.StatusOK, e.ERROR, err)
  3893. return
  3894. }
  3895. sqlnamestrs := params.Get("name")
  3896. sheetname := params.Get("sheetname")
  3897. pastureid := params.Get("pastureid")
  3898. // importParams := params.Get("importParams")
  3899. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3900. // 必输项参数 (字符串格式 "field1,field2,field3")
  3901. requiredParams := params.Get("requiredParams")
  3902. // 日期参数
  3903. dateParams := params.Get("dateParams")
  3904. // 数字参数
  3905. numParams := params.Get("numParams")
  3906. //将字符串分割开
  3907. dateParamslist := strings.Split(dateParams, ",")
  3908. requiredParamslist := strings.Split(requiredParams, ",")
  3909. numParamslist := strings.Split(numParams, ",")
  3910. queryData := make([]interface{}, 0)
  3911. sqlslist := strings.Split(sqlnamestrs, ",")
  3912. xlsx1, err := excelize.OpenReader(file)
  3913. if err != nil {
  3914. fmt.Println(err)
  3915. return
  3916. }
  3917. ok := 0
  3918. error := 0
  3919. isdone := true
  3920. tx := restful.Engine.NewSession()
  3921. defer tx.Close()
  3922. languageStatus := GetLanguageStatus()
  3923. if languageStatus == "0" {
  3924. 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
  3925. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3926. if err != nil {
  3927. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3928. return
  3929. }
  3930. rows := xlsx1.GetRows(sheetname)
  3931. // 限制10000条,多余的截取掉
  3932. if len(rows) > 10000 {
  3933. rows = rows[:10000]
  3934. }
  3935. dataList := make(map[string][]*upFpdetail, 0)
  3936. for i, row := range rows {
  3937. if i > 0 {
  3938. entry := make(map[string]interface{})
  3939. outentry := make(map[string]interface{})
  3940. for j, colCell := range rows[0] {
  3941. for k, colCell1 := range row {
  3942. if j == k {
  3943. outentry[colCell] = colCell1
  3944. entry[colCell] = colCell1
  3945. }
  3946. }
  3947. }
  3948. inputdata = ""
  3949. a := ""
  3950. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3951. //校验日期格式
  3952. for _, v := range dateParamslist {
  3953. if v == "" {
  3954. continue
  3955. }
  3956. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3957. dtime, err := TransfTime(d.(string))
  3958. if err != nil {
  3959. a = strings.Trim(v, " ")
  3960. break
  3961. }
  3962. outentry[strings.Trim(v, " ")] = dtime
  3963. }
  3964. }
  3965. if a != "" {
  3966. outentry["error_msg"] = a + " 格式错误"
  3967. error++
  3968. queryData = append(queryData, outentry)
  3969. continue
  3970. }
  3971. a = ""
  3972. //校验必填格式
  3973. for _, v := range requiredParamslist {
  3974. if v == "" {
  3975. continue
  3976. }
  3977. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3978. a = strings.Trim(v, " ")
  3979. break
  3980. }
  3981. }
  3982. if a != "" {
  3983. outentry["error_msg"] = a + " 未填或格式错误"
  3984. error++
  3985. queryData = append(queryData, outentry)
  3986. continue
  3987. }
  3988. a = ""
  3989. //校验数字格式
  3990. for _, v := range numParamslist {
  3991. if v == "" {
  3992. continue
  3993. }
  3994. d, ok := outentry[strings.Trim(v, " ")]
  3995. if !ok || d == "" {
  3996. outentry[strings.Trim(v, " ")] = 0
  3997. } else {
  3998. var fl float64
  3999. switch d.(type) {
  4000. case string:
  4001. fl, err = strconv.ParseFloat(d.(string), 64)
  4002. }
  4003. if err != nil || fl < 0 {
  4004. a = strings.Trim(v, " ")
  4005. break
  4006. }
  4007. }
  4008. }
  4009. if a != "" {
  4010. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  4011. error++
  4012. queryData = append(queryData, outentry)
  4013. continue
  4014. }
  4015. errExist := false
  4016. for _, sqlnamestr := range sqlslist {
  4017. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4018. paramslist := strings.Split(paramslists, ",")
  4019. if len(paramslist) > 0 {
  4020. s_params := make([]interface{}, 0)
  4021. for _, value := range paramslist {
  4022. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4023. if tempv, exists := c.Get("jwt_username"); exists {
  4024. s_params = append(s_params, tempv.(string))
  4025. } else {
  4026. s_params = append(s_params, "")
  4027. }
  4028. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4029. s_params = append(s_params, pastureid)
  4030. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4031. ids, err := setting.SnowIds.NextId()
  4032. if err != nil {
  4033. ids = time.Now().UnixNano()
  4034. logging.Info("create SnowIds err", err)
  4035. }
  4036. s_params = append(s_params, ids)
  4037. } else {
  4038. if outentry[strings.Trim(value, " ")] == nil {
  4039. s_params = append(s_params, "")
  4040. } else {
  4041. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4042. }
  4043. }
  4044. }
  4045. outentry["input"] = inputdata
  4046. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4047. if err != nil {
  4048. errExist = true
  4049. // if tx != nil {
  4050. // tx.Rollback()
  4051. // }
  4052. // if tx != nil {
  4053. // tx.Close()
  4054. // }
  4055. msg := geterrmsg(err.Error())
  4056. outentry["error_msg"] = msg
  4057. error++
  4058. queryData = append(queryData, outentry)
  4059. isdone = true
  4060. break
  4061. } else {
  4062. if len(returnmsgmap1) > 0 {
  4063. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4064. // if tx != nil {
  4065. // tx.Rollback()
  4066. // }
  4067. // if tx != nil {
  4068. // tx.Close()
  4069. // }
  4070. msg := geterrmsg(va.(string))
  4071. outentry["error_msg"] = msg
  4072. error++
  4073. queryData = append(queryData, outentry)
  4074. isdone = true
  4075. break
  4076. }
  4077. }
  4078. isdone = false
  4079. }
  4080. }
  4081. }
  4082. fmt.Println(outentry["栏舍名称"])
  4083. if !errExist {
  4084. dataexcel := make(map[string]interface{}, 0)
  4085. if _, ok := outentry["栏舍名称"]; ok {
  4086. dataexcel["barname"] = outentry["栏舍名称"]
  4087. }
  4088. if _, ok := outentry["实际牛头数"]; ok {
  4089. dataexcel["ccount"] = outentry["实际牛头数"]
  4090. }
  4091. // if _, ok := outentry["实际羊只数"]; ok {
  4092. // dataexcel["ccount"] = outentry["实际羊只数"]
  4093. // }
  4094. if _, ok := outentry["系数(%)"]; ok {
  4095. dataexcel["ratio"] = outentry["系数(%)"]
  4096. }
  4097. if _, ok := outentry["配方模板"]; ok {
  4098. dataexcel["ftname"] = outentry["配方模板"]
  4099. }
  4100. if _, ok := outentry["补料配方"]; ok {
  4101. dataexcel["ptsfname"] = outentry["补料配方"]
  4102. }
  4103. if _, ok := outentry["第一班比例(%)"]; ok {
  4104. dataexcel["1"] = outentry["第一班比例(%)"]
  4105. if fmt.Sprintf("%v", dataexcel["1"]) == "" {
  4106. dataexcel["1"] = 0
  4107. }
  4108. } else {
  4109. dataexcel["1"] = 0
  4110. }
  4111. if _, ok := outentry["第二班比例(%)"]; ok {
  4112. dataexcel["2"] = outentry["第二班比例(%)"]
  4113. if fmt.Sprintf("%v", dataexcel["2"]) == "" {
  4114. dataexcel["2"] = 0
  4115. }
  4116. } else {
  4117. dataexcel["2"] = 0
  4118. }
  4119. if _, ok := outentry["第三班比例(%)"]; ok {
  4120. dataexcel["3"] = outentry["第三班比例(%)"]
  4121. if fmt.Sprintf("%v", dataexcel["3"]) == "" {
  4122. dataexcel["3"] = 0
  4123. }
  4124. } else {
  4125. dataexcel["3"] = 0
  4126. }
  4127. if _, ok := outentry["第四班比例(%)"]; ok {
  4128. dataexcel["4"] = outentry["第四班比例(%)"]
  4129. if fmt.Sprintf("%v", dataexcel["4"]) == "" {
  4130. dataexcel["4"] = 0
  4131. }
  4132. } else {
  4133. dataexcel["4"] = 0
  4134. }
  4135. if _, ok := outentry["第五班比例(%)"]; ok {
  4136. dataexcel["5"] = outentry["第五班比例(%)"]
  4137. if fmt.Sprintf("%v", dataexcel["5"]) == "" {
  4138. dataexcel["5"] = 0
  4139. }
  4140. } else {
  4141. dataexcel["5"] = 0
  4142. }
  4143. if _, ok := outentry["第六班比例(%)"]; ok {
  4144. dataexcel["6"] = outentry["第六班比例(%)"]
  4145. if fmt.Sprintf("%v", dataexcel["6"]) == "" {
  4146. dataexcel["6"] = 0
  4147. }
  4148. } else {
  4149. dataexcel["6"] = 0
  4150. }
  4151. dataWeight := new(models.FpdetailEdit)
  4152. // dataWeightMap := make(map[string]interface{}, 0)
  4153. if _, ok := outentry["第一班重量"]; ok {
  4154. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4155. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4156. }
  4157. if _, ok := outentry["第二班重量"]; ok {
  4158. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4159. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4160. }
  4161. if _, ok := outentry["第三班重量"]; ok {
  4162. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4163. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4164. }
  4165. if _, ok := outentry["第四班重量"]; ok {
  4166. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4167. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4168. }
  4169. if _, ok := outentry["第五班重量"]; ok {
  4170. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4171. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4172. }
  4173. if _, ok := outentry["第六班重量"]; ok {
  4174. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4175. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4176. }
  4177. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4178. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4179. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4180. // fmt.Println(err)
  4181. if fmt.Sprintf("%v", dataexcel["ccount"]) == "0" {
  4182. dataWeight.Weight1 = 0
  4183. dataWeight.Weight2 = 0
  4184. dataWeight.Weight3 = 0
  4185. dataWeight.Weight4 = 0
  4186. dataWeight.Weight5 = 0
  4187. dataWeight.Weight6 = 0
  4188. }
  4189. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4190. if weight > 0 {
  4191. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4192. if err != nil {
  4193. logs.Error(err)
  4194. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4195. return
  4196. }
  4197. if !existbar {
  4198. continue
  4199. }
  4200. _, 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()
  4201. if err != nil {
  4202. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4203. return
  4204. }
  4205. _, 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()
  4206. if err != nil {
  4207. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4208. return
  4209. }
  4210. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4211. if err != nil {
  4212. logs.Error(err)
  4213. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4214. return
  4215. }
  4216. if !existft {
  4217. continue
  4218. }
  4219. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4220. if err != nil {
  4221. logs.Error(err)
  4222. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4223. return
  4224. }
  4225. if !ftexist {
  4226. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4227. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4228. if err != nil {
  4229. logs.Error(err)
  4230. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4231. return
  4232. }
  4233. tx.SQL(` update fpdetail set ptuse = 0 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. }
  4240. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4241. if err != nil {
  4242. logs.Error(err)
  4243. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4244. return
  4245. }
  4246. if !exist {
  4247. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4248. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4249. if err != nil {
  4250. logs.Error(err)
  4251. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4252. return
  4253. }
  4254. }
  4255. var feedpargs []interface{}
  4256. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4257. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4258. if _, ok := dataexcel["ftname"]; ok {
  4259. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4260. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4261. // upFeedpSql += `,ftweight = ? `
  4262. // feedpargs = append(feedpargs, weight)
  4263. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4264. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4265. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4266. } else {
  4267. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4268. }
  4269. if _, ok := dataexcel["ptsfname"]; ok {
  4270. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4271. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4272. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4273. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4274. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4275. } else {
  4276. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4277. }
  4278. upFeedpSql += " where barname = ? and pastureid = ? "
  4279. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4280. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4281. if err != nil {
  4282. logs.Error(err)
  4283. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4284. return
  4285. }
  4286. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4287. if err != nil {
  4288. logs.Error(err)
  4289. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4290. return
  4291. }
  4292. if !exist1 {
  4293. _, 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) `,
  4294. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4295. if err != nil {
  4296. logs.Error(err)
  4297. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4298. return
  4299. }
  4300. }
  4301. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4302. if err != nil {
  4303. logs.Error(err)
  4304. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4305. return
  4306. }
  4307. if !exist2 {
  4308. _, 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) `,
  4309. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4310. if err != nil {
  4311. logs.Error(err)
  4312. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4313. return
  4314. }
  4315. }
  4316. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4317. if err != nil {
  4318. logs.Error(err)
  4319. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4320. return
  4321. }
  4322. if !exist3 {
  4323. _, 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) `,
  4324. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4325. if err != nil {
  4326. logs.Error(err)
  4327. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4328. return
  4329. }
  4330. }
  4331. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4332. if err != nil {
  4333. logs.Error(err)
  4334. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4335. return
  4336. }
  4337. if !exist4 {
  4338. _, 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) `,
  4339. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4340. if err != nil {
  4341. logs.Error(err)
  4342. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4343. return
  4344. }
  4345. }
  4346. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4347. if err != nil {
  4348. logs.Error(err)
  4349. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4350. return
  4351. }
  4352. if !exist5 {
  4353. _, 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) `,
  4354. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4355. if err != nil {
  4356. logs.Error(err)
  4357. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4358. return
  4359. }
  4360. }
  4361. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4362. if err != nil {
  4363. logs.Error(err)
  4364. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4365. return
  4366. }
  4367. if !exist6 {
  4368. _, 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) `,
  4369. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4370. if err != nil {
  4371. logs.Error(err)
  4372. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4373. return
  4374. }
  4375. }
  4376. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4377. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4378. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4379. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4380. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4381. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4382. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4383. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4384. and pastureid = ? and times = ?`
  4385. var fpdargs1 []interface{}
  4386. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4387. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4388. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4389. if err != nil {
  4390. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4391. return
  4392. }
  4393. var fpdargs2 []interface{}
  4394. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4395. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4396. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4397. if err != nil {
  4398. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4399. return
  4400. }
  4401. var fpdargs3 []interface{}
  4402. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4403. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4404. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4405. if err != nil {
  4406. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4407. return
  4408. }
  4409. var fpdargs4 []interface{}
  4410. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4411. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4412. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4413. if err != nil {
  4414. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4415. return
  4416. }
  4417. var fpdargs5 []interface{}
  4418. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4419. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4420. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4421. if err != nil {
  4422. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4423. return
  4424. }
  4425. var fpdargs6 []interface{}
  4426. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4427. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4428. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4429. if err != nil {
  4430. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4431. return
  4432. }
  4433. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4434. 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()
  4435. if err != nil {
  4436. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4437. return
  4438. }
  4439. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4440. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4441. upFpdetailList := make([]*upFpdetail, 0)
  4442. for _, newfpd := range newList {
  4443. for _, oldfpd := range oldFpdList {
  4444. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4445. var oldweight, newweight float64
  4446. if oldfpd["weight"] != nil {
  4447. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4448. }
  4449. if newfpd["weight"] != nil {
  4450. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4451. }
  4452. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4453. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4454. Old: oldweight,
  4455. New: newweight,
  4456. Times: newfpd["times"].(int64),
  4457. Ptid: newfpd["ptid"].(int64),
  4458. Fweight: fweight,
  4459. Id: oldfpd["id"].(int64),
  4460. })
  4461. break
  4462. }
  4463. }
  4464. }
  4465. // fmt.Println(dataexcel["barname"])
  4466. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4467. } else {
  4468. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4469. if err != nil {
  4470. logs.Error(err)
  4471. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4472. return
  4473. }
  4474. if !existbar {
  4475. continue
  4476. }
  4477. _, 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()
  4478. if err != nil {
  4479. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4480. return
  4481. }
  4482. _, 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()
  4483. if err != nil {
  4484. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4485. return
  4486. }
  4487. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4488. if err != nil {
  4489. logs.Error(err)
  4490. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4491. return
  4492. }
  4493. if !existft {
  4494. continue
  4495. }
  4496. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4497. if err != nil {
  4498. logs.Error(err)
  4499. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4500. return
  4501. }
  4502. if !ftexist {
  4503. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4504. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4505. if err != nil {
  4506. logs.Error(err)
  4507. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4508. return
  4509. }
  4510. tx.SQL(` update fpdetail set ptuse = 0 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. }
  4517. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4518. if err != nil {
  4519. logs.Error(err)
  4520. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4521. return
  4522. }
  4523. if !exist {
  4524. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4525. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4526. if err != nil {
  4527. logs.Error(err)
  4528. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4529. return
  4530. }
  4531. }
  4532. var feedpargs []interface{}
  4533. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4534. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4535. if _, ok := dataexcel["ftname"]; ok {
  4536. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4537. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4538. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4539. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4540. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4541. } else {
  4542. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4543. }
  4544. if _, ok := dataexcel["ptsfname"]; ok {
  4545. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4546. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4547. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4548. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4549. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4550. } else {
  4551. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4552. }
  4553. upFeedpSql += " where barname = ? and pastureid = ? "
  4554. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4555. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4556. if err != nil {
  4557. logs.Error(err)
  4558. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4559. return
  4560. }
  4561. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4562. if err != nil {
  4563. logs.Error(err)
  4564. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4565. return
  4566. }
  4567. if !exist1 {
  4568. _, 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) `,
  4569. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4570. if err != nil {
  4571. logs.Error(err)
  4572. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4573. return
  4574. }
  4575. }
  4576. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4577. if err != nil {
  4578. logs.Error(err)
  4579. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4580. return
  4581. }
  4582. if !exist2 {
  4583. _, 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) `,
  4584. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4585. if err != nil {
  4586. logs.Error(err)
  4587. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4588. return
  4589. }
  4590. }
  4591. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4592. if err != nil {
  4593. logs.Error(err)
  4594. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4595. return
  4596. }
  4597. if !exist3 {
  4598. _, 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) `,
  4599. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4600. if err != nil {
  4601. logs.Error(err)
  4602. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4603. return
  4604. }
  4605. }
  4606. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4607. if err != nil {
  4608. logs.Error(err)
  4609. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4610. return
  4611. }
  4612. if !exist4 {
  4613. _, 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) `,
  4614. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4615. if err != nil {
  4616. logs.Error(err)
  4617. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4618. return
  4619. }
  4620. }
  4621. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4622. if err != nil {
  4623. logs.Error(err)
  4624. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4625. return
  4626. }
  4627. if !exist5 {
  4628. _, 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) `,
  4629. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4630. if err != nil {
  4631. logs.Error(err)
  4632. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4633. return
  4634. }
  4635. }
  4636. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4637. if err != nil {
  4638. logs.Error(err)
  4639. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4640. return
  4641. }
  4642. if !exist6 {
  4643. _, 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) `,
  4644. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4645. if err != nil {
  4646. logs.Error(err)
  4647. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4648. return
  4649. }
  4650. }
  4651. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4652. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4653. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4654. and pastureid = ? and times = ?`
  4655. var fpdargs1 []interface{}
  4656. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4657. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4658. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4659. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4660. if err != nil {
  4661. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4662. return
  4663. }
  4664. var fpdargs2 []interface{}
  4665. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4666. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4667. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4668. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4669. if err != nil {
  4670. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4671. return
  4672. }
  4673. var fpdargs3 []interface{}
  4674. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4675. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4676. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4677. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4678. if err != nil {
  4679. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4680. return
  4681. }
  4682. var fpdargs4 []interface{}
  4683. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4684. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4685. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4686. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4687. if err != nil {
  4688. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4689. return
  4690. }
  4691. var fpdargs5 []interface{}
  4692. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4693. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4694. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4695. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4696. if err != nil {
  4697. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4698. return
  4699. }
  4700. var fpdargs6 []interface{}
  4701. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4702. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4703. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4704. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4705. if err != nil {
  4706. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4707. return
  4708. }
  4709. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4710. 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()
  4711. if err != nil {
  4712. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4713. return
  4714. }
  4715. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4716. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4717. upFpdetailList := make([]*upFpdetail, 0)
  4718. for _, newfpd := range newList {
  4719. for _, oldfpd := range oldFpdList {
  4720. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4721. var oldweight, newweight float64
  4722. if oldfpd["weight"] != nil {
  4723. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4724. }
  4725. if newfpd["weight"] != nil {
  4726. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4727. }
  4728. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4729. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4730. Old: oldweight,
  4731. New: newweight,
  4732. Times: newfpd["times"].(int64),
  4733. Ptid: newfpd["ptid"].(int64),
  4734. Fweight: fweight,
  4735. Id: oldfpd["id"].(int64),
  4736. })
  4737. break
  4738. }
  4739. }
  4740. }
  4741. // fmt.Println(dataexcel["barname"])
  4742. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4743. }
  4744. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4745. }
  4746. }
  4747. if !isdone {
  4748. ok++
  4749. isdone = true
  4750. }
  4751. }
  4752. for barname, v := range dataList {
  4753. // for _, v1 := range v {
  4754. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4755. // and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4756. // if count == 1 {
  4757. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4758. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4759. // if err != nil {
  4760. // logs.Error(err)
  4761. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4762. // return
  4763. // }
  4764. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4765. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4766. // if err != nil {
  4767. // logs.Error(err)
  4768. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4769. // return
  4770. // }
  4771. // }
  4772. // }
  4773. // /*
  4774. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  4775. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  4776. if err != nil {
  4777. logs.Error(err)
  4778. return
  4779. }
  4780. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4781. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  4782. if err != nil {
  4783. logs.Error(err)
  4784. return
  4785. }
  4786. // */
  4787. updateFpdetailByBar(pastureid, barname, v)
  4788. }
  4789. } else {
  4790. 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
  4791. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4792. if err != nil {
  4793. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4794. return
  4795. }
  4796. rows := xlsx1.GetRows(sheetname)
  4797. // 限制10000条,多余的截取掉
  4798. if len(rows) > 10000 {
  4799. rows = rows[:10000]
  4800. }
  4801. dataList := make(map[string][]*upFpdetail, 0)
  4802. for i, row := range rows {
  4803. if i > 0 {
  4804. entry := make(map[string]interface{})
  4805. outentry := make(map[string]interface{})
  4806. for j, colCell := range rows[0] {
  4807. for k, colCell1 := range row {
  4808. if j == k {
  4809. outentry[colCell] = colCell1
  4810. entry[colCell] = colCell1
  4811. }
  4812. }
  4813. }
  4814. inputdata = ""
  4815. a := ""
  4816. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4817. //校验日期格式
  4818. for _, v := range dateParamslist {
  4819. if v == "" {
  4820. continue
  4821. }
  4822. if d, ok := outentry[v]; ok {
  4823. dtime, err := TransfTime(d.(string))
  4824. if err != nil {
  4825. a = v
  4826. break
  4827. }
  4828. outentry[v] = dtime
  4829. }
  4830. }
  4831. if a != "" {
  4832. outentry["error_msg"] = a + " format error"
  4833. error++
  4834. queryData = append(queryData, outentry)
  4835. continue
  4836. }
  4837. a = ""
  4838. //校验必填格式
  4839. for _, v := range requiredParamslist {
  4840. if v == "" {
  4841. continue
  4842. }
  4843. if d, ok := outentry[v]; !ok || d == "" {
  4844. a = v
  4845. break
  4846. }
  4847. }
  4848. if a != "" {
  4849. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4850. error++
  4851. queryData = append(queryData, outentry)
  4852. continue
  4853. }
  4854. a = ""
  4855. //校验数字格式
  4856. for _, v := range numParamslist {
  4857. if v == "" {
  4858. continue
  4859. }
  4860. d, ok := outentry[v]
  4861. if !ok || d == "" {
  4862. outentry[v] = 0
  4863. } else {
  4864. var fl float64
  4865. switch d.(type) {
  4866. case string:
  4867. fl, err = strconv.ParseFloat(d.(string), 64)
  4868. }
  4869. if err != nil || fl < 0 {
  4870. a = v
  4871. break
  4872. }
  4873. }
  4874. }
  4875. if a != "" {
  4876. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4877. error++
  4878. queryData = append(queryData, outentry)
  4879. continue
  4880. }
  4881. errExist := false
  4882. for _, sqlnamestr := range sqlslist {
  4883. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4884. paramslist := strings.Split(paramslists, ",")
  4885. if len(paramslist) > 0 {
  4886. s_params := make([]interface{}, 0)
  4887. for _, value := range paramslist {
  4888. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4889. if tempv, exists := c.Get("jwt_username"); exists {
  4890. s_params = append(s_params, tempv.(string))
  4891. } else {
  4892. s_params = append(s_params, "")
  4893. }
  4894. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4895. s_params = append(s_params, pastureid)
  4896. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4897. ids, err := setting.SnowIds.NextId()
  4898. if err != nil {
  4899. ids = time.Now().UnixNano()
  4900. logging.Info("create SnowIds err", err)
  4901. }
  4902. s_params = append(s_params, ids)
  4903. } else {
  4904. if outentry[strings.Trim(value, " ")] == nil {
  4905. s_params = append(s_params, "")
  4906. } else {
  4907. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4908. }
  4909. }
  4910. }
  4911. outentry["input"] = inputdata
  4912. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4913. if err != nil {
  4914. errExist = true
  4915. // if tx != nil {
  4916. // tx.Rollback()
  4917. // }
  4918. // if tx != nil {
  4919. // tx.Close()
  4920. // }
  4921. msg := geterrmsg(err.Error())
  4922. outentry["error_msg"] = msg
  4923. error++
  4924. queryData = append(queryData, outentry)
  4925. isdone = true
  4926. break
  4927. } else {
  4928. if len(returnmsgmap1) > 0 {
  4929. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4930. // if tx != nil {
  4931. // tx.Rollback()
  4932. // }
  4933. // if tx != nil {
  4934. // tx.Close()
  4935. // }
  4936. msg := geterrmsg(va.(string))
  4937. outentry["error_msg"] = msg
  4938. error++
  4939. queryData = append(queryData, outentry)
  4940. isdone = true
  4941. break
  4942. }
  4943. }
  4944. isdone = false
  4945. }
  4946. }
  4947. }
  4948. if !errExist {
  4949. dataexcel := make(map[string]interface{}, 0)
  4950. if _, ok := outentry["Pen Name"]; ok {
  4951. dataexcel["barname"] = outentry["Pen Name"]
  4952. }
  4953. if _, ok := outentry["Actual Cattle Number"]; ok {
  4954. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4955. }
  4956. if _, ok := outentry["Coefficient(%)"]; ok {
  4957. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4958. }
  4959. if _, ok := outentry["Formula Template"]; ok {
  4960. dataexcel["ftname"] = outentry["Formula Template"]
  4961. }
  4962. if _, ok := outentry["Supplement Formula"]; ok {
  4963. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4964. }
  4965. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4966. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4967. }
  4968. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4969. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4970. }
  4971. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4972. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4973. }
  4974. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4975. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4976. }
  4977. if _, ok := outentry["Fifth Shift Ratio(%)"]; ok {
  4978. dataexcel["5"] = outentry["Fifth Shift Ratio(%)"]
  4979. }
  4980. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4981. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4982. }
  4983. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4984. if err != nil {
  4985. logs.Error(err)
  4986. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4987. return
  4988. }
  4989. if !existbar {
  4990. continue
  4991. }
  4992. _, 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()
  4993. if err != nil {
  4994. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4995. return
  4996. }
  4997. _, 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()
  4998. if err != nil {
  4999. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5000. return
  5001. }
  5002. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  5003. if err != nil {
  5004. logs.Error(err)
  5005. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  5006. return
  5007. }
  5008. if !existft {
  5009. continue
  5010. }
  5011. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  5012. if err != nil {
  5013. logs.Error(err)
  5014. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5015. return
  5016. }
  5017. if !ftexist {
  5018. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  5019. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5020. if err != nil {
  5021. logs.Error(err)
  5022. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5023. return
  5024. }
  5025. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5026. if err != nil {
  5027. logs.Error(err)
  5028. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5029. return
  5030. }
  5031. }
  5032. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5033. if err != nil {
  5034. logs.Error(err)
  5035. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5036. return
  5037. }
  5038. if !exist {
  5039. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  5040. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  5041. if err != nil {
  5042. logs.Error(err)
  5043. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5044. return
  5045. }
  5046. }
  5047. var feedpargs []interface{}
  5048. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  5049. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  5050. if _, ok := dataexcel["ftname"]; ok {
  5051. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  5052. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  5053. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  5054. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  5055. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5056. } else {
  5057. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  5058. }
  5059. if _, ok := dataexcel["ptsfname"]; ok {
  5060. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  5061. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  5062. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  5063. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  5064. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5065. } else {
  5066. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  5067. }
  5068. upFeedpSql += " where barname = ? and pastureid = ? "
  5069. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  5070. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  5071. if err != nil {
  5072. logs.Error(err)
  5073. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5074. return
  5075. }
  5076. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  5077. if err != nil {
  5078. logs.Error(err)
  5079. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5080. return
  5081. }
  5082. if !exist1 {
  5083. _, 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) `,
  5084. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5085. if err != nil {
  5086. logs.Error(err)
  5087. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5088. return
  5089. }
  5090. }
  5091. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5092. if err != nil {
  5093. logs.Error(err)
  5094. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5095. return
  5096. }
  5097. if !exist2 {
  5098. _, 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) `,
  5099. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5100. if err != nil {
  5101. logs.Error(err)
  5102. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5103. return
  5104. }
  5105. }
  5106. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5107. if err != nil {
  5108. logs.Error(err)
  5109. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5110. return
  5111. }
  5112. if !exist3 {
  5113. _, 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) `,
  5114. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5115. if err != nil {
  5116. logs.Error(err)
  5117. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5118. return
  5119. }
  5120. }
  5121. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5122. if err != nil {
  5123. logs.Error(err)
  5124. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5125. return
  5126. }
  5127. if !exist4 {
  5128. _, 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) `,
  5129. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5130. if err != nil {
  5131. logs.Error(err)
  5132. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5133. return
  5134. }
  5135. }
  5136. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5137. if err != nil {
  5138. logs.Error(err)
  5139. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5140. return
  5141. }
  5142. if !exist5 {
  5143. _, 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) `,
  5144. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5145. if err != nil {
  5146. logs.Error(err)
  5147. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5148. return
  5149. }
  5150. }
  5151. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5152. if err != nil {
  5153. logs.Error(err)
  5154. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5155. return
  5156. }
  5157. if !exist6 {
  5158. _, 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) `,
  5159. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5160. if err != nil {
  5161. logs.Error(err)
  5162. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5163. return
  5164. }
  5165. }
  5166. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5167. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5168. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5169. and pastureid = ? and times = ?`
  5170. var fpdargs1 []interface{}
  5171. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5172. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5173. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5174. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5175. if err != nil {
  5176. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5177. return
  5178. }
  5179. var fpdargs2 []interface{}
  5180. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5181. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5182. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5183. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5184. if err != nil {
  5185. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5186. return
  5187. }
  5188. var fpdargs3 []interface{}
  5189. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5190. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5191. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5192. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5193. if err != nil {
  5194. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5195. return
  5196. }
  5197. var fpdargs4 []interface{}
  5198. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5199. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5200. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5201. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5202. if err != nil {
  5203. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5204. return
  5205. }
  5206. var fpdargs5 []interface{}
  5207. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5208. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5209. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5210. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5211. if err != nil {
  5212. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5213. return
  5214. }
  5215. var fpdargs6 []interface{}
  5216. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5217. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5218. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5219. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5220. if err != nil {
  5221. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5222. return
  5223. }
  5224. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5225. 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()
  5226. if err != nil {
  5227. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5228. return
  5229. }
  5230. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5231. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5232. upFpdetailList := make([]*upFpdetail, 0)
  5233. for _, newfpd := range newList {
  5234. for _, oldfpd := range oldFpdList {
  5235. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5236. var oldweight, newweight float64
  5237. if oldfpd["weight"] != nil {
  5238. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5239. }
  5240. if newfpd["weight"] != nil {
  5241. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5242. }
  5243. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5244. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5245. Old: oldweight,
  5246. New: newweight,
  5247. Times: newfpd["times"].(int64),
  5248. Ptid: newfpd["ptid"].(int64),
  5249. Fweight: fweight,
  5250. Id: oldfpd["id"].(int64),
  5251. })
  5252. break
  5253. }
  5254. }
  5255. }
  5256. // fmt.Println(dataexcel["barname"])
  5257. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5258. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5259. }
  5260. }
  5261. if !isdone {
  5262. ok++
  5263. isdone = true
  5264. }
  5265. }
  5266. for barname, v := range dataList {
  5267. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5268. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5269. if err != nil {
  5270. logs.Error(err)
  5271. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5272. return
  5273. }
  5274. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5275. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5276. if err != nil {
  5277. logs.Error(err)
  5278. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5279. return
  5280. }
  5281. updateFpdetailByBar(pastureid, barname, v)
  5282. }
  5283. }
  5284. data := make(map[string]interface{})
  5285. data["result"] = queryData
  5286. data["success"] = ok
  5287. data["err_count"] = error
  5288. appG.Response(http.StatusOK, e.SUCCESS, data)
  5289. }
  5290. type upFpdetail struct {
  5291. Old float64
  5292. New float64
  5293. Times int64
  5294. Ptid int64
  5295. Fweight float64
  5296. Id int64
  5297. // Ptsid string
  5298. }
  5299. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5300. tx := restful.Engine.NewSession()
  5301. defer tx.Close()
  5302. tx.Begin()
  5303. 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 `,
  5304. pastureid, barname).Query().List()
  5305. if err != nil {
  5306. logs.Error(err)
  5307. }
  5308. for _, fpd := range fpdList {
  5309. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5310. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5311. pastureid, fpd["id"], fpd["times"]).Query().List()
  5312. if err != nil {
  5313. tx.Rollback()
  5314. logs.Error(err)
  5315. return err
  5316. }
  5317. var lweight float64
  5318. for _, lppland := range lpplandList {
  5319. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5320. lweight += lweight1
  5321. }
  5322. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5323. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5324. if fpdweight >= ptuse && lweight == ptuse {
  5325. continue
  5326. } else {
  5327. if lweight <= fpdweight {
  5328. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5329. if err != nil {
  5330. tx.Rollback()
  5331. logs.Error(err)
  5332. return err
  5333. }
  5334. } else {
  5335. weight := lweight - fpdweight
  5336. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5337. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5338. if err != nil {
  5339. tx.Rollback()
  5340. logs.Error(err)
  5341. return err
  5342. }
  5343. for _, lppland := range lpplandList {
  5344. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5345. if weight >= lpplandlweight {
  5346. weight = weight - lpplandlweight
  5347. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5348. if err != nil {
  5349. tx.Rollback()
  5350. logs.Error(err)
  5351. return err
  5352. }
  5353. } else {
  5354. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5355. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5356. if err != nil {
  5357. tx.Rollback()
  5358. logs.Error(err)
  5359. return err
  5360. }
  5361. weight = 0
  5362. break
  5363. }
  5364. }
  5365. }
  5366. }
  5367. }
  5368. for _, list := range dataList {
  5369. ftmap := make(map[string]interface{})
  5370. ftmap["old"] = list.Old
  5371. ftmap["new"] = list.New
  5372. ftmap["times"] = list.Times
  5373. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5374. ftmap["ptsid"] = ""
  5375. // fmt.Println(ftmap)
  5376. // 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 ,
  5377. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5378. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5379. // UNION
  5380. fpdDataList, err := tx.SQL(`
  5381. 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 ,
  5382. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5383. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5384. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5385. if err != nil {
  5386. tx.Rollback()
  5387. logs.Error(err)
  5388. }
  5389. for _, fpd := range fpdDataList {
  5390. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5391. // fttype := -1
  5392. // if fpd["fttype"].(string) == "1" {
  5393. fttype := 1
  5394. // }
  5395. var fweight float64
  5396. var lweight float64
  5397. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5398. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  5399. t.maxstirfeed,t.volume * (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  5400. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5401. join tmr t on t.id = lpp.tmrid
  5402. where lppland.fpdid =?
  5403. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5404. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5405. if err != nil {
  5406. tx.Rollback()
  5407. logs.Error(err)
  5408. }
  5409. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5410. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5411. // 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
  5412. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5413. var w float64
  5414. var status int
  5415. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5416. if weight >= 0 {
  5417. continue
  5418. }
  5419. w = weight
  5420. status = 0
  5421. } else {
  5422. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5423. // continue
  5424. // }
  5425. w = weight
  5426. status = 1
  5427. }
  5428. // for _, lppland := range lpplandtl1List {
  5429. // lweight += lppland.Lweight
  5430. // }
  5431. for _, lppland := range lpplandtl1List {
  5432. lpplandInfo := new(lpplandtlInfo)
  5433. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5434. lweight = lpplandInfo.Lweight
  5435. if status == 1 {
  5436. // if w <= lppland.Lweight {
  5437. if lppland.Maxweight <= lweight {
  5438. continue
  5439. }
  5440. if w+lweight <= lppland.Maxweight {
  5441. lppland.Lweight += w
  5442. lweight += w
  5443. fweight += w
  5444. w = 0
  5445. } else {
  5446. w = w - (lppland.Maxweight - lweight)
  5447. n := (lppland.Maxweight - lweight)
  5448. lppland.Lweight = lppland.Lweight + n
  5449. lweight += n
  5450. fweight += n
  5451. }
  5452. } else {
  5453. if lppland.Lweight == 0 {
  5454. continue
  5455. }
  5456. if w+lppland.Lweight >= 0 {
  5457. lppland.Lweight = lppland.Lweight + w
  5458. lweight = lweight + w
  5459. fweight = fweight + w
  5460. w = 0
  5461. } else {
  5462. w = w + lppland.Lweight
  5463. lweight = lweight - lppland.Lweight
  5464. fweight = fweight - lppland.Lweight
  5465. lppland.Lweight = 0
  5466. }
  5467. }
  5468. if lppland.Lweight > 0 {
  5469. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5470. if err != nil {
  5471. tx.Rollback()
  5472. logs.Error(err)
  5473. return err
  5474. }
  5475. } else {
  5476. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5477. if err != nil {
  5478. tx.Rollback()
  5479. logs.Error(err)
  5480. return err
  5481. }
  5482. }
  5483. if w == 0 {
  5484. break
  5485. }
  5486. }
  5487. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5488. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5489. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5490. if err != nil {
  5491. tx.Rollback()
  5492. logs.Error(err)
  5493. }
  5494. if w == 0 {
  5495. break
  5496. }
  5497. }
  5498. }
  5499. }
  5500. err = tx.Commit()
  5501. if err != nil {
  5502. logs.Error(err)
  5503. tx.Rollback()
  5504. return err
  5505. }
  5506. now := time.Now()
  5507. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5508. if err != nil {
  5509. logs.Error(err)
  5510. return nil
  5511. }
  5512. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5513. if err != nil {
  5514. logs.Error(err)
  5515. return nil
  5516. }
  5517. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5518. if err != nil {
  5519. logs.Error(err)
  5520. return nil
  5521. }
  5522. for _, newLpplandtl1 := range newLpplandtl1List {
  5523. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5524. background,cowcount,ccountradio,lweighthis,createdate)
  5525. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5526. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5527. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5528. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5529. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5530. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5531. if err != nil {
  5532. logs.Error(err)
  5533. // appG.Response(http.StatusOK, e.ERROR, false)
  5534. return err
  5535. }
  5536. }
  5537. for _, newFpd := range newFpdDataList {
  5538. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5539. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5540. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5541. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5542. if err != nil {
  5543. logs.Error(err)
  5544. // appG.Response(http.StatusOK, e.ERROR, false)
  5545. return err
  5546. }
  5547. }
  5548. for _, newFeedp := range newFeedpList {
  5549. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5550. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5551. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5552. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5553. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5554. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5555. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5556. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5557. if err != nil {
  5558. logs.Error(err)
  5559. // appG.Response(http.StatusOK, e.ERROR, false)
  5560. return err
  5561. }
  5562. }
  5563. return nil
  5564. }
  5565. func DeleteFTdetail(c *gin.Context) {
  5566. appG := app.Gin{C: c}
  5567. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5568. fsion := gofasion.NewFasion(string(dataByte))
  5569. parammaps := fsion.Get("parammaps")
  5570. pastureid := parammaps.Get("pastureid").ValueStr()
  5571. ftid := parammaps.Get("ftid").ValueStr()
  5572. tx := restful.Engine.NewSession()
  5573. defer tx.Close()
  5574. tx.Begin()
  5575. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5576. if err != nil {
  5577. tx.Rollback()
  5578. logs.Error(err)
  5579. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5580. return
  5581. }
  5582. if parammaps.Get("type").ValueStr() == "1" {
  5583. _, err := tx.SQL(`UPDATE feedp fp
  5584. set
  5585. fp.ftweight= IFNULL(IF(
  5586. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5587. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5588. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5589. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5590. ),0),fp.feedweight = IFNULL(IF(
  5591. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5592. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5593. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5594. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5595. ),0) +ifnull(fp.supplyweight,0)
  5596. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5597. if err != nil {
  5598. tx.Rollback()
  5599. logs.Error(err)
  5600. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5601. return
  5602. }
  5603. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5604. _, err = tx.SQL(`
  5605. UPDATE fpdetail fpd
  5606. INNER JOIN feedp fp
  5607. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5608. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5609. ptuse= 0
  5610. WHERE fp.pastureid = ? AND fp.ftid =?`, 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. } else {
  5618. _, err := tx.SQL(`UPDATE feedp fp
  5619. SET
  5620. fp.supplyweight= IFNULL(IF(
  5621. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5622. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5623. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5624. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5625. ),0),fp.feedweight = IFNULL(IF(
  5626. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5627. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5628. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5629. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5630. ),0) + ifnull(fp.supplyweight,0)
  5631. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5632. if err != nil {
  5633. tx.Rollback()
  5634. logs.Error(err)
  5635. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5636. return
  5637. }
  5638. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5639. _, err = tx.SQL(`
  5640. UPDATE fpdetail fpd
  5641. INNER JOIN feedp fp
  5642. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5643. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5644. ptsrate = 0
  5645. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5646. if err != nil {
  5647. tx.Rollback()
  5648. logs.Error(err)
  5649. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5650. return
  5651. }
  5652. }
  5653. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5654. if err != nil {
  5655. tx.Rollback()
  5656. logs.Error(err)
  5657. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5658. return
  5659. }
  5660. err = tx.Commit()
  5661. if err != nil {
  5662. tx.Rollback()
  5663. logs.Error(err)
  5664. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5665. return
  5666. }
  5667. appG.Response(http.StatusOK, e.SUCCESS, true)
  5668. }
  5669. func DeleteSpillageAll(c *gin.Context) {
  5670. appG := app.Gin{C: c}
  5671. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5672. fsion := gofasion.NewFasion(string(dataByte))
  5673. parammaps := fsion.Get("parammaps")
  5674. pastureid := parammaps.Get("pastureid").ValueStr()
  5675. times := parammaps.Get("times").ValueStr()
  5676. barid := parammaps.Get("barid").ValueStr()
  5677. tx := restful.Engine.NewSession()
  5678. defer tx.Close()
  5679. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5680. if err != nil {
  5681. logs.Error(err)
  5682. appG.Response(http.StatusOK, e.ERROR, false)
  5683. return
  5684. }
  5685. now := time.Now()
  5686. for _, item := range lpplandtl1List {
  5687. go func(item map[string]interface{}) {
  5688. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5689. background,cowcount,ccountradio,lweighthis,createdate)
  5690. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5691. item["pastureid"], item["lppid"], item["barid"],
  5692. item["barname"], item["fpdid"], item["fttype"],
  5693. item["lweight"], item["sort"], item["tmrid"],
  5694. item["tmrname"], item["background"], item["cowcount"],
  5695. item["ccountradio"], item["lweighthis"], now).Execute()
  5696. if err != nil {
  5697. logs.Error(err)
  5698. appG.Response(http.StatusOK, e.ERROR, false)
  5699. return
  5700. }
  5701. }(item)
  5702. }
  5703. tx.Begin()
  5704. _, 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()
  5705. if err != nil {
  5706. tx.Rollback()
  5707. logs.Error(err)
  5708. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5709. return
  5710. }
  5711. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5712. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5713. if err != nil {
  5714. tx.Rollback()
  5715. logs.Error(err)
  5716. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5717. return
  5718. }
  5719. err = tx.Commit()
  5720. if err != nil {
  5721. tx.Rollback()
  5722. logs.Error(err)
  5723. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5724. return
  5725. }
  5726. appG.Response(http.StatusOK, e.SUCCESS, true)
  5727. }
  5728. func GetTMRListEnableTypeAll(c *gin.Context) {
  5729. appG := app.Gin{C: c}
  5730. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5731. fsion := gofasion.NewFasion(string(dataByte))
  5732. parammaps := fsion.Get("parammaps")
  5733. pastureid := parammaps.Get("pastureid").ValueStr()
  5734. tx := restful.Engine.NewSession()
  5735. defer tx.Close()
  5736. dataList, err := tx.SQL(`SELECT
  5737. eqcode,
  5738. tname,
  5739. datacaptureno,
  5740. trim(tclassid) tclassid,
  5741. concat(tname,' / ',eqcode) tmrmix,
  5742. d.label tclassname,
  5743. maxstirfeed,
  5744. remark,
  5745. tmr.enable,
  5746. TRIM(tmr.id) id,
  5747. TRIM(tmr.pastureid)pastureid
  5748. FROM
  5749. tmr
  5750. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5751. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5752. ORDER BY id DESC`, pastureid).Query().List()
  5753. if err != nil {
  5754. logs.Error(err)
  5755. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5756. return
  5757. }
  5758. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5759. if err != nil {
  5760. logs.Error(err)
  5761. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5762. return
  5763. }
  5764. var carNum int64
  5765. for _, sysopt := range sysoptData {
  5766. if sysopt["inforvalue"] == nil {
  5767. carNum = 1
  5768. } else {
  5769. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5770. }
  5771. }
  5772. id := 200
  5773. n := 0
  5774. for i := carNum; i > 0; i-- {
  5775. id++
  5776. n++
  5777. data := make(map[string]interface{}, 0)
  5778. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5779. data["tname"] = fmt.Sprintf("任意车%d", n)
  5780. data["datacaptureno"] = -2
  5781. data["tclassid"] = -2
  5782. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5783. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5784. data["maxstirfeed"] = 100000
  5785. data["remark"] = fmt.Sprintf("任意车%d", n)
  5786. data["enable"] = 1
  5787. data["id"] = fmt.Sprintf("%d", id)
  5788. data["pastureid"] = pastureid
  5789. // data := make(map[string]interface{}, 0)
  5790. // data["eqcode"] = fmt.Sprintf("AnyCar%d", n)
  5791. // data["tname"] = fmt.Sprintf("AnyCar%d", n)
  5792. // data["datacaptureno"] = -2
  5793. // data["tclassid"] = -2
  5794. // data["tmrmix"] = fmt.Sprintf("AnyCar%d", n)
  5795. // data["tclassname"] = fmt.Sprintf("AnyCar%d", n)
  5796. // data["maxstirfeed"] = 100000
  5797. // data["remark"] = fmt.Sprintf("AnyCar%d", n)
  5798. // data["enable"] = 1
  5799. // data["id"] = fmt.Sprintf("%d", id)
  5800. // data["pastureid"] = pastureid
  5801. dataList = append(dataList, data)
  5802. }
  5803. // UNION ALL
  5804. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5805. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5806. }
  5807. func GetFeedpHistory(c *gin.Context) {
  5808. appG := app.Gin{C: c}
  5809. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5810. fsion := gofasion.NewFasion(string(dataByte))
  5811. // parammaps := fsion.Get("parammaps")
  5812. bar := fsion.Get("barname").ValueStr()
  5813. startDate := fsion.Get("startDate").ValueStr()
  5814. endDate := fsion.Get("endDate").ValueStr()
  5815. tx := restful.Engine.NewSession()
  5816. defer tx.Close()
  5817. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5818. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5819. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5820. if err != nil {
  5821. logs.Error(err)
  5822. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5823. return
  5824. }
  5825. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5826. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5827. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5828. if err != nil {
  5829. logs.Error(err)
  5830. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5831. return
  5832. }
  5833. for _, feedp := range feedpList {
  5834. // LastftList, err := tx.SQL(` select tname ,id
  5835. // from feedtemplethistory where id = ?
  5836. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5837. // if err != nil {
  5838. // logs.Error(err)
  5839. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5840. // return
  5841. // }
  5842. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5843. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5844. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5845. if err != nil {
  5846. logs.Error(err)
  5847. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5848. return
  5849. }
  5850. var ftname interface{}
  5851. ftnamestatus := 0
  5852. ftname = feedp["ftname"]
  5853. var lastftid int64
  5854. if len(nextfeedpList) > 0 {
  5855. for _, ft := range nextfeedpList {
  5856. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5857. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5858. lastftid = ft["ftid"].(int64)
  5859. ftnamestatus = 1
  5860. break
  5861. }
  5862. }
  5863. }
  5864. for i, fpd := range fpdList {
  5865. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5866. fpd["weightstatus"] = 0
  5867. fpd["tratiostatus"] = 0
  5868. fpd["ftnamestatus"] = ftnamestatus
  5869. for k, fpd2 := range fpdList {
  5870. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5871. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5872. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5873. fpd["weightstatus"] = 1
  5874. }
  5875. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5876. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5877. fpd["tratiostatus"] = 1
  5878. }
  5879. break
  5880. }
  5881. }
  5882. fpd["barid"] = feedp["barid"]
  5883. fpd["barname"] = feedp["barname"]
  5884. fpd["ccount"] = feedp["ccount"]
  5885. fpd["ratio"] = feedp["ratio"]
  5886. fpd["ccountratio"] = feedp["ccountratio"]
  5887. fpd["ftid"] = feedp["ftid"]
  5888. fpd["ftname"] = ftname
  5889. fpd["ccountstatus"] = 0
  5890. fpd["ccountratiostatus"] = 0
  5891. fpd["ratiostatus"] = 0
  5892. fpd["ftnamestatus"] = 0
  5893. fpd["lastftid"] = lastftid
  5894. for _, next := range nextfeedpList {
  5895. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5896. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5897. fpd["ccountstatus"] = 1
  5898. }
  5899. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5900. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5901. fpd["ccountratiostatus"] = 1
  5902. }
  5903. if next["ratio"].(string) != fpd["ratio"].(string) {
  5904. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5905. fpd["ratiostatus"] = 1
  5906. }
  5907. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5908. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5909. // fpd["ftnamestatus"] = 1
  5910. // }
  5911. }
  5912. }
  5913. }
  5914. }
  5915. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5916. }
  5917. // func GetLpplandtl1History(c *gin.Context) {
  5918. // appG := app.Gin{C: c}
  5919. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5920. // fsion := gofasion.NewFasion(string(dataByte))
  5921. // // parammaps := fsion.Get("parammaps")
  5922. // barid := fsion.Get("barid").ValueStr()
  5923. // startDate := fsion.Get("startDate").ValueStr()
  5924. // endDate := fsion.Get("endDate").ValueStr()
  5925. // tx := restful.Engine.NewSession()
  5926. // defer tx.Close()
  5927. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5928. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5929. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5930. // // if err != nil {
  5931. // // logs.Error(err)
  5932. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5933. // // return
  5934. // // }
  5935. // // for _, feedp := range feedpList {
  5936. // // fmt.Println(feedp)
  5937. // // for i, fpd := range fpdList {
  5938. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5939. // // for k, fpd2 := range fpdList {
  5940. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5941. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5942. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5943. // // }
  5944. // // break
  5945. // // }
  5946. // // }
  5947. // // fpd["barid"] = feedp["barid"]
  5948. // // fpd["barname"] = feedp["barname"]
  5949. // // fpd["ccount"] = feedp["ccount"]
  5950. // // fpd["ratio"] = feedp["ratio"]
  5951. // // fpd["ccountratio"] = feedp["ccountratio"]
  5952. // // fpd["ftid"] = feedp["ftid"]
  5953. // // fpd["ftname"] = feedp["ftname"]
  5954. // // }
  5955. // // }
  5956. // // }
  5957. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5958. // }
  5959. func GetRemind(c *gin.Context) {
  5960. appG := app.Gin{C: c}
  5961. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5962. fsion := gofasion.NewFasion(string(dataByte))
  5963. parammaps := fsion.Get("parammaps")
  5964. pastureid := parammaps.Get("pastureid").ValueStr()
  5965. tx := restful.Engine.NewSession()
  5966. defer tx.Close()
  5967. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5968. if err != nil {
  5969. logs.Error(err)
  5970. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5971. return
  5972. }
  5973. // pastureid = "3"
  5974. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5975. if err != nil {
  5976. logs.Error(err)
  5977. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5978. return
  5979. }
  5980. defer resp.Body.Close()
  5981. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5982. buf.ReadFrom(resp.Body)
  5983. fmt.Println(string(buf.Bytes()))
  5984. respMap := make(map[string]interface{}, 0)
  5985. err = json.Unmarshal(buf.Bytes(), &respMap)
  5986. if err != nil {
  5987. logs.Error(err)
  5988. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5989. return
  5990. }
  5991. for _, data := range dataList {
  5992. r := make(map[string]interface{}, 0)
  5993. r["sys_name"] = ""
  5994. r["service_id"] = ""
  5995. r["pasture_id"] = ""
  5996. r["type_name"] = ""
  5997. r["remind_type_id"] = ""
  5998. r["remind_type"] = ""
  5999. r["push_date"] = ""
  6000. r["push_time"] = ""
  6001. r["interval_time"] = ""
  6002. r["push_limit"] = ""
  6003. r["template_id"] = ""
  6004. r["roles_id"] = ""
  6005. r["users_id"] = ""
  6006. r["date_type"] = ""
  6007. r["cycle_type"] = ""
  6008. data["data"] = r
  6009. for _, resp := range respMap["data"].([]interface{}) {
  6010. resp1 := resp.(map[string]interface{})
  6011. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  6012. if resp1["push_time"] == nil {
  6013. resp1["push_time"] = ""
  6014. }
  6015. data["data"] = resp1
  6016. break
  6017. }
  6018. }
  6019. }
  6020. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  6021. }
  6022. type NoticeMsgtype struct {
  6023. SysName string `json:"sys_name"`
  6024. PastureId int64 `json:"pasture_id"`
  6025. ServiceId int64 `json:"service_id"`
  6026. TypeName string `json:"type_name"`
  6027. RemindType int64 `json:"remind_type"`
  6028. PushDate int64 `json:"push_date"`
  6029. PushTime string `json:"push_time"`
  6030. IntervalTime int64 `json:"interval_time"`
  6031. PushLimit int64 `json:"push_limit"`
  6032. TemplateId string `json:"template_id"`
  6033. UsersId string `json:"users_id"`
  6034. DateType int64 `json:"date_type"`
  6035. CycleType int64 `json:"cycle_type"`
  6036. DelayTime int64 `json:"delay_time"`
  6037. Status int64 `json:"status"`
  6038. }
  6039. func UpdateRemind(c *gin.Context) {
  6040. appG := app.Gin{C: c}
  6041. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6042. parammaps := gofasion.NewFasion(string(dataByte))
  6043. // parammaps := fsion.Get("parammaps")
  6044. // user := parammaps.Get("user").ValueStr()
  6045. id := parammaps.Get("id").ValueInt64()
  6046. noticeMsgtype := new(NoticeMsgtype)
  6047. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  6048. noticeMsgtype.ServiceId = id
  6049. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  6050. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  6051. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  6052. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  6053. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  6054. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  6055. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  6056. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  6057. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  6058. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  6059. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  6060. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  6061. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  6062. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  6063. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  6064. //TODO
  6065. noticeMsgtype.SysName = "tmrWatch"
  6066. userList := parammaps.Get("user").Array()
  6067. var userstr []string
  6068. for _, user := range userList {
  6069. userstr = append(userstr, user.ValueStr())
  6070. }
  6071. tx := restful.Engine.NewSession()
  6072. defer tx.Close()
  6073. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  6074. if err != nil {
  6075. logs.Error(err)
  6076. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6077. return
  6078. }
  6079. // var jsonStr = []byte(noticeMsgtype
  6080. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  6081. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  6082. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  6083. req.Header.Set("Content-Type", "application/json")
  6084. client := &http.Client{}
  6085. resp, err := client.Do(req)
  6086. if err != nil {
  6087. logs.Error(err)
  6088. }
  6089. defer resp.Body.Close()
  6090. body, _ := ioutil.ReadAll(resp.Body)
  6091. fmt.Println("response Body:", string(body))
  6092. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  6093. if err != nil {
  6094. logs.Error(err)
  6095. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6096. return
  6097. }
  6098. defer getresp.Body.Close()
  6099. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6100. buf.ReadFrom(getresp.Body)
  6101. // fmt.Println(string(buf.Bytes()))
  6102. respMap := make(map[string]interface{}, 0)
  6103. err = json.Unmarshal(buf.Bytes(), &respMap)
  6104. if err != nil {
  6105. logs.Error(err)
  6106. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6107. return
  6108. }
  6109. for _, resp := range respMap["data"].([]interface{}) {
  6110. resp1 := resp.(map[string]interface{})
  6111. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6112. if err != nil {
  6113. logs.Error(err)
  6114. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6115. return
  6116. }
  6117. }
  6118. appG.Response(http.StatusOK, e.SUCCESS, true)
  6119. }
  6120. func GetSpillageallHistory(c *gin.Context) {
  6121. appG := app.Gin{C: c}
  6122. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6123. parammaps := gofasion.NewFasion(string(dataByte))
  6124. barname := parammaps.Get("barname").ValueStr()
  6125. pastureid := parammaps.Get("pastureid").ValueStr()
  6126. startdate := parammaps.Get("startDate").ValueStr()
  6127. enddate := parammaps.Get("endDate").ValueStr()
  6128. tx := restful.Engine.NewSession()
  6129. defer tx.Close()
  6130. 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
  6131. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6132. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6133. if err != nil {
  6134. logs.Error(err)
  6135. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6136. return
  6137. }
  6138. respMap := make([]map[string]interface{}, 0)
  6139. data := make(map[interface{}]interface{})
  6140. for _, history := range historyList {
  6141. data[history["createdate"]] = history["createdate"]
  6142. }
  6143. createList := []string{}
  6144. for _, v := range data {
  6145. createList = append(createList, v.(string))
  6146. }
  6147. // sort.Sort()
  6148. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6149. sort.Slice(createList, func(i, j int) bool {
  6150. return createList[i] > createList[j]
  6151. })
  6152. for _, v := range createList {
  6153. a := make(map[string]interface{})
  6154. a["createdate"] = data[v]
  6155. // createList = append(createList, v.(string))
  6156. respMap = append(respMap, a)
  6157. }
  6158. number := 0
  6159. dataMap := make([]interface{}, 0)
  6160. for k, resp := range respMap {
  6161. createdate := resp["createdate"].(string)
  6162. var nextcreatedate string
  6163. if len(respMap) > k+1 {
  6164. nextcreatedate = respMap[k+1]["createdate"].(string)
  6165. }
  6166. // dataList := make(map[string][]interface{})
  6167. // list := make(map[string]interface{})
  6168. times := make(map[interface{}]int)
  6169. for _, history := range historyList {
  6170. // List := make(map[interface{}][]interface{})
  6171. i := 0
  6172. if history["createdate"].(string) == createdate {
  6173. times[history["times"]]++
  6174. data := make(map[string]interface{})
  6175. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6176. // exist := false
  6177. if nextcreatedate != "" {
  6178. for _, history1 := range historyList {
  6179. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6180. history1["times"].(int64) == history["times"].(int64) {
  6181. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6182. break
  6183. // exist = true
  6184. }
  6185. }
  6186. }
  6187. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6188. i++
  6189. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6190. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6191. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6192. // resp["times"] = history["times"]
  6193. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6194. data1 := make(map[string]interface{})
  6195. data1["times"] = history["times"]
  6196. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6197. data1["createdate"] = resp["createdate"]
  6198. // fmt.Println(dataList)
  6199. dataMap = append(dataMap, data1)
  6200. }
  6201. if i > number {
  6202. number = i
  6203. }
  6204. // respMap = append(respMap, dataList)
  6205. }
  6206. // for k, data := range dataList {
  6207. // resp[k] = data
  6208. // }
  6209. // resp["data"] = dataList
  6210. }
  6211. // resp := make(map[string]interface{})
  6212. // sort.Strings(createList)
  6213. //
  6214. // for _, create := range createList {
  6215. // for _, r := range respMap {
  6216. // if create == r["createdate"].(string) {
  6217. // resp[create] = r
  6218. // break
  6219. // }
  6220. // }
  6221. // }
  6222. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6223. var trainsList []interface{}
  6224. for i := 0; i < number; i++ {
  6225. trains := make(map[string]interface{})
  6226. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6227. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6228. trainsList = append(trainsList, trains)
  6229. }
  6230. respdata := make(map[string]interface{})
  6231. respdata["data"] = dataMap
  6232. respdata["trains"] = trainsList
  6233. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6234. }
  6235. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6236. appG := app.Gin{C: c}
  6237. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6238. parammaps := gofasion.NewFasion(string(dataByte))
  6239. ftid := parammaps.Get("ftid").ValueInt64()
  6240. lastftid := parammaps.Get("lastftid").ValueInt64()
  6241. pastureid := parammaps.Get("pastureid").ValueInt64()
  6242. // createdate := parammaps.Get("createdate").ValueStr()
  6243. tx := restful.Engine.NewSession()
  6244. defer tx.Close()
  6245. data := make(map[string]interface{})
  6246. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6247. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6248. if err != nil {
  6249. logs.Error(err)
  6250. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6251. return
  6252. }
  6253. feedtemplet := make(map[string]interface{})
  6254. for _, f := range feedtempletList {
  6255. feedtemplet = f
  6256. }
  6257. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  6258. if err != nil {
  6259. logs.Error(err)
  6260. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6261. return
  6262. }
  6263. feedtemplet["fit"] = fitList
  6264. data["current"] = feedtemplet
  6265. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6266. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6267. if err != nil {
  6268. logs.Error(err)
  6269. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6270. return
  6271. }
  6272. lastfeedtemplet := make(map[string]interface{})
  6273. for _, f := range lastfeedtempletList {
  6274. lastfeedtemplet = f
  6275. }
  6276. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  6277. if err != nil {
  6278. logs.Error(err)
  6279. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6280. return
  6281. }
  6282. lastfeedtemplet["fit"] = lastfitList
  6283. data["last"] = lastfeedtemplet
  6284. appG.Response(http.StatusOK, e.SUCCESS, data)
  6285. }
  6286. func GetFeedtempletHistory(c *gin.Context) {
  6287. appG := app.Gin{C: c}
  6288. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6289. parammaps := gofasion.NewFasion(string(dataByte))
  6290. ftid := parammaps.Get("ftid").ValueStr()
  6291. pastureid := parammaps.Get("pastureid").ValueInt64()
  6292. start := parammaps.Get("startdate").ValueStr()
  6293. end := parammaps.Get("enddate").ValueStr()
  6294. tx := restful.Engine.NewSession()
  6295. defer tx.Close()
  6296. 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 ?
  6297. and id = ? and pastureid = ? order by createdate desc `,
  6298. start, end, ftid, pastureid).Query().List()
  6299. if err != nil {
  6300. logs.Error(err)
  6301. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6302. return
  6303. }
  6304. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6305. ftid, pastureid).Query().List()
  6306. if err != nil {
  6307. logs.Error(err)
  6308. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6309. return
  6310. }
  6311. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6312. for i, ft := range ftList {
  6313. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6314. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6315. (select empname from user where id = fit.userId) empname,
  6316. 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
  6317. where fit.fitid = ?
  6318. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6319. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6320. if err != nil {
  6321. logs.Error(err)
  6322. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6323. return
  6324. }
  6325. ft["createdate"] = ft["createdate1"]
  6326. // data["tname"] = ft["tname"]
  6327. // data["tcode"] = ft["tcode"]
  6328. // data["tcolor"] = ft["tcolor"]
  6329. // data["fttype"] = ft["fttype"]
  6330. // data["ccname"] = ft["ccname"]
  6331. // data["source"] = ft["source"]
  6332. // data["version"] = ft["version"]
  6333. // data["remark"] = ft["remark"]
  6334. for n, ft2 := range ftList {
  6335. if i < n {
  6336. if ft["tname"].(string) != ft2["tname"].(string) {
  6337. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6338. }
  6339. if _, ok := ft["tcode"]; ok {
  6340. if _, ok := ft2["tcode"]; ok {
  6341. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6342. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6343. }
  6344. }
  6345. }
  6346. if _, ok := ft["tcolor"]; ok {
  6347. if _, ok := ft2["tcolor"]; ok {
  6348. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6349. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6350. }
  6351. }
  6352. }
  6353. if _, ok := ft["fttype"]; ok {
  6354. if _, ok := ft2["fttype"]; ok {
  6355. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6356. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6357. }
  6358. }
  6359. }
  6360. if _, ok := ft["ccname"]; ok {
  6361. if _, ok := ft2["ccname"]; ok {
  6362. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6363. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6364. }
  6365. }
  6366. }
  6367. if _, ok := ft["source"]; ok {
  6368. if _, ok := ft2["source"]; ok {
  6369. if ft["source"].(string) != ft2["source"].(string) {
  6370. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6371. }
  6372. }
  6373. }
  6374. if _, ok := ft["version"]; ok {
  6375. if _, ok := ft2["version"]; ok {
  6376. if ft["version"].(int64) != ft2["version"].(int64) {
  6377. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6378. }
  6379. }
  6380. }
  6381. if _, ok := ft["remark"]; ok {
  6382. if _, ok := ft2["remark"]; ok {
  6383. if ft["remark"].(string) != ft2["remark"].(string) {
  6384. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6385. }
  6386. }
  6387. }
  6388. break
  6389. }
  6390. }
  6391. dataList := make([]map[string]interface{}, 0)
  6392. if len(fithisList) > 0 {
  6393. for _, fit := range fithisList {
  6394. data := make(map[string]interface{})
  6395. data["feedgroup"] = fit["feedgroup"]
  6396. data["fname"] = fit["fname"]
  6397. data["empname"] = fit["empname"]
  6398. if fit["Eweight"] != nil {
  6399. if fit["Eweight"].(string) != fit["weight"].(string) {
  6400. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6401. } else {
  6402. data["fweight"] = fit["Eweight"]
  6403. }
  6404. data["fweightstatus"] = 1
  6405. } else {
  6406. data["fweight"] = fit["weight"]
  6407. data["fweightstatus"] = 0
  6408. }
  6409. data["autosecond"] = fit["autosecond"]
  6410. // data["tname"] = ft["tname"]
  6411. // data["tcode"] = ft["tcode"]
  6412. // data["tcolor"] = ft["tcolor"]
  6413. // data["fttype"] = ft["fttype"]
  6414. // data["ccname"] = ft["ccname"]
  6415. // data["source"] = ft["source"]
  6416. // data["version"] = ft["version"]
  6417. // data["remark"] = ft["remark"]
  6418. // data["createdate"] = ft["createdate1"]
  6419. // ft["fit"] = data
  6420. dataList = append(dataList, data)
  6421. }
  6422. } else {
  6423. for _, fit := range ftdetailList {
  6424. data := make(map[string]interface{})
  6425. data["feedgroup"] = fit["feedgroup"]
  6426. data["fname"] = fit["fname"]
  6427. // if fit["Eweight"] != nil {
  6428. // data["weight"] = fit["Eweight"]
  6429. // } else {
  6430. data["fweight"] = fit["fweight"]
  6431. // }
  6432. data["autosecond"] = fit["autosecond"]
  6433. // ft["fit"] = data
  6434. dataList = append(dataList, data)
  6435. }
  6436. }
  6437. ft["fit"] = dataList
  6438. }
  6439. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6440. }
  6441. func UpdateMaterialTMR(c *gin.Context) {
  6442. appG := app.Gin{C: c}
  6443. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6444. parammaps := gofasion.NewFasion(string(dataByte))
  6445. tmrid := parammaps.Get("tmrid").ValueStr()
  6446. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6447. lppid := parammaps.Get("lppid").ValueStr()
  6448. times := parammaps.Get("times").ValueStr()
  6449. pastureid := parammaps.Get("pastureid").ValueStr()
  6450. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6451. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6452. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6453. tx := restful.Engine.NewSession()
  6454. defer tx.Close()
  6455. tx.Begin()
  6456. if tmrid != "1000" {
  6457. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6458. if err != nil {
  6459. logs.Error(err)
  6460. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6461. return
  6462. }
  6463. var maxstirfeed float64
  6464. for _, tmr := range tmrList {
  6465. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6466. }
  6467. if status == 0 {
  6468. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6469. if err != nil {
  6470. tx.Rollback()
  6471. logs.Error(err)
  6472. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6473. return
  6474. }
  6475. var lweight float64
  6476. for _, item := range lpplandtl1List {
  6477. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6478. lweight += fl
  6479. }
  6480. if lweight > maxstirfeed {
  6481. lweight = lweight - maxstirfeed
  6482. } else {
  6483. lweight = 0
  6484. }
  6485. if lweight > 0 {
  6486. lweight1 := lweight / float64(len(lpplandtl1List))
  6487. number := 0
  6488. for _, item := range lpplandtl1List {
  6489. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6490. if lweight1 >= fl {
  6491. number++
  6492. }
  6493. }
  6494. lweight := lweight / float64((len(lpplandtl1List) - number))
  6495. for _, item := range lpplandtl1List {
  6496. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6497. if lweight1 >= fl {
  6498. continue
  6499. }
  6500. if tmrtype == "1" {
  6501. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6502. if err != nil {
  6503. tx.Rollback()
  6504. logs.Error(err)
  6505. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6506. return
  6507. }
  6508. } else if tmrtype == "2" {
  6509. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6510. if err != nil {
  6511. tx.Rollback()
  6512. logs.Error(err)
  6513. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6514. return
  6515. }
  6516. }
  6517. if item["fttype"].(int64) == 0 {
  6518. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6519. if err != nil {
  6520. tx.Rollback()
  6521. logs.Error(err)
  6522. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6523. return
  6524. }
  6525. } else {
  6526. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6527. if err != nil {
  6528. tx.Rollback()
  6529. logs.Error(err)
  6530. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6531. return
  6532. }
  6533. }
  6534. }
  6535. } else {
  6536. for _, item := range lpplandtl1List {
  6537. // 自走式
  6538. if tmrtype == "1" {
  6539. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6540. if err != nil {
  6541. logs.Error(err)
  6542. tx.Rollback()
  6543. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6544. return
  6545. }
  6546. } else if tmrtype == "2" {
  6547. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6548. if err != nil {
  6549. logs.Error(err)
  6550. tx.Rollback()
  6551. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6552. return
  6553. }
  6554. }
  6555. }
  6556. }
  6557. } else if status == 1 {
  6558. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6559. if err != nil {
  6560. logs.Error(err)
  6561. tx.Rollback()
  6562. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6563. return
  6564. }
  6565. var lweight float64
  6566. for _, item := range lpplandtl1List {
  6567. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6568. lweight += fl
  6569. }
  6570. if lweight > maxstirfeed {
  6571. lweight = lweight - maxstirfeed
  6572. } else {
  6573. lweight = 0
  6574. }
  6575. for _, item := range lpplandtl1List {
  6576. if lweight > 0 {
  6577. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6578. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6579. if fl >= lweight {
  6580. item["lweight"] = fl - lweight
  6581. lweight = 0
  6582. if tmrtype == "1" {
  6583. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6584. if err != nil {
  6585. logs.Error(err)
  6586. tx.Rollback()
  6587. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6588. return
  6589. }
  6590. } else if tmrtype == "2" {
  6591. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6592. if err != nil {
  6593. logs.Error(err)
  6594. tx.Rollback()
  6595. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6596. return
  6597. }
  6598. }
  6599. if item["fttype"].(int64) == 0 {
  6600. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6601. if err != nil {
  6602. logs.Error(err)
  6603. tx.Rollback()
  6604. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6605. return
  6606. }
  6607. } else {
  6608. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6609. if err != nil {
  6610. logs.Error(err)
  6611. tx.Rollback()
  6612. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6613. return
  6614. }
  6615. }
  6616. } else {
  6617. lweight = lweight - fl
  6618. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6619. if err != nil {
  6620. logs.Error(err)
  6621. tx.Rollback()
  6622. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6623. return
  6624. }
  6625. if item["fttype"].(int64) == 0 {
  6626. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6627. if err != nil {
  6628. logs.Error(err)
  6629. tx.Rollback()
  6630. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6631. return
  6632. }
  6633. } else {
  6634. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6635. if err != nil {
  6636. logs.Error(err)
  6637. tx.Rollback()
  6638. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6639. return
  6640. }
  6641. }
  6642. }
  6643. } else {
  6644. // 自走式
  6645. if tmrtype == "1" {
  6646. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6647. if err != nil {
  6648. logs.Error(err)
  6649. tx.Rollback()
  6650. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6651. return
  6652. }
  6653. } else if tmrtype == "2" {
  6654. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6655. if err != nil {
  6656. logs.Error(err)
  6657. tx.Rollback()
  6658. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6659. return
  6660. }
  6661. }
  6662. }
  6663. }
  6664. } else {
  6665. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6666. if err != nil {
  6667. logs.Error(err)
  6668. tx.Rollback()
  6669. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6670. return
  6671. }
  6672. for _, item := range lpplandtl1List {
  6673. if item["fttype"].(int64) == 0 {
  6674. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6675. if err != nil {
  6676. logs.Error(err)
  6677. tx.Rollback()
  6678. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6679. return
  6680. }
  6681. } else {
  6682. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6683. if err != nil {
  6684. logs.Error(err)
  6685. tx.Rollback()
  6686. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6687. return
  6688. }
  6689. }
  6690. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6691. if err != nil {
  6692. logs.Error(err)
  6693. tx.Rollback()
  6694. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6695. return
  6696. }
  6697. }
  6698. }
  6699. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6700. if err != nil {
  6701. logs.Error(err)
  6702. tx.Rollback()
  6703. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6704. return
  6705. }
  6706. } else {
  6707. if status == 2 {
  6708. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6709. if err != nil {
  6710. logs.Error(err)
  6711. tx.Rollback()
  6712. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6713. return
  6714. }
  6715. for _, item := range lpplandtl1List {
  6716. if item["fttype"].(int64) == 0 {
  6717. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6718. if err != nil {
  6719. logs.Error(err)
  6720. tx.Rollback()
  6721. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6722. return
  6723. }
  6724. } else {
  6725. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6726. if err != nil {
  6727. logs.Error(err)
  6728. tx.Rollback()
  6729. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6730. return
  6731. }
  6732. }
  6733. }
  6734. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6735. if err != nil {
  6736. logs.Error(err)
  6737. tx.Rollback()
  6738. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6739. return
  6740. }
  6741. } else {
  6742. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6743. if err != nil {
  6744. logs.Error(err)
  6745. tx.Rollback()
  6746. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6747. return
  6748. }
  6749. }
  6750. }
  6751. err := tx.Commit()
  6752. if err != nil {
  6753. logs.Error(err)
  6754. tx.Rollback()
  6755. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6756. return
  6757. }
  6758. appG.Response(http.StatusOK, e.SUCCESS, true)
  6759. }
  6760. func UpdateMaterialTMRDate(c *gin.Context) {
  6761. appG := app.Gin{C: c}
  6762. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6763. parammaps := gofasion.NewFasion(string(dataByte))
  6764. tmrid := parammaps.Get("tmrid").ValueStr()
  6765. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6766. lppid := parammaps.Get("lppid").ValueStr()
  6767. times := parammaps.Get("times").ValueStr()
  6768. pastureid := parammaps.Get("pastureid").ValueStr()
  6769. date := parammaps.Get("date").ValueStr()
  6770. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6771. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6772. tx := restful.Engine.NewSession()
  6773. defer tx.Close()
  6774. tx.Begin()
  6775. if tmrid != "1000" {
  6776. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6777. if err != nil {
  6778. logs.Error(err)
  6779. tx.Rollback()
  6780. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6781. return
  6782. }
  6783. var maxstirfeed float64
  6784. for _, tmr := range tmrList {
  6785. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6786. }
  6787. if status == 0 {
  6788. 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()
  6789. if err != nil {
  6790. logs.Error(err)
  6791. tx.Rollback()
  6792. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6793. return
  6794. }
  6795. var lweight float64
  6796. for _, item := range lpplandtl1List {
  6797. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6798. lweight += fl
  6799. }
  6800. if lweight > maxstirfeed {
  6801. lweight = lweight - maxstirfeed
  6802. } else {
  6803. lweight = 0
  6804. }
  6805. if lweight > 0 {
  6806. lweight1 := lweight / float64(len(lpplandtl1List))
  6807. number := 0
  6808. for _, item := range lpplandtl1List {
  6809. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6810. if lweight1 >= fl {
  6811. number++
  6812. }
  6813. }
  6814. lweight := lweight / float64((len(lpplandtl1List) - number))
  6815. for _, item := range lpplandtl1List {
  6816. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6817. if lweight1 >= fl {
  6818. continue
  6819. }
  6820. if tmrtype == "1" {
  6821. _, 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()
  6822. if err != nil {
  6823. logs.Error(err)
  6824. tx.Rollback()
  6825. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6826. return
  6827. }
  6828. } else if tmrtype == "2" {
  6829. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6830. if err != nil {
  6831. logs.Error(err)
  6832. tx.Rollback()
  6833. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6834. return
  6835. }
  6836. }
  6837. if item["fttype"].(int64) == 0 {
  6838. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], 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 {
  6846. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], 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. } else {
  6856. for _, item := range lpplandtl1List {
  6857. // 自走式
  6858. if tmrtype == "1" {
  6859. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6860. if err != nil {
  6861. logs.Error(err)
  6862. tx.Rollback()
  6863. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6864. return
  6865. }
  6866. } else if tmrtype == "2" {
  6867. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6868. if err != nil {
  6869. logs.Error(err)
  6870. tx.Rollback()
  6871. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6872. return
  6873. }
  6874. }
  6875. }
  6876. }
  6877. } else if status == 1 {
  6878. 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()
  6879. if err != nil {
  6880. logs.Error(err)
  6881. tx.Rollback()
  6882. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6883. return
  6884. }
  6885. var lweight float64
  6886. for _, item := range lpplandtl1List {
  6887. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6888. lweight += fl
  6889. }
  6890. if lweight > maxstirfeed {
  6891. lweight = lweight - maxstirfeed
  6892. } else {
  6893. lweight = 0
  6894. }
  6895. for _, item := range lpplandtl1List {
  6896. if lweight > 0 {
  6897. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6898. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6899. if fl >= lweight {
  6900. item["lweight"] = fl - lweight
  6901. lweight = 0
  6902. if tmrtype == "1" {
  6903. _, 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()
  6904. if err != nil {
  6905. logs.Error(err)
  6906. tx.Rollback()
  6907. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6908. return
  6909. }
  6910. } else if tmrtype == "2" {
  6911. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6912. if err != nil {
  6913. logs.Error(err)
  6914. tx.Rollback()
  6915. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6916. return
  6917. }
  6918. }
  6919. if item["fttype"].(int64) == 0 {
  6920. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6921. if err != nil {
  6922. logs.Error(err)
  6923. tx.Rollback()
  6924. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6925. return
  6926. }
  6927. } else {
  6928. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6929. if err != nil {
  6930. logs.Error(err)
  6931. tx.Rollback()
  6932. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6933. return
  6934. }
  6935. }
  6936. } else {
  6937. lweight = lweight - fl
  6938. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6939. if err != nil {
  6940. logs.Error(err)
  6941. tx.Rollback()
  6942. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6943. return
  6944. }
  6945. if item["fttype"].(int64) == 0 {
  6946. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6947. if err != nil {
  6948. logs.Error(err)
  6949. tx.Rollback()
  6950. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6951. return
  6952. }
  6953. } else {
  6954. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6955. if err != nil {
  6956. logs.Error(err)
  6957. tx.Rollback()
  6958. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6959. return
  6960. }
  6961. }
  6962. }
  6963. } else {
  6964. // 自走式
  6965. if tmrtype == "1" {
  6966. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6967. if err != nil {
  6968. logs.Error(err)
  6969. tx.Rollback()
  6970. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6971. return
  6972. }
  6973. } else if tmrtype == "2" {
  6974. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6975. if err != nil {
  6976. logs.Error(err)
  6977. tx.Rollback()
  6978. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6979. return
  6980. }
  6981. }
  6982. }
  6983. }
  6984. } else {
  6985. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6986. if err != nil {
  6987. logs.Error(err)
  6988. tx.Rollback()
  6989. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6990. return
  6991. }
  6992. for _, item := range lpplandtl1List {
  6993. if item["fttype"].(int64) == 0 {
  6994. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6995. if err != nil {
  6996. logs.Error(err)
  6997. tx.Rollback()
  6998. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6999. return
  7000. }
  7001. } else {
  7002. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7003. if err != nil {
  7004. logs.Error(err)
  7005. tx.Rollback()
  7006. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7007. return
  7008. }
  7009. }
  7010. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  7011. if err != nil {
  7012. logs.Error(err)
  7013. tx.Rollback()
  7014. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7015. return
  7016. }
  7017. }
  7018. }
  7019. _, 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()
  7020. if err != nil {
  7021. logs.Error(err)
  7022. tx.Rollback()
  7023. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7024. return
  7025. }
  7026. } else {
  7027. if status == 2 {
  7028. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  7029. if err != nil {
  7030. logs.Error(err)
  7031. tx.Rollback()
  7032. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7033. return
  7034. }
  7035. for _, item := range lpplandtl1List {
  7036. if item["fttype"].(int64) == 0 {
  7037. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7038. if err != nil {
  7039. logs.Error(err)
  7040. tx.Rollback()
  7041. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7042. return
  7043. }
  7044. } else {
  7045. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7046. if err != nil {
  7047. logs.Error(err)
  7048. tx.Rollback()
  7049. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7050. return
  7051. }
  7052. }
  7053. }
  7054. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  7055. if err != nil {
  7056. logs.Error(err)
  7057. tx.Rollback()
  7058. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7059. return
  7060. }
  7061. } else {
  7062. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  7063. if err != nil {
  7064. logs.Error(err)
  7065. tx.Rollback()
  7066. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7067. return
  7068. }
  7069. }
  7070. }
  7071. err := tx.Commit()
  7072. if err != nil {
  7073. logs.Error(err)
  7074. tx.Rollback()
  7075. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7076. return
  7077. }
  7078. appG.Response(http.StatusOK, e.SUCCESS, true)
  7079. }
  7080. func Decimal(value float64) float64 {
  7081. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  7082. return value
  7083. }
  7084. func UpdateDailyData(c *gin.Context) {
  7085. appG := app.Gin{C: c}
  7086. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7087. parammaps := gofasion.NewFasion(string(dataByte))
  7088. pid := parammaps.Get("pid").ValueDefaultStr("0")
  7089. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  7090. sort := parammaps.Get("sort").ValueDefaultStr("0")
  7091. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  7092. date := parammaps.Get("date").ValueStr()
  7093. tx := restful.Engine.NewSession()
  7094. defer tx.Close()
  7095. 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()
  7096. if err != nil {
  7097. logs.Error("UpdateDailyData-error-0:", err)
  7098. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7099. return
  7100. }
  7101. if count > 0 {
  7102. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7103. return
  7104. }
  7105. tx.Begin()
  7106. if location == 0 {
  7107. fid := parammaps.Get("fid").ValueStr()
  7108. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  7109. if err != nil {
  7110. logs.Error("UpdateDailyData-error-1:", err)
  7111. tx.Rollback()
  7112. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7113. return
  7114. }
  7115. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7116. if err != nil {
  7117. logs.Error("UpdateDailyData-error-1:", err)
  7118. tx.Rollback()
  7119. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7120. return
  7121. }
  7122. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7123. if err != nil {
  7124. fmt.Println("Error:", err)
  7125. return
  7126. }
  7127. actualWeight := weight - num
  7128. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7129. if err != nil {
  7130. logs.Error("UpdateDailyData-error-2:", err)
  7131. tx.Rollback()
  7132. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7133. return
  7134. }
  7135. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7136. if err != nil {
  7137. logs.Error("UpdateDailyData-error-3:", err)
  7138. tx.Rollback()
  7139. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7140. return
  7141. }
  7142. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7143. if err != nil {
  7144. logs.Error("UpdateDailyData-error-4:", err)
  7145. tx.Rollback()
  7146. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7147. return
  7148. }
  7149. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7150. if err != nil {
  7151. logs.Error("UpdateDailyData-error-5:", err)
  7152. tx.Rollback()
  7153. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7154. return
  7155. }
  7156. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7157. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7158. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7159. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7160. if err != nil {
  7161. fmt.Println("Error:", err)
  7162. return
  7163. }
  7164. // actual := actualWeight / float64(len(downloadedplanList))
  7165. for _, item := range downloadedplanList {
  7166. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7167. if err != nil {
  7168. fmt.Println("Error:", err)
  7169. return
  7170. }
  7171. actual := itemLweight / lweight * actualWeight
  7172. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7173. if err != nil {
  7174. logs.Error("UpdateDailyData-error-6:", err)
  7175. tx.Rollback()
  7176. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7177. return
  7178. }
  7179. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7180. if err != nil {
  7181. logs.Error("UpdateDailyData-error-7:", err)
  7182. tx.Rollback()
  7183. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7184. return
  7185. }
  7186. _, 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()
  7187. if err != nil {
  7188. logs.Error("UpdateDailyData-error-8:", err)
  7189. tx.Rollback()
  7190. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7191. return
  7192. }
  7193. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7194. if err != nil {
  7195. logs.Error("UpdateDailyData-error-9:", err)
  7196. tx.Rollback()
  7197. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7198. return
  7199. }
  7200. }
  7201. } else {
  7202. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7203. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7204. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7205. // if err != nil {
  7206. // fmt.Println("Error:", err)
  7207. // return
  7208. // }
  7209. for _, item := range downloadedplanList {
  7210. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7211. if err != nil {
  7212. logs.Error("UpdateDailyData-error-6:", err)
  7213. tx.Rollback()
  7214. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7215. return
  7216. }
  7217. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7218. item["lweight"], actualWeight, item["id"]).Execute()
  7219. if err != nil {
  7220. logs.Error("UpdateDailyData-error-7:", err)
  7221. tx.Rollback()
  7222. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7223. return
  7224. }
  7225. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7226. where pid = ?`, item["id"]).Execute()
  7227. if err != nil {
  7228. logs.Error("UpdateDailyData-error-8:", err)
  7229. tx.Rollback()
  7230. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7231. return
  7232. }
  7233. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7234. if err != nil {
  7235. logs.Error("UpdateDailyData-error-9:", err)
  7236. tx.Rollback()
  7237. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7238. return
  7239. }
  7240. }
  7241. }
  7242. } else {
  7243. fbarid := parammaps.Get("fbarid").ValueStr()
  7244. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7245. if err != nil {
  7246. logs.Error("UpdateDailyData-error-10:", err)
  7247. tx.Rollback()
  7248. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7249. return
  7250. }
  7251. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7252. if err != nil {
  7253. logs.Error("UpdateDailyData-error-1:", err)
  7254. tx.Rollback()
  7255. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7256. return
  7257. }
  7258. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7259. if err != nil {
  7260. fmt.Println("Error:", err)
  7261. return
  7262. }
  7263. actualWeight := weight - num
  7264. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7265. if err != nil {
  7266. logs.Error("UpdateDailyData-error-11:", err)
  7267. tx.Rollback()
  7268. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7269. return
  7270. }
  7271. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  7272. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7273. if err != nil {
  7274. logs.Error("UpdateDailyData-error-12:", err)
  7275. tx.Rollback()
  7276. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7277. return
  7278. }
  7279. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7280. where pid = ? `, pid).Execute()
  7281. if err != nil {
  7282. logs.Error("UpdateDailyData-error-13:", err)
  7283. tx.Rollback()
  7284. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7285. return
  7286. }
  7287. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7288. if err != nil {
  7289. logs.Error("UpdateDailyData-error-14:", err)
  7290. tx.Rollback()
  7291. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7292. return
  7293. }
  7294. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7295. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7296. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7297. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7298. if err != nil {
  7299. fmt.Println("Error:", err)
  7300. return
  7301. }
  7302. for _, item := range downloadedplanList {
  7303. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7304. if err != nil {
  7305. fmt.Println("Error:", err)
  7306. return
  7307. }
  7308. actual := itemLweight / lweight * actualWeight
  7309. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7310. if err != nil {
  7311. logs.Error("UpdateDailyData-error-6:", err)
  7312. tx.Rollback()
  7313. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7314. return
  7315. }
  7316. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7317. if err != nil {
  7318. logs.Error("UpdateDailyData-error-7:", err)
  7319. tx.Rollback()
  7320. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7321. return
  7322. }
  7323. _, 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()
  7324. if err != nil {
  7325. logs.Error("UpdateDailyData-error-8:", err)
  7326. tx.Rollback()
  7327. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7328. return
  7329. }
  7330. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7331. if err != nil {
  7332. logs.Error("UpdateDailyData-error-9:", err)
  7333. tx.Rollback()
  7334. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7335. return
  7336. }
  7337. }
  7338. } else {
  7339. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7340. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7341. for _, item := range downloadedplanList {
  7342. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7343. // if err != nil {
  7344. // fmt.Println("Error:", err)
  7345. // return
  7346. // }
  7347. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7348. if err != nil {
  7349. logs.Error("UpdateDailyData-error-6:", err)
  7350. tx.Rollback()
  7351. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7352. return
  7353. }
  7354. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7355. item["lweight"], actualWeight, item["id"]).Execute()
  7356. if err != nil {
  7357. logs.Error("UpdateDailyData-error-7:", err)
  7358. tx.Rollback()
  7359. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7360. return
  7361. }
  7362. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7363. where pid = ?`, item["id"]).Execute()
  7364. if err != nil {
  7365. logs.Error("UpdateDailyData-error-8:", err)
  7366. tx.Rollback()
  7367. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7368. return
  7369. }
  7370. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7371. if err != nil {
  7372. logs.Error("UpdateDailyData-error-9:", err)
  7373. tx.Rollback()
  7374. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7375. return
  7376. }
  7377. }
  7378. }
  7379. }
  7380. err = tx.Commit()
  7381. if err != nil {
  7382. logs.Error("UpdateDailyData-error-20:", err)
  7383. tx.Rollback()
  7384. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7385. return
  7386. }
  7387. appG.Response(http.StatusOK, e.SUCCESS, true)
  7388. }
  7389. func GetFormulaStatistics(c *gin.Context) {
  7390. appG := app.Gin{C: c}
  7391. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7392. parammaps := gofasion.NewFasion(string(dataByte))
  7393. startTime := parammaps.Get("startTime").ValueStr()
  7394. endTime := parammaps.Get("endTime").ValueStr()
  7395. pastureId := parammaps.Get("pastureId").ValueStr()
  7396. tx := restful.Engine.NewSession()
  7397. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7398. if err != nil {
  7399. logs.Error("GetFormulaStatistics-error-1:", err)
  7400. tx.Rollback()
  7401. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7402. return
  7403. }
  7404. var feedtemplet, dateList []string
  7405. for _, f := range feedtempletList {
  7406. feedtemplet = append(feedtemplet, f["tname"].(string))
  7407. }
  7408. layout := "2006-01-02"
  7409. // s := "2023-05-01"
  7410. // e := "2023-05-23"
  7411. start, err := time.Parse(layout, startTime)
  7412. if err != nil {
  7413. fmt.Println(err)
  7414. return
  7415. }
  7416. end, err := time.Parse(layout, endTime)
  7417. if err != nil {
  7418. fmt.Println(err)
  7419. return
  7420. }
  7421. end = end.AddDate(0, 0, 1)
  7422. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7423. dateList = append(dateList, d.Format("2006-01-02"))
  7424. }
  7425. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7426. 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= ?
  7427. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7428. if err != nil {
  7429. logs.Error("GetFormulaStatistics-error-2:", err)
  7430. tx.Rollback()
  7431. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7432. return
  7433. }
  7434. var data2 [][]interface{}
  7435. for _, f := range feedtemplet {
  7436. var data1 []interface{}
  7437. for _, date := range dateList {
  7438. exist := false
  7439. for _, item := range downloadedplanList {
  7440. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7441. data1 = append(data1, item["total"])
  7442. exist = true
  7443. break
  7444. }
  7445. }
  7446. if !exist {
  7447. data1 = append(data1, 0)
  7448. }
  7449. }
  7450. data2 = append(data2, data1)
  7451. }
  7452. //前端让加的
  7453. feedtemplet = append(feedtemplet, "")
  7454. {
  7455. var data1 []interface{}
  7456. for _, f := range dateList {
  7457. // f = f + "\n"
  7458. fmt.Println(f)
  7459. data1 = append(data1, 0)
  7460. }
  7461. data2 = append(data2, data1)
  7462. }
  7463. resp := make(map[string]interface{}, 0)
  7464. resp["xdata"] = dateList
  7465. resp["data1"] = feedtemplet
  7466. resp["data2"] = data2
  7467. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7468. }
  7469. func GetPlanData(c *gin.Context) {
  7470. appG := app.Gin{C: c}
  7471. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7472. fsion := gofasion.NewFasion(string(dataByte))
  7473. sqlnamestr := fsion.Get("name").ValueStr()
  7474. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7475. offset := fsion.Get("offset").ValueDefaultInt(0)
  7476. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7477. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7478. month := fsion.Get("month").ValueDefaultStr("map")
  7479. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7480. tx := restful.Engine.NewSession()
  7481. err := tx.Begin()
  7482. defer func() {
  7483. switch {
  7484. case err != nil:
  7485. if tx != nil {
  7486. tx.Rollback()
  7487. }
  7488. default:
  7489. if tx != nil {
  7490. err = tx.Commit()
  7491. }
  7492. }
  7493. if tx != nil {
  7494. tx.Close()
  7495. }
  7496. }()
  7497. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7498. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7499. if sql != "" {
  7500. s_params := make([]interface{}, 0)
  7501. if fsion.HasKey("parammaps") {
  7502. parammaps := fsion.Get("parammaps")
  7503. paramslist := strings.Split(p, ",")
  7504. if len(paramslist) > 0 && p != "" {
  7505. for _, value := range paramslist {
  7506. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7507. if tempv, exists := c.Get("jwt_username"); exists {
  7508. s_params = append(s_params, tempv.(string))
  7509. } else {
  7510. s_params = append(s_params, "")
  7511. }
  7512. } else {
  7513. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7514. }
  7515. }
  7516. }
  7517. }
  7518. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7519. if err != nil {
  7520. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7521. } else {
  7522. paramslist1 := strings.Split(p1, ",")
  7523. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7524. s_params1 := make([]interface{}, 0)
  7525. if len(paramslist1) > 0 && p1 != "" {
  7526. for _, v := range paramslist1 {
  7527. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7528. }
  7529. }
  7530. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7531. for _, item := range arr {
  7532. trgaddressList := []string{}
  7533. if _, ok := item["trgaddress"]; ok {
  7534. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7535. for _, str := range trgaddressList1 {
  7536. if str != "" {
  7537. trgaddressList = append(trgaddressList, str)
  7538. }
  7539. }
  7540. }
  7541. item["trgaddressList"] = trgaddressList
  7542. }
  7543. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7544. }
  7545. // var wg sync.WaitGroup
  7546. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7547. // wg.Add(1)
  7548. // go func(value map[string]interface{}) {
  7549. // defer wg.Done()
  7550. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7551. // }(value)
  7552. // }
  7553. // wg.Wait()
  7554. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7555. }
  7556. } else {
  7557. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7558. }
  7559. }
  7560. func PostPlanData(c *gin.Context) {
  7561. appG := app.Gin{C: c}
  7562. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7563. fsion := gofasion.NewFasion(string(dataByte))
  7564. logging.Info("PostRJSBData err: ", string(dataByte))
  7565. s_params := make([]interface{}, 0)
  7566. tx := restful.Engine.NewSession()
  7567. err := tx.Begin()
  7568. defer func() {
  7569. switch {
  7570. case err != nil:
  7571. if tx != nil {
  7572. tx.Rollback()
  7573. }
  7574. default:
  7575. if tx != nil {
  7576. err = tx.Commit()
  7577. }
  7578. }
  7579. if tx != nil {
  7580. tx.Close()
  7581. }
  7582. }()
  7583. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7584. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7585. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7586. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7587. if !fsion.HasKey("parammaps") {
  7588. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7589. return
  7590. }
  7591. parammaps := fsion.Get("parammaps")
  7592. // paramslist := strings.Split(p, ",")
  7593. // if len(paramslist) > 0 && p != "" {
  7594. // for _, value := range paramslist {
  7595. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7596. // }
  7597. // }
  7598. // _, err = tx.SQL(sql, s_params...).Execute()
  7599. // if err != nil {
  7600. // logging.Error("PostRJSBData err: ", err)
  7601. // msg := geterrmsg(err.Error())
  7602. // appG.Response(http.StatusOK, e.ERROR, msg)
  7603. // return
  7604. // }
  7605. s_params = make([]interface{}, 0)
  7606. paramslist := strings.Split(p1, ",")
  7607. if len(paramslist) > 0 && p1 != "" {
  7608. for _, value := range paramslist {
  7609. // if value == "ID" {
  7610. // id := parammaps.Get("ID").ValueStr()
  7611. // pastureid := parammaps.Get("pastureid").ValueStr()
  7612. // 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
  7613. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7614. // if err != nil {
  7615. // logging.Error("PostRJSBData err: ", err)
  7616. // msg := geterrmsg(err.Error())
  7617. // appG.Response(http.StatusOK, e.ERROR, msg)
  7618. // return
  7619. // }
  7620. // for _, item := range datalist {
  7621. // id = item["id"]
  7622. // }
  7623. // s_params = append(s_params, id)
  7624. // } else {
  7625. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7626. // }
  7627. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7628. }
  7629. }
  7630. _, err = tx.SQL(sql1, s_params...).Execute()
  7631. if err != nil {
  7632. logging.Error("PostRJSBData1 err: ", err)
  7633. msg := geterrmsg(err.Error())
  7634. appG.Response(http.StatusOK, e.ERROR, msg)
  7635. return
  7636. }
  7637. s_params = make([]interface{}, 0)
  7638. paramslist = strings.Split(p2, ",")
  7639. if len(paramslist) > 0 && p2 != "" {
  7640. for _, value := range paramslist {
  7641. if value == "ID" {
  7642. id := parammaps.Get("ID").ValueStr()
  7643. pastureid := parammaps.Get("pastureid").ValueStr()
  7644. 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
  7645. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7646. if err != nil {
  7647. logging.Error("PostRJSBData err: ", err)
  7648. msg := geterrmsg(err.Error())
  7649. appG.Response(http.StatusOK, e.ERROR, msg)
  7650. return
  7651. }
  7652. for _, item := range datalist {
  7653. id = item["id"]
  7654. }
  7655. s_params = append(s_params, id)
  7656. } else {
  7657. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7658. }
  7659. }
  7660. }
  7661. _, err = tx.SQL(sql2, s_params...).Execute()
  7662. if err != nil {
  7663. logging.Error("PostRJSBData2 err: ", err)
  7664. msg := geterrmsg(err.Error())
  7665. appG.Response(http.StatusOK, e.ERROR, msg)
  7666. return
  7667. }
  7668. s_params = make([]interface{}, 0)
  7669. paramslist = strings.Split(p3, ",")
  7670. if len(paramslist) > 0 && p3 != "" {
  7671. for _, value := range paramslist {
  7672. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7673. }
  7674. }
  7675. _, err = tx.SQL(sql3, s_params...).Execute()
  7676. if err != nil {
  7677. logging.Error("PostRJSBData3 err: ", err)
  7678. msg := geterrmsg(err.Error())
  7679. appG.Response(http.StatusOK, e.ERROR, msg)
  7680. return
  7681. }
  7682. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7683. }
  7684. func CheckFeedTrgaddress(c *gin.Context) {
  7685. appG := app.Gin{C: c}
  7686. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7687. fsion := gofasion.NewFasion(string(dataByte))
  7688. fclassid := fsion.Get("fclassid").ValueStr()
  7689. feedId := fsion.Get("feedId").ValueStr()
  7690. backup1 := fsion.Get("backup1").ValueStr()
  7691. backup1List := strings.Split(backup1, ",")
  7692. tx := restful.Engine.NewSession()
  7693. defer tx.Close()
  7694. // if backup1 != "" {
  7695. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7696. for _, feed := range feedList {
  7697. if feed["backup1"] == "" {
  7698. continue
  7699. }
  7700. feedbackupList := strings.Split(feed["backup1"], ",")
  7701. for _, feedbackup := range feedbackupList {
  7702. for _, backup := range backup1List {
  7703. if feedbackup == backup {
  7704. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7705. return
  7706. }
  7707. }
  7708. }
  7709. }
  7710. // }
  7711. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7712. }
  7713. func ThiGetDataByName(c *gin.Context) {
  7714. appG := app.Gin{C: c}
  7715. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7716. fsion := gofasion.NewFasion(string(dataByte))
  7717. sqlnamestr := fsion.Get("name").ValueStr()
  7718. offset := fsion.Get("offset").ValueDefaultInt(0)
  7719. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7720. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7721. tx := restful.Engine.NewSession()
  7722. err := tx.Begin()
  7723. defer func() {
  7724. switch {
  7725. case err != nil:
  7726. logging.Error("tx.Begin 事务启动失败__error:", err)
  7727. if tx != nil {
  7728. tx.Rollback()
  7729. }
  7730. default:
  7731. if tx != nil {
  7732. err = tx.Commit()
  7733. }
  7734. }
  7735. if tx != nil {
  7736. tx.Close()
  7737. }
  7738. }()
  7739. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7740. if sql != "" {
  7741. s_params := make([]interface{}, 0)
  7742. if fsion.HasKey("parammaps") {
  7743. parammaps := fsion.Get("parammaps")
  7744. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7745. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7746. }
  7747. paramslist := strings.Split(p, ",")
  7748. if len(paramslist) > 0 && p != "" {
  7749. for _, value := range paramslist {
  7750. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7751. if tempv, exists := c.Get("jwt_username"); exists {
  7752. s_params = append(s_params, tempv.(string))
  7753. } else {
  7754. s_params = append(s_params, "")
  7755. }
  7756. } else {
  7757. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7758. }
  7759. }
  7760. }
  7761. } else if fsion.HasKey("params") {
  7762. params := fsion.Get("params").Array()
  7763. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7764. for _, v_params := range params {
  7765. s_params = append(s_params, v_params.ValueStr())
  7766. }
  7767. }
  7768. if returntype == "xlsx" {
  7769. var xlsxfile *xlsx.File
  7770. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7771. //c.File("c:/dd.xlsx")
  7772. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7773. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7774. c.Header("Content-Transfer-Encoding", "binary")
  7775. _ = xlsxfile.Write(c.Writer)
  7776. } else {
  7777. if sqlnamestr == "getHomepageStr" {
  7778. parammaps := fsion.Get("parammaps")
  7779. pastureid := parammaps.Get("pastureid").ValueStr()
  7780. var montimeList []float64
  7781. var montime float64
  7782. var wg sync.WaitGroup
  7783. now := time.Now()
  7784. for i := 0; i < 30; i++ {
  7785. wg.Add(1)
  7786. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7787. go func(nowstr string) {
  7788. defer wg.Done()
  7789. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7790. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7791. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7792. montimeList = append(montimeList, m)
  7793. }(nowstr)
  7794. }
  7795. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7796. if err != nil {
  7797. logging.Error("GetDataByName err: ", err)
  7798. msg := geterrmsg(err.Error())
  7799. appG.Response(http.StatusOK, e.ERROR, msg)
  7800. }
  7801. wg.Wait()
  7802. for _, m := range montimeList {
  7803. montime += m
  7804. }
  7805. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7806. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7807. return
  7808. }
  7809. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7810. if err != nil {
  7811. logging.Error("GetDataByName err: ", err)
  7812. msg := geterrmsg(err.Error())
  7813. appG.Response(http.StatusOK, e.ERROR, msg)
  7814. } else {
  7815. if sqlnamestr == "getFeedTrgaddressList" {
  7816. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7817. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7818. trgaddressList := []string{}
  7819. for _, str := range trgaddressList1 {
  7820. if str != "" {
  7821. trgaddressList = append(trgaddressList, str)
  7822. }
  7823. }
  7824. item["trgaddressList"] = trgaddressList
  7825. }
  7826. }
  7827. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7828. }
  7829. }
  7830. } else {
  7831. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7832. }
  7833. }
  7834. // func ToggleCcount(c *gin.Context) {
  7835. // appG := app.Gin{C: c}
  7836. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7837. // fsion := gofasion.NewFasion(string(dataByte))
  7838. // // 0 实际 1 软件
  7839. // status := fsion.Get("status").ValueDefaultInt64(0)
  7840. // pastureId := fsion.Get("pastureId").ValueStr()
  7841. // tx := restful.Engine.NewSession()
  7842. // err := tx.Begin()
  7843. // defer func() {
  7844. // switch {
  7845. // case err != nil:
  7846. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7847. // if tx != nil {
  7848. // tx.Rollback()
  7849. // }
  7850. // default:
  7851. // if tx != nil {
  7852. // err = tx.Commit()
  7853. // }
  7854. // }
  7855. // if tx != nil {
  7856. // tx.Close()
  7857. // }
  7858. // }()
  7859. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7860. // if err != nil {
  7861. // logs.Error(err)
  7862. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7863. // return
  7864. // }
  7865. // for _, bar := range barList {
  7866. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7867. // if err != nil {
  7868. // logs.Error(err)
  7869. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7870. // return
  7871. // }
  7872. // if !exist {
  7873. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7874. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7875. // if err != nil {
  7876. // logs.Error(err)
  7877. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7878. // return
  7879. // }
  7880. // }
  7881. // }
  7882. // if status == 0 {
  7883. // tx.Exec(`update feedp set ccount = actualcount `)
  7884. // }else{
  7885. // tx.Exec(`update feedp set ccount = softccount `)
  7886. // }
  7887. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7888. // if err != nil {
  7889. // logs.Error(err)
  7890. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7891. // return
  7892. // }
  7893. // for _, feedpData :=range feedpList{
  7894. // var feedpargs []interface{}
  7895. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7896. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7897. // if _, ok := feedpData["ftname"]; ok {
  7898. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7899. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7900. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7901. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7902. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7903. // } else {
  7904. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7905. // }
  7906. // if _, ok := feedpData["ptsfname"]; ok {
  7907. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7908. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7909. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7910. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7911. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7912. // } else {
  7913. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7914. // }
  7915. // upFeedpSql += " where barname = ? and pastureid = ? "
  7916. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7917. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7918. // if err != nil {
  7919. // logs.Error(err)
  7920. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7921. // return
  7922. // }
  7923. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7924. // if err != nil {
  7925. // logs.Error(err)
  7926. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7927. // return
  7928. // }
  7929. // if !exist1 {
  7930. // _, 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) `,
  7931. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7932. // if err != nil {
  7933. // logs.Error(err)
  7934. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7935. // return
  7936. // }
  7937. // }
  7938. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7939. // if err != nil {
  7940. // logs.Error(err)
  7941. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7942. // return
  7943. // }
  7944. // if !exist2 {
  7945. // _, 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) `,
  7946. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7947. // if err != nil {
  7948. // logs.Error(err)
  7949. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7950. // return
  7951. // }
  7952. // }
  7953. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7954. // if err != nil {
  7955. // logs.Error(err)
  7956. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7957. // return
  7958. // }
  7959. // if !exist3 {
  7960. // _, 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) `,
  7961. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7962. // if err != nil {
  7963. // logs.Error(err)
  7964. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7965. // return
  7966. // }
  7967. // }
  7968. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7969. // if err != nil {
  7970. // logs.Error(err)
  7971. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7972. // return
  7973. // }
  7974. // if !exist4 {
  7975. // _, 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) `,
  7976. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7977. // if err != nil {
  7978. // logs.Error(err)
  7979. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7980. // return
  7981. // }
  7982. // }
  7983. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7984. // if err != nil {
  7985. // logs.Error(err)
  7986. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7987. // return
  7988. // }
  7989. // if !exist5 {
  7990. // _, 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) `,
  7991. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7992. // if err != nil {
  7993. // logs.Error(err)
  7994. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7995. // return
  7996. // }
  7997. // }
  7998. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7999. // if err != nil {
  8000. // logs.Error(err)
  8001. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8002. // return
  8003. // }
  8004. // if !exist6 {
  8005. // _, 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) `,
  8006. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  8007. // if err != nil {
  8008. // logs.Error(err)
  8009. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8010. // return
  8011. // }
  8012. // }
  8013. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8014. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8015. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8016. // and pastureid = ? and times = ?`
  8017. // var fpdargs1 []interface{}
  8018. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8019. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8020. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8021. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8022. // if err != nil {
  8023. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8024. // return
  8025. // }
  8026. // var fpdargs2 []interface{}
  8027. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8028. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8029. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8030. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8031. // if err != nil {
  8032. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8033. // return
  8034. // }
  8035. // var fpdargs3 []interface{}
  8036. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8037. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8038. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8039. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8040. // if err != nil {
  8041. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8042. // return
  8043. // }
  8044. // var fpdargs4 []interface{}
  8045. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8046. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8047. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8048. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8049. // if err != nil {
  8050. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8051. // return
  8052. // }
  8053. // var fpdargs5 []interface{}
  8054. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8055. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8056. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8057. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8058. // if err != nil {
  8059. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8060. // return
  8061. // }
  8062. // var fpdargs6 []interface{}
  8063. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8064. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8065. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8066. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8067. // if err != nil {
  8068. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8069. // return
  8070. // }
  8071. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8072. // 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()
  8073. // if err != nil {
  8074. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8075. // return
  8076. // }
  8077. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8078. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8079. // upFpdetailList := make([]*upFpdetail, 0)
  8080. // for _, newfpd := range newList {
  8081. // for _, oldfpd := range oldFpdList {
  8082. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8083. // var oldweight, newweight float64
  8084. // if oldfpd["weight"] != nil {
  8085. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8086. // }
  8087. // if newfpd["weight"] != nil {
  8088. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8089. // }
  8090. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8091. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  8092. // Old: oldweight,
  8093. // New: newweight,
  8094. // Times: newfpd["times"].(int64),
  8095. // Ptid: newfpd["ptid"].(int64),
  8096. // Fweight: fweight,
  8097. // Id: oldfpd["id"].(int64),
  8098. // })
  8099. // break
  8100. // }
  8101. // }
  8102. // }
  8103. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8104. // }
  8105. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8106. // }
  8107. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8108. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8109. if err != nil {
  8110. return err
  8111. }
  8112. for _, item := range feedpList {
  8113. // if item["ftid"].(string) != data["ftid"].(string) {
  8114. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8115. if err != nil {
  8116. return err
  8117. }
  8118. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8119. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8120. if err != nil {
  8121. return err
  8122. }
  8123. // }
  8124. }
  8125. return nil
  8126. }
  8127. func PostPlanDatas(c *gin.Context) {
  8128. appG := app.Gin{C: c}
  8129. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8130. fsions := gofasion.NewFasion(string(dataByte))
  8131. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8132. tx := restful.Engine.NewSession()
  8133. err := tx.Begin()
  8134. defer func() {
  8135. switch {
  8136. case err != nil:
  8137. if tx != nil {
  8138. tx.Rollback()
  8139. }
  8140. default:
  8141. if tx != nil {
  8142. err = tx.Commit()
  8143. }
  8144. }
  8145. if tx != nil {
  8146. tx.Close()
  8147. }
  8148. }()
  8149. pastureId := fsions.Get("pastureid").ValueStr()
  8150. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8151. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8152. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8153. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8154. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8155. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8156. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8157. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8158. for _, parammaps := range fsions.Get("arrList").Array() {
  8159. fmt.Println(parammaps.Json())
  8160. if parammaps.Json() == "null" {
  8161. continue
  8162. }
  8163. // if !fsion.HasKey("arrList") {
  8164. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8165. // return
  8166. // continue
  8167. // }
  8168. // parammaps := fsion.Get("arrList")
  8169. s_params := make([]interface{}, 0)
  8170. // paramslist := strings.Split(p, ",")
  8171. // if len(paramslist) > 0 && p != "" {
  8172. // for _, value := range paramslist {
  8173. // if value == "pastureid" {
  8174. // s_params = append(s_params, pastureId)
  8175. // } else {
  8176. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8177. // }
  8178. // }
  8179. // }
  8180. // _, err = tx.SQL(sql, s_params...).Execute()
  8181. // if err != nil {
  8182. // logging.Error("PostRJSBData err: ", err)
  8183. // msg := geterrmsg(err.Error())
  8184. // appG.Response(http.StatusOK, e.ERROR, msg)
  8185. // return
  8186. // }
  8187. s_params = make([]interface{}, 0)
  8188. paramslist := strings.Split(p1, ",")
  8189. if len(paramslist) > 0 && p1 != "" {
  8190. for _, value := range paramslist {
  8191. // if value == "ID" {
  8192. // id := parammaps.Get("ID").ValueStr()
  8193. // pastureid := parammaps.Get("pastureid").ValueStr()
  8194. // 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
  8195. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8196. // if err != nil {
  8197. // logging.Error("PostRJSBData err: ", err)
  8198. // msg := geterrmsg(err.Error())
  8199. // appG.Response(http.StatusOK, e.ERROR, msg)
  8200. // return
  8201. // }
  8202. // for _, item := range datalist {
  8203. // id = item["id"]
  8204. // }
  8205. // s_params = append(s_params, id)
  8206. // } else {
  8207. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8208. // }
  8209. if value == "pastureid" {
  8210. s_params = append(s_params, pastureId)
  8211. } else {
  8212. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8213. }
  8214. }
  8215. }
  8216. _, err = tx.SQL(sql1, s_params...).Execute()
  8217. if err != nil {
  8218. logging.Error("PostRJSBData1 err: ", err)
  8219. msg := geterrmsg(err.Error())
  8220. appG.Response(http.StatusOK, e.ERROR, msg)
  8221. return
  8222. }
  8223. s_params = make([]interface{}, 0)
  8224. paramslist = strings.Split(p2, ",")
  8225. if len(paramslist) > 0 && p2 != "" {
  8226. for _, value := range paramslist {
  8227. if value == "ID" {
  8228. id := parammaps.Get("ID").ValueStr()
  8229. pastureid := parammaps.Get("pastureid").ValueStr()
  8230. 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
  8231. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8232. if err != nil {
  8233. logging.Error("PostRJSBData err: ", err)
  8234. msg := geterrmsg(err.Error())
  8235. appG.Response(http.StatusOK, e.ERROR, msg)
  8236. return
  8237. }
  8238. for _, item := range datalist {
  8239. id = item["id"]
  8240. }
  8241. s_params = append(s_params, id)
  8242. } else if value == "pastureid" {
  8243. s_params = append(s_params, pastureId)
  8244. } else {
  8245. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8246. }
  8247. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8248. }
  8249. }
  8250. _, err = tx.SQL(sql2, s_params...).Execute()
  8251. if err != nil {
  8252. logging.Error("PostRJSBData2 err: ", err)
  8253. msg := geterrmsg(err.Error())
  8254. appG.Response(http.StatusOK, e.ERROR, msg)
  8255. return
  8256. }
  8257. s_params = make([]interface{}, 0)
  8258. paramslist = strings.Split(p3, ",")
  8259. if len(paramslist) > 0 && p3 != "" {
  8260. for _, value := range paramslist {
  8261. if value == "pastureid" {
  8262. s_params = append(s_params, pastureId)
  8263. } else {
  8264. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8265. }
  8266. }
  8267. }
  8268. _, err = tx.SQL(sql3, s_params...).Execute()
  8269. if err != nil {
  8270. logging.Error("PostRJSBData3 err: ", err)
  8271. msg := geterrmsg(err.Error())
  8272. appG.Response(http.StatusOK, e.ERROR, msg)
  8273. return
  8274. }
  8275. }
  8276. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8277. }
  8278. func FpdBatchEdit(c *gin.Context) {
  8279. appG := app.Gin{C: c}
  8280. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8281. fsions := gofasion.NewFasion(string(dataByte))
  8282. barList := fsions.Get("barList").Array()
  8283. pastureid := fsions.Get("pastureId").ValueStr()
  8284. tx := restful.Engine.NewSession()
  8285. defer tx.Close()
  8286. 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
  8287. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8288. if err != nil {
  8289. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8290. return
  8291. }
  8292. for _, barFsions := range barList {
  8293. dataexcel := make(map[string]interface{}, 0)
  8294. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8295. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8296. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8297. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8298. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8299. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8300. continue
  8301. }
  8302. // /*
  8303. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8304. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8305. if err != nil {
  8306. logs.Error(err)
  8307. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8308. return
  8309. }
  8310. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8311. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8312. if err != nil {
  8313. logs.Error(err)
  8314. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8315. return
  8316. }
  8317. // */
  8318. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8319. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8320. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8321. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8322. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8323. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8324. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8325. if err != nil {
  8326. logs.Error(err)
  8327. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8328. return
  8329. }
  8330. if !ftexist {
  8331. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8332. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8333. if err != nil {
  8334. logs.Error(err)
  8335. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8336. return
  8337. }
  8338. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8339. if err != nil {
  8340. logs.Error(err)
  8341. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8342. return
  8343. }
  8344. }
  8345. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8346. if err != nil {
  8347. logs.Error(err)
  8348. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8349. return
  8350. }
  8351. if !exist {
  8352. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8353. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8354. if err != nil {
  8355. logs.Error(err)
  8356. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8357. return
  8358. }
  8359. }
  8360. var feedpargs []interface{}
  8361. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8362. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8363. if _, ok := dataexcel["ftname"]; ok {
  8364. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8365. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8366. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8367. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8368. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8369. } else {
  8370. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8371. }
  8372. if _, ok := dataexcel["ptsfname"]; ok {
  8373. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8374. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8375. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8376. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8377. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8378. } else {
  8379. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8380. }
  8381. upFeedpSql += " where barname = ? and pastureid = ? "
  8382. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8383. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8384. if err != nil {
  8385. logs.Error(err)
  8386. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8387. return
  8388. }
  8389. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8390. if err != nil {
  8391. logs.Error(err)
  8392. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8393. return
  8394. }
  8395. if !exist1 {
  8396. _, 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) `,
  8397. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8398. if err != nil {
  8399. logs.Error(err)
  8400. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8401. return
  8402. }
  8403. }
  8404. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8405. if err != nil {
  8406. logs.Error(err)
  8407. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8408. return
  8409. }
  8410. if !exist2 {
  8411. _, 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) `,
  8412. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8413. if err != nil {
  8414. logs.Error(err)
  8415. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8416. return
  8417. }
  8418. }
  8419. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8420. if err != nil {
  8421. logs.Error(err)
  8422. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8423. return
  8424. }
  8425. if !exist3 {
  8426. _, 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) `,
  8427. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8428. if err != nil {
  8429. logs.Error(err)
  8430. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8431. return
  8432. }
  8433. }
  8434. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8435. if err != nil {
  8436. logs.Error(err)
  8437. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8438. return
  8439. }
  8440. if !exist4 {
  8441. _, 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) `,
  8442. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8443. if err != nil {
  8444. logs.Error(err)
  8445. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8446. return
  8447. }
  8448. }
  8449. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8450. if err != nil {
  8451. logs.Error(err)
  8452. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8453. return
  8454. }
  8455. if !exist5 {
  8456. _, 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) `,
  8457. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8458. if err != nil {
  8459. logs.Error(err)
  8460. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8461. return
  8462. }
  8463. }
  8464. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8465. if err != nil {
  8466. logs.Error(err)
  8467. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8468. return
  8469. }
  8470. if !exist6 {
  8471. _, 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) `,
  8472. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8473. if err != nil {
  8474. logs.Error(err)
  8475. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8476. return
  8477. }
  8478. }
  8479. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8480. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8481. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8482. and pastureid = ? and times = ?`
  8483. var fpdargs1 []interface{}
  8484. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8485. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8486. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8487. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8488. if err != nil {
  8489. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8490. return
  8491. }
  8492. var fpdargs2 []interface{}
  8493. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8494. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8495. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8496. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8497. if err != nil {
  8498. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8499. return
  8500. }
  8501. var fpdargs3 []interface{}
  8502. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8503. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8504. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8505. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8506. if err != nil {
  8507. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8508. return
  8509. }
  8510. var fpdargs4 []interface{}
  8511. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8512. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8513. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8514. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8515. if err != nil {
  8516. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8517. return
  8518. }
  8519. var fpdargs5 []interface{}
  8520. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8521. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8522. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8523. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8524. if err != nil {
  8525. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8526. return
  8527. }
  8528. var fpdargs6 []interface{}
  8529. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8530. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8531. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8532. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8533. if err != nil {
  8534. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8535. return
  8536. }
  8537. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8538. 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()
  8539. if err != nil {
  8540. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8541. return
  8542. }
  8543. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8544. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8545. upFpdetailList := make([]*upFpdetail, 0)
  8546. for _, newfpd := range newList {
  8547. for _, oldfpd := range oldFpdList {
  8548. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8549. var oldweight, newweight float64
  8550. if oldfpd["weight"] != nil {
  8551. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8552. }
  8553. if newfpd["weight"] != nil {
  8554. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8555. }
  8556. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8557. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8558. Old: oldweight,
  8559. New: newweight,
  8560. Times: newfpd["times"].(int64),
  8561. Ptid: newfpd["ptid"].(int64),
  8562. Fweight: fweight,
  8563. Id: oldfpd["id"].(int64),
  8564. })
  8565. break
  8566. }
  8567. }
  8568. }
  8569. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8570. }
  8571. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8572. }
  8573. func UdBarSync(c *gin.Context) {
  8574. appG := app.Gin{C: c}
  8575. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8576. fsions := gofasion.NewFasion(string(dataByte))
  8577. pastureid := fsions.Get("pastureId").ValueStr()
  8578. tx := restful.Engine.NewSession()
  8579. defer tx.Close()
  8580. pastureinfo := new(udPastureInfo)
  8581. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8582. if err != nil {
  8583. logs.Error(err)
  8584. return
  8585. }
  8586. // gm.UdBarSync(pastureid, pastureinfo.Werks)
  8587. jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8588. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8589. }
  8590. func UdFeedSync(c *gin.Context) {
  8591. appG := app.Gin{C: c}
  8592. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8593. fsions := gofasion.NewFasion(string(dataByte))
  8594. pastureid := fsions.Get("pastureId").ValueStr()
  8595. tx := restful.Engine.NewSession()
  8596. defer tx.Close()
  8597. pastureinfo := new(udPastureInfo)
  8598. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8599. if err != nil {
  8600. logs.Error(err)
  8601. return
  8602. }
  8603. // gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8604. jpud.UdFeedSync(pastureid, pastureinfo.Werks)
  8605. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8606. }
  8607. func UdFeedtempletPush(c *gin.Context) {
  8608. appG := app.Gin{C: c}
  8609. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8610. fsions := gofasion.NewFasion(string(dataByte))
  8611. pastureid := fsions.Get("pastureId").ValueStr()
  8612. date := fsions.Get("date").ValueStr()
  8613. tx := restful.Engine.NewSession()
  8614. defer tx.Close()
  8615. pastureinfo := new(udPastureInfo)
  8616. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8617. if err != nil {
  8618. logs.Error(err)
  8619. return
  8620. }
  8621. // gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8622. jpud.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8623. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8624. }
  8625. func UdUtirPush(c *gin.Context) {
  8626. appG := app.Gin{C: c}
  8627. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8628. fsions := gofasion.NewFasion(string(dataByte))
  8629. pastureid := fsions.Get("pastureId").ValueStr()
  8630. date := fsions.Get("date").ValueStr()
  8631. tx := restful.Engine.NewSession()
  8632. defer tx.Close()
  8633. pastureinfo := new(udPastureInfo)
  8634. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8635. if err != nil {
  8636. logs.Error(err)
  8637. return
  8638. }
  8639. // gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8640. jpud.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8641. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8642. }
  8643. func UdBarFeedRemainPush(c *gin.Context) {
  8644. appG := app.Gin{C: c}
  8645. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8646. fsions := gofasion.NewFasion(string(dataByte))
  8647. pastureid := fsions.Get("pastureId").ValueStr()
  8648. date := fsions.Get("date").ValueStr()
  8649. tx := restful.Engine.NewSession()
  8650. defer tx.Close()
  8651. pastureinfo := new(udPastureInfo)
  8652. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8653. if err != nil {
  8654. logs.Error(err)
  8655. return
  8656. }
  8657. // gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8658. jpud.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8659. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8660. }
  8661. func UdMaterialIssuePush(c *gin.Context) {
  8662. appG := app.Gin{C: c}
  8663. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8664. fsions := gofasion.NewFasion(string(dataByte))
  8665. pastureid := fsions.Get("pastureId").ValueStr()
  8666. date := fsions.Get("date").ValueStr()
  8667. tx := restful.Engine.NewSession()
  8668. defer tx.Close()
  8669. pastureinfo := new(udPastureInfo)
  8670. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8671. if err != nil {
  8672. logs.Error(err)
  8673. return
  8674. }
  8675. // gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8676. jpud.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8677. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8678. }
  8679. //搅拌
  8680. func YmyUtirPush(c *gin.Context) {
  8681. appG := app.Gin{C: c}
  8682. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8683. fsions := gofasion.NewFasion(string(dataByte))
  8684. pastureid := fsions.Get("pastureId").ValueStr()
  8685. date := fsions.Get("date").ValueStr()
  8686. tx := restful.Engine.NewSession()
  8687. defer tx.Close()
  8688. pastureinfo := new(udPastureInfo)
  8689. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8690. if err != nil {
  8691. logs.Error(err)
  8692. return
  8693. }
  8694. ymy.YmyUtirPush(pastureid, pastureinfo.Werks, date)
  8695. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8696. }
  8697. //撒料
  8698. func YmyMaterialIssuePush(c *gin.Context) {
  8699. appG := app.Gin{C: c}
  8700. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8701. fsions := gofasion.NewFasion(string(dataByte))
  8702. pastureid := fsions.Get("pastureId").ValueStr()
  8703. date := fsions.Get("date").ValueStr()
  8704. tx := restful.Engine.NewSession()
  8705. defer tx.Close()
  8706. pastureinfo := new(udPastureInfo)
  8707. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8708. if err != nil {
  8709. logs.Error(err)
  8710. return
  8711. }
  8712. ymy.YmyMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8713. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8714. }
  8715. func YmyFeedtempletPush(c *gin.Context) {
  8716. appG := app.Gin{C: c}
  8717. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8718. fsions := gofasion.NewFasion(string(dataByte))
  8719. pastureid := fsions.Get("pastureId").ValueStr()
  8720. date := fsions.Get("date").ValueStr()
  8721. tx := restful.Engine.NewSession()
  8722. defer tx.Close()
  8723. pastureinfo := new(udPastureInfo)
  8724. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8725. if err != nil {
  8726. logs.Error(err)
  8727. return
  8728. }
  8729. ymy.YmyFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8730. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8731. }
  8732. //饲料
  8733. func YmySyncFeed(c *gin.Context) {
  8734. appG := app.Gin{C: c}
  8735. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8736. fsions := gofasion.NewFasion(string(dataByte))
  8737. pastureid := fsions.Get("pastureId").ValueStr()
  8738. // date := fsions.Get("date").ValueStr()
  8739. tx := restful.Engine.NewSession()
  8740. defer tx.Close()
  8741. ymy.YmySyncFeed(pastureid)
  8742. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8743. }
  8744. // 栏舍
  8745. func YmySyncBar(c *gin.Context) {
  8746. appG := app.Gin{C: c}
  8747. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8748. fsions := gofasion.NewFasion(string(dataByte))
  8749. pastureid := fsions.Get("pastureId").ValueStr()
  8750. // date := fsions.Get("date").ValueStr()
  8751. tx := restful.Engine.NewSession()
  8752. defer tx.Close()
  8753. pastureinfo := new(udPastureInfo)
  8754. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8755. if err != nil {
  8756. logs.Error(err)
  8757. return
  8758. }
  8759. ymy.YmySyncBar(pastureinfo.Werks, pastureid)
  8760. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8761. }
  8762. func DelFeedTemplet(c *gin.Context) {
  8763. appG := app.Gin{C: c}
  8764. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8765. fsions := gofasion.NewFasion(string(dataByte))
  8766. ftId := fsions.Get("ftId").ValueStr()
  8767. // userId := fsions.Get("userId").ValueStr()
  8768. tx := restful.Engine.NewSession()
  8769. defer tx.Close()
  8770. _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
  8771. if err != nil {
  8772. logs.Error(err)
  8773. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8774. return
  8775. }
  8776. /*
  8777. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8778. if err != nil {
  8779. logs.Error(err)
  8780. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8781. return
  8782. }
  8783. */
  8784. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8785. if err != nil {
  8786. logs.Error(err)
  8787. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8788. return
  8789. }
  8790. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8791. if err != nil {
  8792. logs.Error(err)
  8793. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8794. return
  8795. }
  8796. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8797. if count > 0 {
  8798. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8799. if err != nil {
  8800. logs.Error(err)
  8801. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8802. return
  8803. }
  8804. }
  8805. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8806. if err != nil {
  8807. logs.Error(err)
  8808. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8809. return
  8810. }
  8811. // var barIdStr []string
  8812. // for _, bar := range barIdList {
  8813. // barIdStr = append(barIdStr, bar["barid"])
  8814. // }
  8815. // if len(barIdStr) > 0 {
  8816. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8817. // if err != nil {
  8818. // logs.Error(err)
  8819. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8820. // return
  8821. // }
  8822. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8823. // if err != nil {
  8824. // logs.Error(err)
  8825. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8826. // return
  8827. // }
  8828. // now := time.Now()
  8829. // for _, newFpd := range newFpdDataList {
  8830. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8831. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8832. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8833. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8834. // if err != nil {
  8835. // logs.Error(err)
  8836. // appG.Response(http.StatusOK, e.ERROR, false)
  8837. // return
  8838. // }
  8839. // }
  8840. // for _, newFeedp := range newFeedpList {
  8841. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8842. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8843. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8844. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8845. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8846. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8847. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8848. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8849. // if err != nil {
  8850. // logs.Error(err)
  8851. // appG.Response(http.StatusOK, e.ERROR, false)
  8852. // return
  8853. // }
  8854. // }
  8855. // }
  8856. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8857. }
  8858. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8859. sysOpt := new(models.SysOpt)
  8860. tx.Table("sysopt").Where("inforname = ?", "separateVehicles").Get(sysOpt)
  8861. lweight := 0.0
  8862. if sysOpt.InforValue != "" {
  8863. lweight, _ = strconv.ParseFloat(sysOpt.InforValue, 64)
  8864. } else if sysOpt.InforValue == "" || sysOpt.InforValue == "0" {
  8865. return
  8866. }
  8867. fmt.Println(sysOpt)
  8868. data := fasion["parammaps"].(map[string]interface{})
  8869. // plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(2) ").Count()
  8870. downloadedplanList := make([]*models.DownloadedPlan, 0)
  8871. tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype = 2 ").Find(&downloadedplanList)
  8872. fmt.Println(lweight)
  8873. for _, downloadedplan := range downloadedplanList {
  8874. if downloadedplan.LWeight < lweight {
  8875. break
  8876. }
  8877. downloadplandtl1List := make([]*models.DownloadPlanDtl1, 0)
  8878. downloadplandtl1ExecList := make([]*models.DownloadPlanDtl1Exec, 0)
  8879. downloadplandtl2List := make([]*models.DownloadPlanDtl2, 0)
  8880. tx.Table("downloadplandtl1").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1List)
  8881. tx.Table("downloadplandtl2").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl2List)
  8882. tx.Table("downloadplandtl1_exec").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1ExecList)
  8883. lweightCount := math.Floor(downloadedplan.LWeight / lweight)
  8884. for i := 0; i <= int(lweightCount); i++ {
  8885. if i == 0 {
  8886. tx.Exec(` update downloadedplan set lweight = ? where id = ? `, lweight, downloadedplan.ID)
  8887. for _, downloadplandtl1 := range downloadplandtl1List {
  8888. tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl1.LWeight, downloadplandtl1.ID)
  8889. }
  8890. for _, downloadplandtl2 := range downloadplandtl2List {
  8891. tx.Exec(` update downloadplandtl2 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8892. }
  8893. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  8894. tx.Exec(` update downloadplandtl1_exec set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8895. }
  8896. // && downloadedplan.LWeight >lweight
  8897. } else if i < int(lweightCount) {
  8898. parts := strings.Split(downloadedplan.ProjName, ".")
  8899. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  8900. data := &models.DownloadedPlan{
  8901. PastureID: downloadedplan.PastureID,
  8902. MyDate: downloadedplan.MyDate,
  8903. ProjName: strings.Join(parts, "."),
  8904. DataCaptureNo: downloadedplan.DataCaptureNo,
  8905. TmrID: downloadedplan.TmrID,
  8906. TmrtName: downloadedplan.TmrtName,
  8907. HaveButton: downloadedplan.HaveButton,
  8908. InButtonType: downloadedplan.InButtonType,
  8909. PlanTime: downloadedplan.PlanTime,
  8910. InTime: downloadedplan.InTime,
  8911. CompletedTime: downloadedplan.CompletedTime,
  8912. IsCompleted: downloadedplan.IsCompleted,
  8913. LpPlanType: downloadedplan.LpPlanType,
  8914. Times: downloadedplan.Times,
  8915. Sort: downloadedplan.Sort,
  8916. Remark: downloadedplan.Remark,
  8917. ItemNum: downloadedplan.ItemNum,
  8918. OutItems: downloadedplan.OutItems,
  8919. FeedPName: downloadedplan.FeedPName,
  8920. FeedPCount: downloadedplan.FeedPCount,
  8921. Pid: downloadedplan.Pid,
  8922. TempID: downloadedplan.TempID,
  8923. TempletName: downloadedplan.TempletName,
  8924. PtsTempID: downloadedplan.PtsTempID,
  8925. PtsTempletName: downloadedplan.PtsTempletName,
  8926. ThoWeight: downloadedplan.ThoWeight,
  8927. FpWeight: downloadedplan.FpWeight,
  8928. LWeight: lweight,
  8929. IWeight: downloadedplan.IWeight,
  8930. OWeight: downloadedplan.OWeight,
  8931. TVersion: downloadedplan.TVersion,
  8932. PtVersion: downloadedplan.PtVersion,
  8933. Enable: downloadedplan.Enable,
  8934. IsUse: downloadedplan.IsUse,
  8935. OldTmrID: downloadedplan.OldTmrID,
  8936. DriverID: downloadedplan.DriverID,
  8937. Artificial: downloadedplan.Artificial,
  8938. }
  8939. _, err := tx.Insert(data)
  8940. fmt.Println(data, err)
  8941. for _, downloadplandtl1 := range downloadplandtl1List {
  8942. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8943. d1 := &models.DownloadPlanDtl1{
  8944. PastureID: downloadplandtl1.PastureID,
  8945. Pid: data.ID,
  8946. Flpid: downloadplandtl1.Flpid,
  8947. Fid: downloadplandtl1.Fid,
  8948. LWeight: lweight / downloadedplan.LWeight * downloadplandtl1.LWeight,
  8949. Sort: downloadplandtl1.Sort,
  8950. ButtonType: downloadplandtl1.ButtonType,
  8951. OptDevice: downloadplandtl1.OptDevice,
  8952. FeedCode: downloadplandtl1.FeedCode,
  8953. FName: downloadplandtl1.FName,
  8954. FeedSort: downloadplandtl1.FeedSort,
  8955. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  8956. StirDelay: downloadplandtl1.StirDelay,
  8957. FWeight: downloadplandtl1.FWeight,
  8958. TmrLoadName: downloadplandtl1.TmrLoadName,
  8959. DryFeed: downloadplandtl1.DryFeed,
  8960. PriceFeed: downloadplandtl1.PriceFeed,
  8961. OutWeight: downloadplandtl1.OutWeight,
  8962. ErrRatio: downloadplandtl1.ErrRatio,
  8963. Date: downloadplandtl1.Date,
  8964. ButtonSucc: downloadplandtl1.ButtonSucc,
  8965. Type: downloadplandtl1.Type,
  8966. Deviation: downloadplandtl1.Deviation,
  8967. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  8968. }
  8969. tx.Insert(d1)
  8970. }
  8971. for _, downloadplandtl2 := range downloadplandtl2List {
  8972. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8973. d2 := &models.DownloadPlanDtl2{
  8974. PastureID: downloadplandtl2.PastureID,
  8975. Pid: data.ID,
  8976. Flpid: downloadplandtl2.Flpid,
  8977. Fbarid: downloadplandtl2.Fbarid,
  8978. FName: downloadplandtl2.FName,
  8979. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8980. LWeightHis: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8981. RemainLeftW: downloadplandtl2.RemainLeftW,
  8982. AllowRW: downloadplandtl2.AllowRW,
  8983. Sort: downloadplandtl2.Sort,
  8984. HaveButton: downloadplandtl2.HaveButton,
  8985. BeginTag: downloadplandtl2.BeginTag,
  8986. EndTag: downloadplandtl2.EndTag,
  8987. ButtonType: downloadplandtl2.ButtonType,
  8988. OptDevice: downloadplandtl2.OptDevice,
  8989. CowCount: downloadplandtl2.CowCount,
  8990. CowClassID: downloadplandtl2.CowClassID,
  8991. CowClassName: downloadplandtl2.CowClassName,
  8992. BigCowName: downloadplandtl2.BigCowName,
  8993. PWeight: downloadplandtl2.PWeight,
  8994. CCountRatio: downloadplandtl2.CCountRatio,
  8995. SumRTime: downloadplandtl2.SumRTime,
  8996. FeedTempletID: downloadplandtl2.FeedTempletID,
  8997. FeedTempletName: downloadplandtl2.FeedTempletName,
  8998. DryWeight: downloadplandtl2.DryWeight,
  8999. SumWeight: downloadplandtl2.SumWeight,
  9000. PriceWeight: downloadplandtl2.PriceWeight,
  9001. // ProcessTime :downloadplandtl2.ProcessTime ,
  9002. Fpid: downloadplandtl2.Fpid,
  9003. UseInBarType: downloadplandtl2.UseInBarType,
  9004. Date: downloadplandtl2.Date,
  9005. AllowRatio: downloadplandtl2.AllowRatio,
  9006. ErrRatio: downloadplandtl2.ErrRatio,
  9007. ButtonSucc: downloadplandtl2.ButtonSucc,
  9008. Type: downloadplandtl2.Type,
  9009. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9010. XxwBarCode: downloadplandtl2.XxwBarCode,
  9011. }
  9012. _, err := tx.Insert(d2)
  9013. fmt.Println(err)
  9014. }
  9015. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9016. d2 := &models.DownloadPlanDtl1Exec{
  9017. PastureID: downloadplandtl2.PastureID,
  9018. Pid: data.ID,
  9019. Flpid: downloadplandtl2.Flpid,
  9020. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9021. HaveButton: downloadplandtl2.HaveButton,
  9022. ButtonType: downloadplandtl2.ButtonType,
  9023. OptDevice: downloadplandtl2.OptDevice,
  9024. Sort: downloadplandtl2.Sort,
  9025. FName: downloadplandtl2.FName,
  9026. FCount: downloadplandtl2.FCount,
  9027. TmrLoadName: downloadplandtl2.TmrLoadName,
  9028. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9029. StirDelay: downloadplandtl2.StirDelay,
  9030. ButtonSucc: downloadplandtl2.ButtonSucc,
  9031. ErrRatio: downloadplandtl2.ErrRatio,
  9032. Date: downloadplandtl2.Date,
  9033. Type: downloadplandtl2.Type,
  9034. Deviation: downloadplandtl2.Deviation,
  9035. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9036. }
  9037. _, err := tx.Insert(d2)
  9038. fmt.Println(err)
  9039. }
  9040. } else {
  9041. parts := strings.Split(downloadedplan.ProjName, ".")
  9042. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  9043. if downloadedplan.LWeight-float64(i)*lweight <= 0 {
  9044. continue
  9045. }
  9046. data := &models.DownloadedPlan{
  9047. PastureID: downloadedplan.PastureID,
  9048. MyDate: downloadedplan.MyDate,
  9049. ProjName: strings.Join(parts, "."),
  9050. DataCaptureNo: downloadedplan.DataCaptureNo,
  9051. TmrID: downloadedplan.TmrID,
  9052. TmrtName: downloadedplan.TmrtName,
  9053. HaveButton: downloadedplan.HaveButton,
  9054. InButtonType: downloadedplan.InButtonType,
  9055. PlanTime: downloadedplan.PlanTime,
  9056. InTime: downloadedplan.InTime,
  9057. CompletedTime: downloadedplan.CompletedTime,
  9058. IsCompleted: downloadedplan.IsCompleted,
  9059. LpPlanType: downloadedplan.LpPlanType,
  9060. Times: downloadedplan.Times,
  9061. Sort: downloadedplan.Sort,
  9062. Remark: downloadedplan.Remark,
  9063. ItemNum: downloadedplan.ItemNum,
  9064. OutItems: downloadedplan.OutItems,
  9065. FeedPName: downloadedplan.FeedPName,
  9066. FeedPCount: downloadedplan.FeedPCount,
  9067. Pid: downloadedplan.Pid,
  9068. TempID: downloadedplan.TempID,
  9069. TempletName: downloadedplan.TempletName,
  9070. PtsTempID: downloadedplan.PtsTempID,
  9071. PtsTempletName: downloadedplan.PtsTempletName,
  9072. ThoWeight: downloadedplan.ThoWeight,
  9073. FpWeight: downloadedplan.FpWeight,
  9074. LWeight: downloadedplan.LWeight - float64(i)*lweight,
  9075. IWeight: downloadedplan.IWeight,
  9076. OWeight: downloadedplan.OWeight,
  9077. TVersion: downloadedplan.TVersion,
  9078. PtVersion: downloadedplan.PtVersion,
  9079. Enable: downloadedplan.Enable,
  9080. IsUse: downloadedplan.IsUse,
  9081. OldTmrID: downloadedplan.OldTmrID,
  9082. DriverID: downloadedplan.DriverID,
  9083. Artificial: downloadedplan.Artificial,
  9084. }
  9085. _, err := tx.Insert(data)
  9086. fmt.Println(data, err)
  9087. for _, downloadplandtl1 := range downloadplandtl1List {
  9088. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9089. d1 := &models.DownloadPlanDtl1{
  9090. PastureID: downloadplandtl1.PastureID,
  9091. Pid: data.ID,
  9092. Flpid: downloadplandtl1.Flpid,
  9093. Fid: downloadplandtl1.Fid,
  9094. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl1.LWeight,
  9095. Sort: downloadplandtl1.Sort,
  9096. ButtonType: downloadplandtl1.ButtonType,
  9097. OptDevice: downloadplandtl1.OptDevice,
  9098. FeedCode: downloadplandtl1.FeedCode,
  9099. FName: downloadplandtl1.FName,
  9100. FeedSort: downloadplandtl1.FeedSort,
  9101. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  9102. StirDelay: downloadplandtl1.StirDelay,
  9103. FWeight: downloadplandtl1.FWeight,
  9104. TmrLoadName: downloadplandtl1.TmrLoadName,
  9105. DryFeed: downloadplandtl1.DryFeed,
  9106. PriceFeed: downloadplandtl1.PriceFeed,
  9107. OutWeight: downloadplandtl1.OutWeight,
  9108. ErrRatio: downloadplandtl1.ErrRatio,
  9109. Date: downloadplandtl1.Date,
  9110. ButtonSucc: downloadplandtl1.ButtonSucc,
  9111. Type: downloadplandtl1.Type,
  9112. Deviation: downloadplandtl1.Deviation,
  9113. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  9114. }
  9115. tx.Insert(d1)
  9116. }
  9117. for _, downloadplandtl2 := range downloadplandtl2List {
  9118. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9119. d2 := &models.DownloadPlanDtl2{
  9120. PastureID: downloadplandtl2.PastureID,
  9121. Pid: data.ID,
  9122. Flpid: downloadplandtl2.Flpid,
  9123. Fbarid: downloadplandtl2.Fbarid,
  9124. FName: downloadplandtl2.FName,
  9125. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9126. LWeightHis: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9127. RemainLeftW: downloadplandtl2.RemainLeftW,
  9128. AllowRW: downloadplandtl2.AllowRW,
  9129. Sort: downloadplandtl2.Sort,
  9130. HaveButton: downloadplandtl2.HaveButton,
  9131. BeginTag: downloadplandtl2.BeginTag,
  9132. EndTag: downloadplandtl2.EndTag,
  9133. ButtonType: downloadplandtl2.ButtonType,
  9134. OptDevice: downloadplandtl2.OptDevice,
  9135. CowCount: downloadplandtl2.CowCount,
  9136. CowClassID: downloadplandtl2.CowClassID,
  9137. CowClassName: downloadplandtl2.CowClassName,
  9138. BigCowName: downloadplandtl2.BigCowName,
  9139. PWeight: downloadplandtl2.PWeight,
  9140. CCountRatio: downloadplandtl2.CCountRatio,
  9141. SumRTime: downloadplandtl2.SumRTime,
  9142. FeedTempletID: downloadplandtl2.FeedTempletID,
  9143. FeedTempletName: downloadplandtl2.FeedTempletName,
  9144. DryWeight: downloadplandtl2.DryWeight,
  9145. SumWeight: downloadplandtl2.SumWeight,
  9146. PriceWeight: downloadplandtl2.PriceWeight,
  9147. // ProcessTime :downloadplandtl2.ProcessTime ,
  9148. Fpid: downloadplandtl2.Fpid,
  9149. UseInBarType: downloadplandtl2.UseInBarType,
  9150. Date: downloadplandtl2.Date,
  9151. AllowRatio: downloadplandtl2.AllowRatio,
  9152. ErrRatio: downloadplandtl2.ErrRatio,
  9153. ButtonSucc: downloadplandtl2.ButtonSucc,
  9154. Type: downloadplandtl2.Type,
  9155. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9156. XxwBarCode: downloadplandtl2.XxwBarCode,
  9157. }
  9158. _, err := tx.Insert(d2)
  9159. fmt.Println(err)
  9160. }
  9161. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9162. d2 := &models.DownloadPlanDtl1Exec{
  9163. PastureID: downloadplandtl2.PastureID,
  9164. Pid: data.ID,
  9165. Flpid: downloadplandtl2.Flpid,
  9166. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9167. HaveButton: downloadplandtl2.HaveButton,
  9168. ButtonType: downloadplandtl2.ButtonType,
  9169. OptDevice: downloadplandtl2.OptDevice,
  9170. Sort: downloadplandtl2.Sort,
  9171. FName: downloadplandtl2.FName,
  9172. FCount: downloadplandtl2.FCount,
  9173. TmrLoadName: downloadplandtl2.TmrLoadName,
  9174. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9175. StirDelay: downloadplandtl2.StirDelay,
  9176. ButtonSucc: downloadplandtl2.ButtonSucc,
  9177. ErrRatio: downloadplandtl2.ErrRatio,
  9178. Date: downloadplandtl2.Date,
  9179. Type: downloadplandtl2.Type,
  9180. Deviation: downloadplandtl2.Deviation,
  9181. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9182. }
  9183. fmt.Println(d2)
  9184. _, err := tx.Insert(d2)
  9185. fmt.Println(err)
  9186. }
  9187. }
  9188. }
  9189. }
  9190. downloadedplanSortList := make([]*models.DownloadedPlan, 0)
  9191. tx.SQL(`SELECT * FROM downloadedplan WHERE mydate = ? ORDER BY projname`, data["startTime"]).Find(&downloadedplanSortList)
  9192. for i, d := range downloadedplanSortList {
  9193. tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, d.ID)
  9194. }
  9195. }
  9196. func EditPlanSort(c *gin.Context) {
  9197. appG := app.Gin{C: c}
  9198. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9199. fsions := gofasion.NewFasion(string(dataByte))
  9200. planIdStr := fsions.Get("planId").ValueStr()
  9201. mydate := fsions.Get("mydate").ValueStr()
  9202. sort := fsions.Get("sort").ValueStr()
  9203. tx := restful.Engine.NewSession()
  9204. defer tx.Close()
  9205. tx.Begin()
  9206. type downloadedplan struct {
  9207. Id int64 `xorm:"id"`
  9208. Sort int `xorm:"sort"`
  9209. Pid int64 `xorm:"pid"`
  9210. }
  9211. planInfo := new(downloadedplan)
  9212. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  9213. if err != nil {
  9214. logs.Error(err)
  9215. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9216. tx.Rollback()
  9217. return
  9218. }
  9219. sort1, _ := strconv.Atoi(sort)
  9220. if sort1 == planInfo.Sort {
  9221. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  9222. tx.Rollback()
  9223. return
  9224. }
  9225. 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()
  9226. if err != nil {
  9227. logs.Error(err)
  9228. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9229. tx.Rollback()
  9230. return
  9231. }
  9232. if count1 == 0 {
  9233. tx.Rollback()
  9234. logs.Error(err)
  9235. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  9236. return
  9237. }
  9238. 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()
  9239. if err != nil {
  9240. logs.Error(err)
  9241. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9242. tx.Rollback()
  9243. return
  9244. }
  9245. if count > 0 {
  9246. tx.Rollback()
  9247. logs.Error(err)
  9248. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  9249. return
  9250. }
  9251. if planInfo.Sort > sort1 {
  9252. 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()
  9253. if err != nil {
  9254. logs.Error(err)
  9255. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9256. tx.Rollback()
  9257. return
  9258. }
  9259. var minSort, pidCount int
  9260. for _, sort := range minSortList {
  9261. minSort, _ = strconv.Atoi(sort["sort"])
  9262. }
  9263. planList := make([]*downloadedplan, 0)
  9264. 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)
  9265. if err != nil {
  9266. logs.Error(err)
  9267. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9268. tx.Rollback()
  9269. return
  9270. }
  9271. planPid := planInfo.Pid
  9272. planList1 := make([]*downloadedplan, 0)
  9273. planList2 := make([]*downloadedplan, 0)
  9274. for _, plan := range planList {
  9275. if plan.Pid == planPid {
  9276. pidCount++
  9277. planList1 = append(planList1, plan)
  9278. } else {
  9279. planList2 = append(planList2, plan)
  9280. }
  9281. }
  9282. planList1 = append(planList1, planList2...)
  9283. for i, plan := range planList1 {
  9284. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  9285. if err != nil {
  9286. logs.Error(err)
  9287. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9288. tx.Rollback()
  9289. return
  9290. }
  9291. }
  9292. } else {
  9293. 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()
  9294. if err != nil {
  9295. logs.Error(err)
  9296. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9297. tx.Rollback()
  9298. return
  9299. }
  9300. var maxSort int
  9301. for _, sort := range maxSortList {
  9302. maxSort, _ = strconv.Atoi(sort["sort"])
  9303. }
  9304. planList := make([]*downloadedplan, 0)
  9305. 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)
  9306. if err != nil {
  9307. logs.Error(err)
  9308. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9309. tx.Rollback()
  9310. return
  9311. }
  9312. planPid := planInfo.Pid
  9313. planList1 := make([]*downloadedplan, 0)
  9314. planList2 := make([]*downloadedplan, 0)
  9315. for _, plan := range planList {
  9316. if plan.Pid == planPid {
  9317. // pidCount++
  9318. planList1 = append(planList1, plan)
  9319. } else {
  9320. planList2 = append(planList2, plan)
  9321. }
  9322. }
  9323. planList2 = append(planList2, planList1...)
  9324. for i, plan := range planList2 {
  9325. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  9326. if err != nil {
  9327. logs.Error(err)
  9328. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9329. tx.Rollback()
  9330. return
  9331. }
  9332. }
  9333. }
  9334. err = tx.Commit()
  9335. if err != nil {
  9336. logs.Error(err)
  9337. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9338. tx.Rollback()
  9339. return
  9340. }
  9341. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9342. }
  9343. func EditDownloadedplanArtificial(c *gin.Context) {
  9344. appG := app.Gin{C: c}
  9345. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9346. fsions := gofasion.NewFasion(string(dataByte))
  9347. planIdStr := fsions.Get("planId").ValueStr()
  9348. tx := restful.Engine.NewSession()
  9349. defer tx.Close()
  9350. tx.Begin()
  9351. planIdList := strings.Split(planIdStr, ",")
  9352. for _, planId := range planIdList {
  9353. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? `, planId)
  9354. if err != nil {
  9355. logs.Error(err)
  9356. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9357. tx.Rollback()
  9358. return
  9359. }
  9360. }
  9361. err := tx.Commit()
  9362. if err != nil {
  9363. logs.Error(err)
  9364. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9365. tx.Rollback()
  9366. return
  9367. }
  9368. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9369. }
  9370. type PlanRFID struct {
  9371. RFID string `json:"RFID"`
  9372. Lweight string `json:"lweight"`
  9373. Gear string `json:"gear"`
  9374. Speed string `json:"speed"`
  9375. }
  9376. func GetPlanRFID(c *gin.Context) {
  9377. appG := app.Gin{C: c}
  9378. RFIDStr := c.Query("RFID")
  9379. planRFIDList := make([]*PlanRFID, 0)
  9380. planRFIDList = append(planRFIDList, &PlanRFID{
  9381. RFID: RFIDStr,
  9382. Lweight: "1411.1",
  9383. Gear: "1",
  9384. Speed: "10",
  9385. })
  9386. planRFIDList = append(planRFIDList, &PlanRFID{
  9387. RFID: RFIDStr,
  9388. Lweight: "1322.1",
  9389. Gear: "1",
  9390. Speed: "10",
  9391. })
  9392. planRFIDList = append(planRFIDList, &PlanRFID{
  9393. RFID: RFIDStr,
  9394. Lweight: "1904.1",
  9395. Gear: "1",
  9396. Speed: "10",
  9397. })
  9398. planRFIDList = append(planRFIDList, &PlanRFID{
  9399. RFID: RFIDStr,
  9400. Lweight: "1870.1",
  9401. Gear: "1",
  9402. Speed: "10",
  9403. })
  9404. planRFIDList = append(planRFIDList, &PlanRFID{
  9405. RFID: RFIDStr,
  9406. Lweight: "2041.1",
  9407. Gear: "1",
  9408. Speed: "10",
  9409. })
  9410. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  9411. }
  9412. type tmrEquipmentMuster struct {
  9413. A string
  9414. N string
  9415. }
  9416. func GetTmrEquipmentMuster(c *gin.Context) {
  9417. appG := app.Gin{C: c}
  9418. id := c.Query("id")
  9419. tx := restful.Engine.NewSession()
  9420. defer tx.Close()
  9421. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  9422. if err != nil {
  9423. logs.Error(err)
  9424. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9425. return
  9426. }
  9427. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  9428. for _, data := range dataList {
  9429. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  9430. for _, g := range tmrEquipmentMusterList {
  9431. a, _ := strconv.ParseFloat(g.A, 64)
  9432. n, _ := strconv.ParseFloat(g.N, 64)
  9433. a1, n1 := ddmmtoddd(a, n)
  9434. g.A = fmt.Sprintf("%f", n1)
  9435. g.N = fmt.Sprintf("%f", a1)
  9436. }
  9437. }
  9438. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  9439. }
  9440. func ddmmtoddd(lng, lat float64) (float64, float64) {
  9441. lngDegree := fmt.Sprintf("%f", lng/100)
  9442. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  9443. lngDegreeInt := int(lngDegreefloat * 1000000)
  9444. dd := lngDegreeInt / 100 * 100 / 60
  9445. fmt.Println(dd)
  9446. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  9447. latDegree := fmt.Sprintf("%f", lat/100)
  9448. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  9449. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  9450. latDegreeInt := int(latDegreefloat * 1000000)
  9451. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  9452. a, _ := strconv.ParseFloat(lngStr, 64)
  9453. b, _ := strconv.ParseFloat(latStr, 64)
  9454. return coordtransform.WGS84toGCJ02(b, a)
  9455. }
  9456. func EditDownloadedplanExecWeight(c *gin.Context) {
  9457. appG := app.Gin{C: c}
  9458. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9459. fsions := gofasion.NewFasion(string(dataByte))
  9460. pid := fsions.Get("pid").ValueStr()
  9461. sort := fsions.Get("sort").ValueStr()
  9462. weight := fsions.Get("weight").ValueStr()
  9463. userId := fsions.Get("userId").ValueStr()
  9464. tx := restful.Engine.NewSession()
  9465. defer tx.Close()
  9466. tx.Begin()
  9467. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  9468. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  9469. pid, sort, pid, sort, weight, userId)
  9470. if err != nil {
  9471. logs.Error(err)
  9472. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9473. tx.Rollback()
  9474. return
  9475. }
  9476. _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9477. if err != nil {
  9478. logs.Error(err)
  9479. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9480. tx.Rollback()
  9481. return
  9482. }
  9483. _, 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)
  9484. if err != nil {
  9485. logs.Error(err)
  9486. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9487. tx.Rollback()
  9488. return
  9489. }
  9490. err = tx.Commit()
  9491. if err != nil {
  9492. logs.Error(err)
  9493. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9494. tx.Rollback()
  9495. return
  9496. }
  9497. appG.Response(http.StatusOK, e.SUCCESS, true)
  9498. }
  9499. func EditDownloadplandtl2Weight(c *gin.Context) {
  9500. appG := app.Gin{C: c}
  9501. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9502. fsions := gofasion.NewFasion(string(dataByte))
  9503. pid := fsions.Get("pid").ValueStr()
  9504. sort := fsions.Get("sort").ValueStr()
  9505. weight := fsions.Get("weight").ValueStr()
  9506. userId := fsions.Get("userId").ValueStr()
  9507. tx := restful.Engine.NewSession()
  9508. defer tx.Close()
  9509. tx.Begin()
  9510. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9511. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9512. pid, sort, pid, sort, weight, userId)
  9513. if err != nil {
  9514. logs.Error(err)
  9515. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9516. tx.Rollback()
  9517. return
  9518. }
  9519. _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9520. if err != nil {
  9521. logs.Error(err)
  9522. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9523. tx.Rollback()
  9524. return
  9525. }
  9526. err = tx.Commit()
  9527. if err != nil {
  9528. logs.Error(err)
  9529. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9530. tx.Rollback()
  9531. return
  9532. }
  9533. appG.Response(http.StatusOK, e.SUCCESS, true)
  9534. }
  9535. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9536. params := fasion.Get("parammaps")
  9537. surplus := params.Get("surplus").ValueStr()
  9538. surplusId := params.Get("surplusId").ValueStr()
  9539. tx := restful.Engine.NewSession()
  9540. defer tx.Close()
  9541. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9542. if surplusId != "0" {
  9543. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9544. if err != nil {
  9545. log.Println("PostDataByName-error-1: ", err)
  9546. return errors.New("配方修改失败!")
  9547. }
  9548. type ftdetail struct {
  9549. Id string
  9550. Fname string
  9551. Sort int64
  9552. }
  9553. ftList := make([]*ftdetail, 0)
  9554. for _, data := range dataList {
  9555. ft := new(ftdetail)
  9556. ft.Fname = data["fname"]
  9557. ft.Id = data["id"]
  9558. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9559. if err != nil {
  9560. log.Println("PostDataByName-error-2: ", err)
  9561. return err
  9562. }
  9563. ft.Sort = sort
  9564. ftList = append(ftList, ft)
  9565. }
  9566. if surplus == "日粮" {
  9567. for _, ft := range ftList {
  9568. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9569. }
  9570. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9571. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9572. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9573. fmt.Println(err)
  9574. } else {
  9575. var sort int64
  9576. for _, ft := range ftList {
  9577. if ft.Fname == surplus {
  9578. sort = ft.Sort
  9579. break
  9580. }
  9581. }
  9582. if sort == 0 {
  9583. for _, ft := range ftList {
  9584. ft.Sort = ft.Sort + 1
  9585. }
  9586. } else {
  9587. for _, ft := range ftList {
  9588. if ft.Sort >= sort {
  9589. ft.Sort = ft.Sort + 1
  9590. }
  9591. }
  9592. }
  9593. for _, ft := range ftList {
  9594. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9595. }
  9596. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9597. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9598. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9599. if err != nil {
  9600. log.Println("PostDataByName-error-1: ", err)
  9601. fmt.Println(err)
  9602. return errors.New("配方修改失败!")
  9603. }
  9604. }
  9605. }
  9606. return nil
  9607. }
  9608. func FeedSurplus(fasion *gofasion.Fasion) {
  9609. tx := restful.Engine.NewSession()
  9610. defer tx.Close()
  9611. params := fasion.Get("parammaps")
  9612. feedId := params.Get("id").ValueStr()
  9613. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9614. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9615. }
  9616. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9617. // params := fasion.Get("parammaps")
  9618. // surplus := params.Get("surplus").ValueStr()
  9619. // surplusId := params.Get("surplusId").ValueStr()
  9620. tx := restful.Engine.NewSession()
  9621. defer tx.Close()
  9622. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9623. if surplusId != "0" {
  9624. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9625. if err != nil {
  9626. log.Println("PostDataByName-error-1: ", err)
  9627. return errors.New("配方修改失败!")
  9628. }
  9629. type ftdetail struct {
  9630. Id string
  9631. Fname string
  9632. Sort int64
  9633. }
  9634. ftList := make([]*ftdetail, 0)
  9635. for _, data := range dataList {
  9636. ft := new(ftdetail)
  9637. ft.Fname = data["fname"]
  9638. ft.Id = data["id"]
  9639. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9640. if err != nil {
  9641. log.Println("PostDataByName-error-2: ", err)
  9642. return err
  9643. }
  9644. ft.Sort = sort
  9645. ftList = append(ftList, ft)
  9646. }
  9647. if surplus == "日粮" {
  9648. for _, ft := range ftList {
  9649. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9650. }
  9651. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9652. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9653. pastureId, id, surplusId, surplusId, surplusId)
  9654. fmt.Println(err)
  9655. } else {
  9656. var sort int64
  9657. for _, ft := range ftList {
  9658. if ft.Fname == surplus {
  9659. sort = ft.Sort
  9660. break
  9661. }
  9662. }
  9663. if sort == 0 {
  9664. for _, ft := range ftList {
  9665. ft.Sort = ft.Sort + 1
  9666. }
  9667. } else {
  9668. for _, ft := range ftList {
  9669. if ft.Sort >= sort {
  9670. ft.Sort = ft.Sort + 1
  9671. }
  9672. }
  9673. }
  9674. for _, ft := range ftList {
  9675. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9676. }
  9677. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9678. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9679. id, surplusId, surplusId, sort, surplusId, pastureId)
  9680. if err != nil {
  9681. log.Println("PostDataByName-error-1: ", err)
  9682. fmt.Println(err)
  9683. return errors.New("配方修改失败!")
  9684. }
  9685. }
  9686. }
  9687. return nil
  9688. }
  9689. func GetLanguageStatus() string {
  9690. tx := restful.Engine.NewSession()
  9691. defer tx.Close()
  9692. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9693. if err != nil {
  9694. log.Println(err)
  9695. return "0"
  9696. }
  9697. return dataList[0]["inforvalue"]
  9698. }
  9699. func EditLanguage(c *gin.Context) {
  9700. appG := app.Gin{C: c}
  9701. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9702. fsions := gofasion.NewFasion(string(dataByte))
  9703. language := fsions.Get("language").ValueStr()
  9704. tx := restful.Engine.NewSession()
  9705. defer tx.Close()
  9706. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9707. if err != nil {
  9708. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9709. return
  9710. }
  9711. if language == "0" {
  9712. _, err := tx.Exec(`delete from dictlist `)
  9713. if err != nil {
  9714. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9715. return
  9716. }
  9717. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9718. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9719. if err != nil {
  9720. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9721. return
  9722. }
  9723. } else {
  9724. _, err := tx.Exec(`delete from dictlist `)
  9725. if err != nil {
  9726. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9727. return
  9728. }
  9729. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9730. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9731. if err != nil {
  9732. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9733. return
  9734. }
  9735. }
  9736. appG.Response(http.StatusOK, e.SUCCESS, true)
  9737. }
  9738. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9739. tx := restful.Engine.NewSession()
  9740. defer tx.Close()
  9741. 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
  9742. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9743. if err != nil {
  9744. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9745. return
  9746. }
  9747. for _, dataexcel := range barList {
  9748. // dataexcel := make(map[string]interface{}, 0)
  9749. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9750. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9751. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9752. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9753. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9754. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9755. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9756. // if err != nil {
  9757. // logs.Error(err)
  9758. // return
  9759. // }
  9760. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9761. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9762. // if err != nil {
  9763. // logs.Error(err)
  9764. // return
  9765. // }
  9766. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9767. continue
  9768. }
  9769. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9770. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9771. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9772. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9773. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9774. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9775. // /*
  9776. // ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  9777. // if err != nil {
  9778. // logs.Error(err)
  9779. // return
  9780. // }
  9781. // if !ftexist {
  9782. // fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  9783. tx.SQL(` update lpplandtl1 set lweight = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9784. if err != nil {
  9785. logs.Error(err)
  9786. return
  9787. }
  9788. tx.SQL(` update fpdetail set ptuse = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9789. if err != nil {
  9790. logs.Error(err)
  9791. return
  9792. }
  9793. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  9794. // and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  9795. // if err != nil {
  9796. // tx.Rollback()
  9797. // logs.Error(err)
  9798. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  9799. // return
  9800. // }
  9801. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9802. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  9803. // if err != nil {
  9804. // tx.Rollback()
  9805. // logs.Error(err)
  9806. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  9807. // return
  9808. // }
  9809. // }
  9810. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  9811. // and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  9812. // if count == 1 {
  9813. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  9814. // and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  9815. // if err != nil {
  9816. // tx.Rollback()
  9817. // logs.Error(err)
  9818. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  9819. // return
  9820. // }
  9821. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9822. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  9823. // if err != nil {
  9824. // tx.Rollback()
  9825. // logs.Error(err)
  9826. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  9827. // return
  9828. // }
  9829. // }
  9830. // */
  9831. exist, err := tx.SQL(` select id from feedp where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9832. if err != nil {
  9833. fmt.Println("1111111111111111111")
  9834. logs.Error(err)
  9835. return
  9836. }
  9837. if !exist {
  9838. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9839. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9840. if err != nil {
  9841. fmt.Println("1111111111111111111")
  9842. logs.Error(err)
  9843. return
  9844. }
  9845. }
  9846. var feedpargs []interface{}
  9847. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9848. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9849. if _, ok := dataexcel["ftname"]; ok {
  9850. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9851. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9852. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9853. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9854. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9855. } else {
  9856. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9857. }
  9858. if _, ok := dataexcel["ptsfname"]; ok {
  9859. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9860. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9861. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9862. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9863. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9864. } else {
  9865. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9866. }
  9867. upFeedpSql += " where barname = ? and pastureid = ? "
  9868. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9869. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9870. if err != nil {
  9871. logs.Error(err)
  9872. return
  9873. }
  9874. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9875. if err != nil {
  9876. logs.Error(err)
  9877. return
  9878. }
  9879. if !exist1 {
  9880. _, 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) `,
  9881. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9882. if err != nil {
  9883. logs.Error(err)
  9884. return
  9885. }
  9886. }
  9887. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9888. if err != nil {
  9889. logs.Error(err)
  9890. return
  9891. }
  9892. if !exist2 {
  9893. _, 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) `,
  9894. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9895. if err != nil {
  9896. logs.Error(err)
  9897. return
  9898. }
  9899. }
  9900. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9901. if err != nil {
  9902. logs.Error(err)
  9903. return
  9904. }
  9905. if !exist3 {
  9906. _, 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) `,
  9907. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9908. if err != nil {
  9909. logs.Error(err)
  9910. return
  9911. }
  9912. }
  9913. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9914. if err != nil {
  9915. logs.Error(err)
  9916. return
  9917. }
  9918. if !exist4 {
  9919. _, 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) `,
  9920. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9921. if err != nil {
  9922. logs.Error(err)
  9923. return
  9924. }
  9925. }
  9926. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9927. if err != nil {
  9928. logs.Error(err)
  9929. return
  9930. }
  9931. if !exist5 {
  9932. _, 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) `,
  9933. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9934. if err != nil {
  9935. logs.Error(err)
  9936. return
  9937. }
  9938. }
  9939. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9940. if err != nil {
  9941. logs.Error(err)
  9942. return
  9943. }
  9944. if !exist6 {
  9945. _, 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) `,
  9946. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9947. if err != nil {
  9948. logs.Error(err)
  9949. return
  9950. }
  9951. }
  9952. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9953. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9954. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9955. and pastureid = ? and times = ?`
  9956. var fpdargs1 []interface{}
  9957. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9958. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9959. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9960. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9961. if err != nil {
  9962. fmt.Println(err)
  9963. return
  9964. }
  9965. var fpdargs2 []interface{}
  9966. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9967. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9968. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9969. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9970. if err != nil {
  9971. fmt.Println(err)
  9972. return
  9973. }
  9974. var fpdargs3 []interface{}
  9975. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9976. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9977. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9978. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9979. if err != nil {
  9980. fmt.Println(err)
  9981. return
  9982. }
  9983. var fpdargs4 []interface{}
  9984. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9985. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9986. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9987. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9988. if err != nil {
  9989. fmt.Println(err)
  9990. return
  9991. }
  9992. var fpdargs5 []interface{}
  9993. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9994. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9995. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9996. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9997. if err != nil {
  9998. fmt.Println(err)
  9999. return
  10000. }
  10001. var fpdargs6 []interface{}
  10002. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  10003. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  10004. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10005. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10006. if err != nil {
  10007. fmt.Println(err)
  10008. return
  10009. }
  10010. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10011. 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()
  10012. if err != nil {
  10013. return
  10014. }
  10015. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10016. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10017. upFpdetailList := make([]*upFpdetail, 0)
  10018. for _, newfpd := range newList {
  10019. for _, oldfpd := range oldFpdList {
  10020. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10021. var oldweight, newweight float64
  10022. if oldfpd["weight"] != nil {
  10023. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10024. }
  10025. if newfpd["weight"] != nil {
  10026. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10027. }
  10028. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10029. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10030. Old: oldweight,
  10031. New: newweight,
  10032. Times: newfpd["times"].(int64),
  10033. Ptid: newfpd["ptid"].(int64),
  10034. Fweight: fweight,
  10035. Id: oldfpd["id"].(int64),
  10036. })
  10037. break
  10038. }
  10039. }
  10040. }
  10041. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  10042. }
  10043. }
  10044. func AddXxwFtdetail(c *gin.Context) {
  10045. appG := app.Gin{C: c}
  10046. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  10047. c.Bind(&xxwFtdetailList)
  10048. tx := restful.Engine.NewSession()
  10049. defer tx.Close()
  10050. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  10051. if err != nil {
  10052. logs.Error(err)
  10053. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10054. }
  10055. _, err = tx.Insert(xxwFtdetailList)
  10056. if err != nil {
  10057. logs.Error(err)
  10058. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10059. }
  10060. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  10061. appG.Response(http.StatusOK, e.SUCCESS, true)
  10062. }
  10063. func AddXxwFeedtemplet(c *gin.Context) {
  10064. appG := app.Gin{C: c}
  10065. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  10066. c.Bind(&xxwFeedtempletList)
  10067. tx := restful.Engine.NewSession()
  10068. defer tx.Close()
  10069. pastureinfo := new(udPastureInfo)
  10070. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  10071. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  10072. if err != nil {
  10073. logs.Error(err)
  10074. return
  10075. }
  10076. for _, ft := range xxwFeedtempletList {
  10077. ids, err := setting.SnowIds.NextId()
  10078. if err != nil {
  10079. ids = time.Now().UnixNano()
  10080. logging.Info("create SnowIds err", err)
  10081. }
  10082. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  10083. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  10084. ft.RecipeobjName, ft.RecipeobjName)
  10085. if err != nil {
  10086. logs.Error(err)
  10087. return
  10088. }
  10089. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  10090. _, 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')),
  10091. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  10092. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  10093. if err != nil {
  10094. logs.Error(err)
  10095. return
  10096. }
  10097. }
  10098. appG.Response(http.StatusOK, e.SUCCESS, true)
  10099. }
  10100. func ProcessExcel(c *gin.Context) {
  10101. appG := app.Gin{C: c}
  10102. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10103. fasion := gofasion.NewFasion(string(dataByte))
  10104. params := fasion.Get("parammaps")
  10105. pastureid := params.Get("pastureid").ValueStr()
  10106. startTime := params.Get("startTime").ValueStr()
  10107. stopTime := params.Get("stopTime").ValueStr()
  10108. iscompleted := params.Get("iscompleted").ValueStr()
  10109. lpplantype := params.Get("lpplantype").ValueStr()
  10110. error := params.Get("error").ValueStr()
  10111. hlwc1 := params.Get("hlwc1").ValueStr()
  10112. hlwc2 := params.Get("hlwc2").ValueStr()
  10113. slwc1 := params.Get("slwc1").ValueStr()
  10114. slwc2 := params.Get("slwc2").ValueStr()
  10115. hlzq1 := params.Get("hlzq1").ValueStr()
  10116. hlzq2 := params.Get("hlzq2").ValueStr()
  10117. slzq1 := params.Get("slzq1").ValueStr()
  10118. slzq2 := params.Get("slzq2").ValueStr()
  10119. fclassid := params.Get("fclassid").ValueStr()
  10120. minproesstime := params.Get("minproesstime").ValueStr()
  10121. maxproesstime := params.Get("maxproesstime").ValueStr()
  10122. tx := restful.Engine.NewSession()
  10123. defer tx.Close()
  10124. planList, err := tx.SQL(`SELECT
  10125. 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
  10126. FROM downloadedplan d
  10127. join pasture p on p.pastureid = d.pastureid
  10128. WHERE d.pastureid= ? and d.intime IS NOT NULL
  10129. AND mydate >= ? AND mydate <= ?
  10130. AND (iscompleted=? or ?='')
  10131. AND (lpplantype = ? or ? = '')
  10132. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  10133. 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
  10134. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  10135. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10136. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  10137. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10138. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  10139. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10140. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  10141. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10142. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  10143. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  10144. 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,
  10145. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  10146. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  10147. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  10148. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10149. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  10150. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  10151. or (?= '' and ? = '' ))
  10152. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  10153. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  10154. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  10155. maxproesstime, minproesstime, maxproesstime).QueryString()
  10156. if err != nil {
  10157. logs.Error(err)
  10158. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10159. return
  10160. }
  10161. planExecList, err := tx.SQL(`SELECT
  10162. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10163. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10164. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  10165. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10166. ) proesstime,
  10167. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10168. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  10169. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10170. sumproesstime, d1.pid,
  10171. d1.sort,
  10172. d1.fname,
  10173. d1.lweight,
  10174. d1.actualweightminus,
  10175. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  10176. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  10177. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  10178. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  10179. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  10180. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  10181. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  10182. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10183. d1.begintime stoptime,
  10184. d1.lastactualweight,
  10185. d1.actualweight,
  10186. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  10187. case d1.buttontype
  10188. when 1 then '自动'
  10189. when 2 then '手动'
  10190. when 3 then '手动'
  10191. end,
  10192. case d1.buttontype
  10193. when 1 then 'Automatic'
  10194. when 2 then 'Manual'
  10195. when 3 then 'Manual'
  10196. end
  10197. ) buttontype
  10198. FROM
  10199. downloadplandtl1_exec d1
  10200. WHERE d1.date between ? and ?
  10201. ORDER BY sort
  10202. `, startTime, stopTime).QueryString()
  10203. if err != nil {
  10204. logs.Error(err)
  10205. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10206. return
  10207. }
  10208. planExec2, err := tx.SQL(`SELECT
  10209. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  10210. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10211. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10212. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  10213. ) proesstime,
  10214. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  10215. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10216. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  10217. d1.sort,
  10218. d1.fname,
  10219. d1.lweight,
  10220. d1.actualweightminus,
  10221. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  10222. ABS(d1.lweight- d1.actualweightminus) diff,
  10223. 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,
  10224. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10225. d1.begintime stoptime,
  10226. d1.lastactualweight,
  10227. d1.actualweight,d1.pid
  10228. FROM
  10229. downloadplandtl2 d1
  10230. WHERE d1.date between ? and ?
  10231. ORDER BY sort`, startTime, stopTime).QueryString()
  10232. if err != nil {
  10233. logs.Error(err)
  10234. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10235. return
  10236. }
  10237. // 创建一个新的 Excel 文件
  10238. f := excelizexuri.NewFile()
  10239. // 创建工作表名称
  10240. sheetName := "Sheet1"
  10241. // border := []excelizexuri.Border{
  10242. // {Type: "left", Color: "000000", Style: 1},
  10243. // {Type: "right", Color: "000000", Style: 1},
  10244. // {Type: "top", Color: "000000", Style: 1},
  10245. // {Type: "bottom", Color: "000000", Style: 1},
  10246. // }
  10247. // 创建新的样式
  10248. style := &excelizexuri.Style{
  10249. // Border: border,
  10250. Alignment: &excelizexuri.Alignment{
  10251. Vertical: "center",
  10252. Horizontal: "center",
  10253. ShrinkToFit: true,
  10254. WrapText: true,
  10255. },
  10256. }
  10257. styleTitle := &excelizexuri.Style{
  10258. Fill: excelizexuri.Fill{
  10259. Color: []string{"FFFF0000"}, // 尝试使用完整的ARGB格式
  10260. },
  10261. // Border: border,
  10262. Font: &excelizexuri.Font{
  10263. Bold: true, // 加粗
  10264. Size: 24, // 字体大小
  10265. // Name: "宋体", // 字体名称
  10266. // WrapText :true,
  10267. Color: "000000", // 字体颜色(黑色)
  10268. },
  10269. Alignment: &excelizexuri.Alignment{
  10270. Vertical: "center", // 垂直居中
  10271. Horizontal: "center", // 水平居中
  10272. ShrinkToFit: true,
  10273. WrapText: true,
  10274. },
  10275. }
  10276. // 创建样式 ID
  10277. styleTitleId, err := f.NewStyle(styleTitle)
  10278. if err != nil {
  10279. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10280. return
  10281. }
  10282. // 创建样式 ID
  10283. styleID, err := f.NewStyle(style)
  10284. if err != nil {
  10285. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10286. return
  10287. }
  10288. // 合并单元格并设置内容
  10289. f.MergeCell(sheetName, "A1", "K1")
  10290. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  10291. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  10292. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  10293. planExecMap := make(map[string][]map[string]string, 0)
  10294. for _, planExec := range planExecList {
  10295. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  10296. }
  10297. plan2Map := make(map[string][]map[string]string, 0)
  10298. for _, plan2 := range planExec2 {
  10299. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  10300. }
  10301. num := 2
  10302. var notBorder []int
  10303. for _, plan := range planList {
  10304. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  10305. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10306. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10307. for i, header := range headers {
  10308. // 从 A2 开始
  10309. if header == "开始日期" {
  10310. cell := "%" + fmt.Sprintf("c%d", num)
  10311. cell = fmt.Sprintf(cell, 'A'+i+1)
  10312. f.SetCellValue(sheetName, cell, header)
  10313. f.SetCellStyle(sheetName, cell, cell, styleID)
  10314. continue
  10315. }
  10316. cell := "%" + fmt.Sprintf("c%d", num)
  10317. cell = fmt.Sprintf(cell, 'A'+i)
  10318. f.SetCellValue(sheetName, cell, header)
  10319. f.SetCellStyle(sheetName, cell, cell, styleID)
  10320. }
  10321. num += 1
  10322. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  10323. cell := "%" + fmt.Sprintf("c%d", num)
  10324. cell = fmt.Sprintf(cell, 'A'+0)
  10325. f.SetCellValue(sheetName, cell, plan["pastureName"])
  10326. f.SetCellStyle(sheetName, cell, cell, styleID)
  10327. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  10328. cell = "%" + fmt.Sprintf("c%d", num)
  10329. cell = fmt.Sprintf(cell, 'A'+1)
  10330. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  10331. f.SetCellStyle(sheetName, cell, cell, styleID)
  10332. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  10333. cell = "%" + fmt.Sprintf("c%d", num)
  10334. cell = fmt.Sprintf(cell, 'A'+2)
  10335. f.SetCellValue(sheetName, cell, plan["projname"])
  10336. f.SetCellStyle(sheetName, cell, cell, styleID)
  10337. cell = "%" + fmt.Sprintf("c%d", num)
  10338. cell = fmt.Sprintf(cell, 'A'+3)
  10339. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10340. f.SetCellValue(sheetName, cell, plan["mydate"])
  10341. f.SetCellStyle(sheetName, cell, cell, styleID)
  10342. cell = "%" + fmt.Sprintf("c%d", num)
  10343. cell = fmt.Sprintf(cell, 'A'+6)
  10344. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10345. f.SetCellValue(sheetName, cell, plan["intime"])
  10346. f.SetCellStyle(sheetName, cell, cell, styleID)
  10347. num += 1
  10348. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10349. for i, header := range headers1 {
  10350. cell = "%" + fmt.Sprintf("c%d", num)
  10351. cell = fmt.Sprintf(cell, 'C'+i)
  10352. f.SetCellValue(sheetName, cell, header)
  10353. f.SetCellStyle(sheetName, cell, cell, styleID)
  10354. // maxWidth := len(header)
  10355. // colName := string('C' + i)
  10356. // f.SetColWidth(sheetName, colName, colName, 20)
  10357. f.SetColWidth(sheetName, header, header, 40)
  10358. }
  10359. num += 1
  10360. // 在循环外部创建红色样式(只创建一次)
  10361. redStyle := &excelizexuri.Style{
  10362. Fill: excelizexuri.Fill{
  10363. Type: "pattern",
  10364. Color: []string{"FF0000"},
  10365. Pattern: 1,
  10366. },
  10367. // Font: &excelizexuri.Font{
  10368. // Bold: true, // 加粗
  10369. // Size: 24, // 字体大小
  10370. // // Name: "宋体", // 字体名称
  10371. // // WrapText :true,
  10372. // Color: "FFFF0000", // 字体颜色(黑色)
  10373. // },
  10374. Alignment: &excelizexuri.Alignment{
  10375. Vertical: "center",
  10376. Horizontal: "center",
  10377. ShrinkToFit: true,
  10378. WrapText: true,
  10379. },
  10380. }
  10381. redStyleID, err := f.NewStyle(redStyle)
  10382. if err != nil {
  10383. c.String(http.StatusInternalServerError, "Failed to create red style: "+err.Error())
  10384. return
  10385. }
  10386. // 在循环内部正确使用条件判断
  10387. for _, planExec := range planExecMap[plan["id"]] {
  10388. var currentStyleID int
  10389. if planExec["abnormal"] == "1" {
  10390. currentStyleID = redStyleID
  10391. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, planExec["abnormal"]) // 调试
  10392. } else {
  10393. currentStyleID = styleID
  10394. }
  10395. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10396. sort, _ := strconv.Atoi(planExec["sort"])
  10397. f.SetCellValue(sheetName, cell, sort)
  10398. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10399. cell = fmt.Sprintf("D%d", num)
  10400. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  10401. f.SetCellValue(sheetName, cell, lweight)
  10402. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10403. cell = fmt.Sprintf("E%d", num)
  10404. if _, ok := planExec["actualweightminus"]; ok {
  10405. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  10406. f.SetCellValue(sheetName, cell, actualweightminus)
  10407. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10408. } else {
  10409. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  10410. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10411. }
  10412. cell = fmt.Sprintf("F%d", num)
  10413. f.SetCellValue(sheetName, cell, planExec["fname"])
  10414. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10415. cell = fmt.Sprintf("G%d", num)
  10416. if _, ok := planExec["diff"]; ok {
  10417. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  10418. f.SetCellValue(sheetName, cell, diff)
  10419. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10420. } else {
  10421. f.SetCellValue(sheetName, cell, planExec["diff"])
  10422. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10423. }
  10424. cell = fmt.Sprintf("H%d", num)
  10425. if _, ok := planExec["diffRate"]; ok {
  10426. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  10427. f.SetCellValue(sheetName, cell, diffRate)
  10428. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10429. } else {
  10430. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  10431. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10432. }
  10433. cell = fmt.Sprintf("I%d", num)
  10434. f.SetCellValue(sheetName, cell, planExec["intime"])
  10435. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10436. cell = fmt.Sprintf("J%d", num)
  10437. if _, ok := planExec["lastactualweight"]; ok {
  10438. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  10439. f.SetCellValue(sheetName, cell, lastactualweight)
  10440. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10441. } else {
  10442. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  10443. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10444. }
  10445. cell = fmt.Sprintf("K%d", num)
  10446. if _, ok := planExec["actualweight"]; ok {
  10447. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  10448. f.SetCellValue(sheetName, cell, actualweight)
  10449. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10450. } else {
  10451. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  10452. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10453. }
  10454. num += 1
  10455. }
  10456. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10457. for i, header := range headers2 {
  10458. cell := "%" + fmt.Sprintf("c%d", num)
  10459. cell = fmt.Sprintf(cell, 'C'+i)
  10460. f.SetCellValue(sheetName, cell, header)
  10461. f.SetCellStyle(sheetName, cell, cell, styleID)
  10462. maxWidth := len(header)
  10463. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  10464. }
  10465. num += 1
  10466. for _, plan2 := range plan2Map[plan["id"]] {
  10467. var currentStyleID int
  10468. if plan2["abnormal"] == "1" {
  10469. currentStyleID = redStyleID
  10470. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, plan2["abnormal"]) // 调试
  10471. } else {
  10472. currentStyleID = styleID
  10473. }
  10474. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10475. sort, _ := strconv.Atoi(plan2["sort"])
  10476. f.SetCellValue(sheetName, cell, sort)
  10477. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10478. cell = fmt.Sprintf("D%d", num)
  10479. f.SetCellValue(sheetName, cell, plan2["fname"])
  10480. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10481. cell = fmt.Sprintf("E%d", num)
  10482. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  10483. f.SetCellValue(sheetName, cell, lweight)
  10484. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10485. cell = fmt.Sprintf("F%d", num)
  10486. if _, ok := plan2["actualweightminus"]; ok {
  10487. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  10488. f.SetCellValue(sheetName, cell, actualweightminus)
  10489. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10490. } else {
  10491. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  10492. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10493. }
  10494. cell = fmt.Sprintf("G%d", num)
  10495. if _, ok := plan2["diff"]; ok {
  10496. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  10497. f.SetCellValue(sheetName, cell, diff)
  10498. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10499. } else {
  10500. f.SetCellValue(sheetName, cell, plan2["diff"])
  10501. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10502. }
  10503. cell = fmt.Sprintf("H%d", num)
  10504. if _, ok := plan2["diffRate"]; ok {
  10505. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  10506. f.SetCellValue(sheetName, cell, diffRate)
  10507. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10508. } else {
  10509. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  10510. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10511. }
  10512. cell = fmt.Sprintf("I%d", num)
  10513. f.SetCellValue(sheetName, cell, plan2["intime"])
  10514. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10515. cell = fmt.Sprintf("J%d", num)
  10516. if _, ok := plan2["lastactualweight"]; ok {
  10517. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  10518. f.SetCellValue(sheetName, cell, lastactualweight)
  10519. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10520. } else {
  10521. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  10522. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10523. }
  10524. cell = fmt.Sprintf("K%d", num)
  10525. if _, ok := plan2["lastactualweight"]; ok {
  10526. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  10527. f.SetCellValue(sheetName, cell, actualweight)
  10528. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10529. } else {
  10530. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  10531. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10532. }
  10533. num += 1
  10534. }
  10535. num += 1
  10536. notBorder = append(notBorder, num)
  10537. }
  10538. // for i := 2; i < num; i++ {
  10539. // exist := false
  10540. // for _, n := range notBorder {
  10541. // if i+1 == n {
  10542. // exist = true
  10543. // break
  10544. // }
  10545. // }
  10546. // if !exist {
  10547. // // 为 A-K 列设置边框
  10548. // for col := 'A'; col <= 'K'; col++ {
  10549. // cellName := fmt.Sprintf("%c%d", col, i)
  10550. // style, _ := f.NewStyle(&excelizexuri.Style{
  10551. // // Border: border,
  10552. // Alignment: &excelizexuri.Alignment{
  10553. // Vertical: "center",
  10554. // Horizontal: "center",
  10555. // ShrinkToFit: true,
  10556. // WrapText: true,
  10557. // },
  10558. // })
  10559. // f.SetCellStyle(sheetName, cellName, cellName, style)
  10560. // }
  10561. // }
  10562. // }
  10563. for col := 'A'; col <= 'K'; col++ {
  10564. colName := string(col)
  10565. switch colName {
  10566. case "A", "B": // 牧场名称、TMR列
  10567. f.SetColWidth(sheetName, colName, colName, 10)
  10568. case "C": // 操作编号列
  10569. f.SetColWidth(sheetName, colName, colName, 10)
  10570. case "D", "E": // 计划重量、实际重量列
  10571. f.SetColWidth(sheetName, colName, colName, 12)
  10572. case "F": // 代表成分/投料位置列
  10573. f.SetColWidth(sheetName, colName, colName, 20)
  10574. case "G", "H": // 误差数、准确率列
  10575. f.SetColWidth(sheetName, colName, colName, 12)
  10576. case "I": // 完成时间列
  10577. f.SetColWidth(sheetName, colName, colName, 15)
  10578. case "J", "K": // 起始读数重量、完成读数重量列
  10579. f.SetColWidth(sheetName, colName, colName, 15)
  10580. }
  10581. }
  10582. // 设置响应头
  10583. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10584. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10585. c.Header("Content-Transfer-Encoding", "binary")
  10586. // 写入 Excel 文件到响应
  10587. if err := f.Write(c.Writer); err != nil {
  10588. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10589. return
  10590. }
  10591. }
  10592. func RestartMqtt(c *gin.Context) {
  10593. appG := app.Gin{C: c}
  10594. // 发送 GET 请求到 MQTT 重启接口
  10595. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10596. if err != nil {
  10597. logging.Error("RestartMqtt request failed:", err)
  10598. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10599. return
  10600. }
  10601. defer resp.Body.Close()
  10602. // 读取响应内容f
  10603. body, err := ioutil.ReadAll(resp.Body)
  10604. if err != nil {
  10605. logging.Error("RestartMqtt read response failed:", err)
  10606. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10607. return
  10608. }
  10609. // 检查响应状态码
  10610. if resp.StatusCode != http.StatusOK {
  10611. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10612. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10613. return
  10614. }
  10615. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10616. }
  10617. func FpdBatchEditByWeight(c *gin.Context) {
  10618. appG := app.Gin{C: c}
  10619. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10620. fsions := gofasion.NewFasion(string(dataByte))
  10621. barList := fsions.Get("barList").Array()
  10622. pastureid := fsions.Get("pastureId").ValueStr()
  10623. tx := restful.Engine.NewSession()
  10624. defer tx.Close()
  10625. 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
  10626. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10627. if err != nil {
  10628. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10629. return
  10630. }
  10631. for _, barFsions := range barList {
  10632. dataexcel := make(map[string]interface{}, 0)
  10633. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10634. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10635. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10636. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10637. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10638. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10639. continue
  10640. }
  10641. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10642. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10643. // if err != nil {
  10644. // logs.Error(err)
  10645. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10646. // return
  10647. // }
  10648. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10649. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10650. // if err != nil {
  10651. // logs.Error(err)
  10652. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10653. // return
  10654. // }
  10655. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10656. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10657. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10658. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10659. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10660. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10661. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10662. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10663. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10664. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10665. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10666. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10667. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10668. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10669. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10670. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10671. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10672. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10673. if err != nil {
  10674. logs.Error(err)
  10675. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10676. return
  10677. }
  10678. if !ftexist {
  10679. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10680. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10681. if err != nil {
  10682. logs.Error(err)
  10683. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10684. return
  10685. }
  10686. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10687. if err != nil {
  10688. logs.Error(err)
  10689. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10690. return
  10691. }
  10692. }
  10693. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10694. if err != nil {
  10695. logs.Error(err)
  10696. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10697. return
  10698. }
  10699. if !exist {
  10700. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10701. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10702. if err != nil {
  10703. logs.Error(err)
  10704. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10705. return
  10706. }
  10707. }
  10708. var feedpargs []interface{}
  10709. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10710. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10711. if _, ok := dataexcel["ftname"]; ok {
  10712. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10713. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10714. // upFeedpSql += `,ftweight = ? `
  10715. // feedpargs = append(feedpargs, weight)
  10716. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10717. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10718. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10719. } else {
  10720. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10721. }
  10722. // if _, ok := dataexcel["ptsfname"]; ok {
  10723. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10724. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10725. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10726. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10727. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10728. // } else {
  10729. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10730. // }
  10731. upFeedpSql += " where barname = ? and pastureid = ? "
  10732. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10733. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10734. if err != nil {
  10735. logs.Error(err)
  10736. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10737. return
  10738. }
  10739. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10740. if err != nil {
  10741. logs.Error(err)
  10742. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10743. return
  10744. }
  10745. if !exist1 {
  10746. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10747. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10748. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10749. if err != nil {
  10750. logs.Error(err)
  10751. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10752. return
  10753. }
  10754. }
  10755. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10756. if err != nil {
  10757. logs.Error(err)
  10758. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10759. return
  10760. }
  10761. if !exist2 {
  10762. _, 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) `,
  10763. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10764. if err != nil {
  10765. logs.Error(err)
  10766. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10767. return
  10768. }
  10769. }
  10770. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10771. if err != nil {
  10772. logs.Error(err)
  10773. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10774. return
  10775. }
  10776. if !exist3 {
  10777. _, 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) `,
  10778. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10779. if err != nil {
  10780. logs.Error(err)
  10781. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10782. return
  10783. }
  10784. }
  10785. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10786. if err != nil {
  10787. logs.Error(err)
  10788. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10789. return
  10790. }
  10791. if !exist4 {
  10792. _, 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) `,
  10793. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10794. if err != nil {
  10795. logs.Error(err)
  10796. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10797. return
  10798. }
  10799. }
  10800. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  10801. if err != nil {
  10802. logs.Error(err)
  10803. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10804. return
  10805. }
  10806. if !exist5 {
  10807. _, 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) `,
  10808. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10809. if err != nil {
  10810. logs.Error(err)
  10811. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10812. return
  10813. }
  10814. }
  10815. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  10816. if err != nil {
  10817. logs.Error(err)
  10818. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10819. return
  10820. }
  10821. if !exist6 {
  10822. _, 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) `,
  10823. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10824. if err != nil {
  10825. logs.Error(err)
  10826. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10827. return
  10828. }
  10829. }
  10830. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10831. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10832. and pastureid = ? and times = ?`
  10833. var fpdargs1 []interface{}
  10834. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10835. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10836. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10837. if err != nil {
  10838. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10839. return
  10840. }
  10841. var fpdargs2 []interface{}
  10842. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10843. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10844. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10845. if err != nil {
  10846. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10847. return
  10848. }
  10849. var fpdargs3 []interface{}
  10850. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10851. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10852. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10853. if err != nil {
  10854. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10855. return
  10856. }
  10857. var fpdargs4 []interface{}
  10858. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10859. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10860. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10861. if err != nil {
  10862. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10863. return
  10864. }
  10865. var fpdargs5 []interface{}
  10866. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10867. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10868. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10869. if err != nil {
  10870. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10871. return
  10872. }
  10873. var fpdargs6 []interface{}
  10874. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10875. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10876. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10877. if err != nil {
  10878. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10879. return
  10880. }
  10881. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10882. 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()
  10883. if err != nil {
  10884. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10885. return
  10886. }
  10887. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10888. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10889. upFpdetailList := make([]*upFpdetail, 0)
  10890. for _, newfpd := range newList {
  10891. for _, oldfpd := range oldFpdList {
  10892. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10893. var oldweight, newweight float64
  10894. if oldfpd["weight"] != nil {
  10895. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10896. }
  10897. if newfpd["weight"] != nil {
  10898. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10899. }
  10900. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10901. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10902. Old: oldweight,
  10903. New: newweight,
  10904. Times: newfpd["times"].(int64),
  10905. Ptid: newfpd["ptid"].(int64),
  10906. Fweight: fweight,
  10907. Id: oldfpd["id"].(int64),
  10908. })
  10909. break
  10910. }
  10911. }
  10912. }
  10913. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10914. }
  10915. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10916. }
  10917. func FtImportExcel(c *gin.Context) {
  10918. appG := app.Gin{C: c}
  10919. inputdata := ""
  10920. c.Request.ParseForm()
  10921. params := c.Request.Form
  10922. file, _, err := c.Request.FormFile("file")
  10923. if err != nil {
  10924. appG.Response(http.StatusOK, e.ERROR, err)
  10925. return
  10926. }
  10927. sqlnamestrs := params.Get("name")
  10928. sheetname := params.Get("sheetname")
  10929. pastureid := params.Get("pastureid")
  10930. //importParams := params.Get("importParams")
  10931. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10932. // 必输项参数 (字符串格式 "field1,field2,field3")
  10933. requiredParams := params.Get("requiredParams")
  10934. // 日期参数
  10935. dateParams := params.Get("dateParams")
  10936. // 数字参数
  10937. numParams := params.Get("numParams")
  10938. //将字符串分割开
  10939. dateParamslist := strings.Split(dateParams, ",")
  10940. requiredParamslist := strings.Split(requiredParams, ",")
  10941. numParamslist := strings.Split(numParams, ",")
  10942. queryData := make([]interface{}, 0)
  10943. sqlslist := strings.Split(sqlnamestrs, ",")
  10944. xlsx1, err := excelize.OpenReader(file)
  10945. if err != nil {
  10946. fmt.Println(err)
  10947. return
  10948. }
  10949. ok := 0
  10950. error := 0
  10951. isdone := true
  10952. rows := xlsx1.GetRows(sheetname)
  10953. // 限制10000条,多余的截取掉
  10954. if len(rows) > 10000 {
  10955. rows = rows[:10000]
  10956. }
  10957. tx := restful.Engine.NewSession()
  10958. ftNameList := make(map[string]interface{})
  10959. var ftNames []interface{}
  10960. for i, row := range rows {
  10961. if i > 0 {
  10962. entry := make(map[string]interface{})
  10963. outentry := make(map[string]interface{})
  10964. for j, colCell := range rows[0] {
  10965. for k, colCell1 := range row {
  10966. if j == k {
  10967. outentry[colCell] = colCell1
  10968. entry[colCell] = colCell1
  10969. }
  10970. }
  10971. }
  10972. inputdata = ""
  10973. a := ""
  10974. fmt.Println(outentry, entry)
  10975. //校验日期格式
  10976. for _, v := range dateParamslist {
  10977. if v == "" {
  10978. continue
  10979. }
  10980. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10981. dtime, err := TransfTime(d.(string))
  10982. if err != nil {
  10983. a = strings.Trim(v, " ")
  10984. break
  10985. }
  10986. outentry[strings.Trim(v, " ")] = dtime
  10987. }
  10988. }
  10989. if a != "" {
  10990. outentry["error_msg"] = a + " 格式错误"
  10991. error++
  10992. queryData = append(queryData, outentry)
  10993. continue
  10994. }
  10995. a = ""
  10996. //校验必填格式
  10997. for _, v := range requiredParamslist {
  10998. if v == "" {
  10999. continue
  11000. }
  11001. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  11002. a = strings.Trim(v, " ")
  11003. break
  11004. }
  11005. }
  11006. if a != "" {
  11007. outentry["error_msg"] = a + " 未填或格式错误"
  11008. error++
  11009. queryData = append(queryData, outentry)
  11010. continue
  11011. }
  11012. a = ""
  11013. //校验数字格式
  11014. for _, v := range numParamslist {
  11015. if v == "" {
  11016. continue
  11017. }
  11018. d, ok := outentry[strings.Trim(v, " ")]
  11019. if !ok || d == "" {
  11020. outentry[strings.Trim(v, " ")] = 0
  11021. } else {
  11022. var fl float64
  11023. switch d.(type) {
  11024. case string:
  11025. fl, err = strconv.ParseFloat(d.(string), 64)
  11026. }
  11027. if err != nil || fl < 0 {
  11028. a = strings.Trim(v, " ")
  11029. break
  11030. }
  11031. }
  11032. }
  11033. if a != "" {
  11034. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  11035. error++
  11036. queryData = append(queryData, outentry)
  11037. continue
  11038. }
  11039. err := tx.Begin()
  11040. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  11041. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  11042. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  11043. }
  11044. for _, sqlnamestr := range sqlslist {
  11045. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  11046. paramslist := strings.Split(paramslists, ",")
  11047. if len(paramslist) > 0 {
  11048. s_params := make([]interface{}, 0)
  11049. for _, value := range paramslist {
  11050. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  11051. if tempv, exists := c.Get("jwt_username"); exists {
  11052. s_params = append(s_params, tempv.(string))
  11053. } else {
  11054. s_params = append(s_params, "")
  11055. }
  11056. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  11057. s_params = append(s_params, pastureid)
  11058. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  11059. ids, err := setting.SnowIds.NextId()
  11060. if err != nil {
  11061. ids = time.Now().UnixNano()
  11062. logging.Info("create SnowIds err", err)
  11063. }
  11064. s_params = append(s_params, ids)
  11065. } else {
  11066. if outentry[strings.Trim(value, " ")] == nil {
  11067. s_params = append(s_params, "")
  11068. } else {
  11069. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  11070. }
  11071. }
  11072. }
  11073. outentry["input"] = inputdata
  11074. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  11075. if err != nil {
  11076. if tx != nil {
  11077. tx.Rollback()
  11078. }
  11079. if tx != nil {
  11080. tx.Close()
  11081. }
  11082. msg := geterrmsg(err.Error())
  11083. outentry["error_msg"] = msg
  11084. error++
  11085. queryData = append(queryData, outentry)
  11086. isdone = true
  11087. break
  11088. } else {
  11089. if len(returnmsgmap1) > 0 {
  11090. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  11091. if tx != nil {
  11092. tx.Rollback()
  11093. }
  11094. if tx != nil {
  11095. tx.Close()
  11096. }
  11097. msg := geterrmsg(va.(string))
  11098. outentry["error_msg"] = msg
  11099. error++
  11100. queryData = append(queryData, outentry)
  11101. isdone = true
  11102. break
  11103. }
  11104. }
  11105. isdone = false
  11106. }
  11107. }
  11108. }
  11109. ftNames = append(ftNames, outentry["配方名称"])
  11110. switch {
  11111. case err != nil:
  11112. if tx != nil {
  11113. tx.Rollback()
  11114. }
  11115. default:
  11116. if tx != nil {
  11117. err = tx.Commit()
  11118. }
  11119. }
  11120. if tx != nil {
  11121. tx.Close()
  11122. }
  11123. }
  11124. if !isdone {
  11125. ok++
  11126. isdone = true
  11127. }
  11128. }
  11129. go ftSync(ftNames, pastureid)
  11130. data := make(map[string]interface{})
  11131. data["result"] = queryData
  11132. data["success"] = ok
  11133. data["err_count"] = error
  11134. appG.Response(http.StatusOK, e.SUCCESS, data)
  11135. }
  11136. func ftSync(ftNameList []interface{}, pastureId string) {
  11137. tx := restful.Engine.NewSession()
  11138. defer tx.Close()
  11139. for _, ftName := range ftNameList {
  11140. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  11141. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  11142. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  11143. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  11144. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  11145. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  11146. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  11147. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  11148. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, ftName).QueryString()
  11149. FpdBatchEditGrfd(pastureId, values1)
  11150. }
  11151. }
  11152. func CopyFeedtemplet(c *gin.Context) {
  11153. appG := app.Gin{C: c}
  11154. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11155. fsion := gofasion.NewFasion(string(dataByte))
  11156. pastureid := fsion.Get("pastureid").ValueStr()
  11157. newName := fsion.Get("newName").ValueStr()
  11158. id := fsion.Get("id").ValueStr()
  11159. tx := restful.Engine.NewSession()
  11160. defer tx.Close()
  11161. count, err := tx.SQL(` select count(1) from feedtemplet where tname = ? `, newName).Count()
  11162. if err != nil {
  11163. appG.Response(http.StatusOK, e.ERROR, err)
  11164. return
  11165. }
  11166. if count > 0 {
  11167. appG.Response(http.StatusOK, e.ERROR, "配方名称重复!")
  11168. return
  11169. }
  11170. type ftCode struct {
  11171. Tcode string `xorm:"tcode"`
  11172. }
  11173. code := new(ftCode)
  11174. err = tx.SQL(`select if(left((select max(tcode) from feedtemplet where pastureid = ?),8) =
  11175. (select DATE_FORMAT(now(),"%Y%m%d")),(select max(tcode)+1 from feedtemplet where pastureid = ?),
  11176. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))) tcode`, pastureid, pastureid).GetFirst(code).Error
  11177. if err != nil {
  11178. appG.Response(http.StatusOK, e.ERROR, err)
  11179. return
  11180. }
  11181. if code.Tcode == "" {
  11182. appG.Response(http.StatusOK, e.ERROR, "配方编码生产失败!")
  11183. return
  11184. }
  11185. _, err = tx.Exec(`INSERT INTO feedtemplet(pastureid,tname,tcode,tcolor,ccid,ccname,fttype,fttypeid,source,
  11186. remark,enable,sort,volume,autozone)
  11187. select pastureid,?,?,tcolor,ccid,ccname,fttype,fttypeid,source,
  11188. remark,enable,sort,volume,autozone from feedtemplet where id = ? `, newName, code.Tcode, id)
  11189. if err != nil {
  11190. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11191. return
  11192. }
  11193. _, err = tx.Exec(`insert into ftdetail(pastureid,ftid,fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11194. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry)
  11195. select pastureid,(select id from feedtemplet where tcode = ? ),fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11196. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry
  11197. from ftdetail where ftid = ? `, code.Tcode, id)
  11198. if err != nil {
  11199. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11200. return
  11201. }
  11202. appG.Response(http.StatusOK, e.SUCCESS, true)
  11203. }
  11204. func Test(c *gin.Context) {
  11205. appG := app.Gin{C: c}
  11206. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11207. appG.Response(http.StatusOK, e.SUCCESS, string(dataByte))
  11208. }
  11209. func GetPlanDry(c *gin.Context) {
  11210. appG := app.Gin{C: c}
  11211. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11212. fsion := gofasion.NewFasion(string(dataByte))
  11213. date := fsion.Get("date").ValueStr()
  11214. tx := restful.Engine.NewSession()
  11215. defer tx.Close()
  11216. dataList, err := tx.SQL(`SELECT
  11217. t.feedtempletName,
  11218. ifnull(t.feedtempletPrice,0)feedtempletPrice,
  11219. ifnull(t.feedtempletWeight,0)feedtempletWeight,
  11220. ifnull(t.feedtempletDryWeight,0)feedtempletDryWeight,
  11221. t.tmrno,
  11222. t.bname,
  11223. t.barid,
  11224. t.dry,
  11225. t.actualweightminus,
  11226. t.mydate,
  11227. t.pasturename,
  11228. t.endDate,
  11229. t.startDate,
  11230. t.times,
  11231. -- 计算startDate和endDate的中间时间
  11232. ifnull(DATE_FORMAT(
  11233. DATE_ADD(
  11234. t.startDate,
  11235. INTERVAL TIMESTAMPDIFF(SECOND, t.startDate, t.endDate)/2 SECOND
  11236. ),
  11237. '%Y-%m-%d %H:%i:%s'
  11238. ),'') AS midTime
  11239. FROM (
  11240. SELECT
  11241. (SELECT sort FROM downloadedplan WHERE pid = d.pid AND mydate = d.mydate AND lpplantype IN (0,1)) tmrno,
  11242. b.bname,
  11243. b.id barid,
  11244. 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
  11245. JOIN downloadplandtl1 dd1 ON dd.id = dd1.pid
  11246. JOIN feednur fn ON fn.fid = dd1.fid
  11247. WHERE dd.pid = d.pid AND dd.mydate = d.mydate AND lpplantype IN (0,1,4))/100),2) dry,
  11248. 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,
  11249. DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate,
  11250. p.pasture_name pastureName,
  11251. DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endDate,
  11252. DATE_FORMAT(IFNULL(
  11253. (SELECT MAX(intime) FROM downloadplandtl2 d1
  11254. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d1.intime<d2.intime),
  11255. (SELECT MAX(intime) FROM downloadplandtl1_exec de
  11256. WHERE de.date=d2.date AND de.pastureid = d2.pastureid AND de.pid=d2.pid)
  11257. ), '%Y-%m-%d %H:%i:%s') startDate,
  11258. d.times ,
  11259. ( SELECT
  11260. round(SUM(
  11261. IF(ftd.preftid<>0,
  11262. ftd.fweight*IFNULL((SELECT SUM(ftd1.fweight*f1.dry/100)/SUM(ftd1.fweight) FROM ftdetaildate ftd1
  11263. JOIN feednur f1 ON f1.fid= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11264. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11265. ftd.fweight*f.dry/100)) ,2)
  11266. dryweight
  11267. FROM ftdetaildate ftd
  11268. LEFT JOIN feednur f ON f.fid= ftd.fid AND f.pastureid = ftd.pastureid
  11269. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletDryWeight,(
  11270. select
  11271. sum(ftd.fweight)
  11272. FROM ftdetaildate ftd
  11273. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletWeight,
  11274. ( SELECT
  11275. round(SUM(
  11276. IF(ftd.preftid<>0,
  11277. IFNULL((SELECT SUM(ftd1.fweight*f1.uprice) FROM ftdetaildate ftd1
  11278. JOIN feed f1 ON f1.id= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11279. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11280. ftd.fweight*f.uprice)) ,2)
  11281. dryweight
  11282. FROM ftdetaildate ftd
  11283. LEFT JOIN feed f ON f.id= ftd.fid AND f.pastureid = ftd.pastureid
  11284. WHERE ftd.ftid = d.tempid and ftd.date = d2.date )
  11285. feedtempletPrice,d.templetname feedtempletName
  11286. FROM downloadedplan d
  11287. JOIN downloadplandtl2 d2 ON d.id=d2.PID
  11288. JOIN bar b ON b.id = d2.fbarid
  11289. JOIN pasture p ON p.pastureid = d.pastureid
  11290. WHERE d.mydate = DATE_FORMAT(?,'%Y-%m-%d')
  11291. AND d2.type = 0
  11292. AND d.havebutton = 1
  11293. ) t
  11294. WHERE 1=1 `, date).QueryString()
  11295. if err != nil {
  11296. logs.Error(err)
  11297. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11298. return
  11299. }
  11300. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11301. }
  11302. func GetBar(c *gin.Context) {
  11303. appG := app.Gin{C: c}
  11304. tx := restful.Engine.NewSession()
  11305. defer tx.Close()
  11306. pastureinfo := new(udPastureInfo)
  11307. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  11308. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  11309. if err != nil {
  11310. logs.Error(err)
  11311. return
  11312. }
  11313. dataList, err := tx.SQL(` select id,bname from bar where pastureid = ?`, pastureinfo.Pastureid).QueryString()
  11314. if err != nil {
  11315. logs.Error(err)
  11316. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11317. return
  11318. }
  11319. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11320. }
  11321. func GetHomepage(c *gin.Context) {
  11322. appG := app.Gin{C: c}
  11323. tx := restful.Engine.NewSession()
  11324. defer tx.Close()
  11325. dataList, err := tx.SQL(` SELECT
  11326. ifnull((SELECT CONCAT(ROUND(if(SUM(lweight) <= SUM(iweight),SUM(lweight)/SUM(iweight),SUM(iweight)/SUM(lweight))*100,2),'%') yesRateHL
  11327. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11328. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) ),'0.00%')yesRateHL, -- 昨日混料准确率
  11329. (SELECT CONCAT(ROUND(SUM(iweight)/SUM(lweight)*100,2),'%') yesRateHL
  11330. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11331. 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日混料准确率
  11332. ifnull((SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11333. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11334. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) ),'0.00%')yesRateSL, -- 昨日撒料准确率
  11335. (SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11336. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11337. 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日撒料准确率
  11338. 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),'%') -- 正确率
  11339. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11340. WHERE dt.pastureid = d.pastureid AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')),'0.00%') yesRateSLR, -- 昨日正确率
  11341. (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),'%') -- 正确率
  11342. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11343. WHERE dt.pastureid = d.pastureid
  11344. 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日正确率
  11345. (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,
  11346. (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,
  11347. 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,
  11348. 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,
  11349. ifnull(round(getSLtimeDiffSINGEL(d.pastureid,d.mydate),2),0.00) temtime,
  11350. ifnull(round(getSLtimeDiffMonth(d.pastureid) ,2),0.00) montime
  11351. FROM
  11352. (SELECT (select column_default as pastureid from information_schema.COLUMNS
  11353. 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()
  11354. if err != nil {
  11355. logs.Error(err)
  11356. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11357. return
  11358. }
  11359. dataList1, err := tx.SQL(`select
  11360. 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
  11361. LEFT JOIN ftdetail ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1'
  11362. join feed f on f.id = ifnull(ftd.fid,d1.fid) where d1.date = date_format(now(),'%Y-%m-%d') `).QueryString()
  11363. if err != nil {
  11364. logs.Error(err)
  11365. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11366. return
  11367. }
  11368. for _, data := range dataList {
  11369. for _, data1 := range dataList1 {
  11370. data["totalCost"] = data1["totalCost"]
  11371. data["cost"] = data1["cost"]
  11372. }
  11373. }
  11374. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11375. }
  11376. func GetFeedingManagement(c *gin.Context) {
  11377. appG := app.Gin{C: c}
  11378. typea := c.Query("typea") // 0 栏舍 1 日期
  11379. startDate := c.Query("startdate")
  11380. endDate := c.Query("enddate")
  11381. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11382. // fsion := gofasion.NewFasion(string(dataByte))
  11383. tx := restful.Engine.NewSession()
  11384. defer tx.Close()
  11385. if typea == "0" {
  11386. 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
  11387. SUM(
  11388. 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 ,
  11389. 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)*
  11390. 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 )),
  11391. 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)*
  11392. 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 ))
  11393. )
  11394. )actualweightminus ,
  11395. SUM(
  11396. 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 ,
  11397. 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)*
  11398. 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 )),
  11399. 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)*
  11400. 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 ))
  11401. ) * ifnull(fn.dry,0)
  11402. ) dryweight , SUM(
  11403. 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 ,
  11404. 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)*
  11405. 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 )),
  11406. 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)*
  11407. 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 ))
  11408. ) * ifnull(f.uprice,0)
  11409. ) priceweight
  11410. ,(select ccount from feedpdate where date = d1.date and barid = d2.fbarid) ccount,b.bname
  11411. FROM
  11412. downloadedplan d
  11413. JOIN downloadplandtl2 d2
  11414. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11415. JOIN downloadplandtl1 d1
  11416. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11417. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11418. 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
  11419. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11420. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11421. left join feednur fn on fn.fid = f.id
  11422. WHERE d.mydate BETWEEN ? AND ? GROUP BY d2.fbarid ) t `, startDate, endDate).QueryString()
  11423. if err != nil {
  11424. logs.Error(err)
  11425. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11426. return
  11427. }
  11428. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11429. } else {
  11430. 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
  11431. SUM(
  11432. 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 ,
  11433. 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)*
  11434. 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 )),
  11435. 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)*
  11436. 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 ))
  11437. )
  11438. )actualweightminus ,
  11439. SUM(
  11440. 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 ,
  11441. 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)*
  11442. 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 )),
  11443. 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)*
  11444. 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 ))
  11445. ) * ifnull(fn.dry,0)
  11446. ) dryweight , SUM(
  11447. 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 ,
  11448. 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)*
  11449. 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 )),
  11450. 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)*
  11451. 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 ))
  11452. ) * ifnull(f.uprice,0)
  11453. ) priceweight
  11454. ,(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
  11455. FROM
  11456. downloadedplan d
  11457. JOIN downloadplandtl2 d2
  11458. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11459. JOIN downloadplandtl1 d1
  11460. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11461. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11462. 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
  11463. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11464. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11465. left join feednur fn on fn.fid = f.id
  11466. WHERE d.mydate BETWEEN ? AND ?
  11467. GROUP BY d.mydate) t `, startDate, endDate).QueryString()
  11468. if err != nil {
  11469. logs.Error(err)
  11470. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11471. return
  11472. }
  11473. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11474. }
  11475. }
  11476. func GetFpdetailFname(c *gin.Context) {
  11477. appG := app.Gin{C: c}
  11478. // id := c.Query("id")
  11479. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11480. fsion := gofasion.NewFasion(string(dataByte))
  11481. id := fsion.Get("id").ValueDefaultStr("")
  11482. tx := restful.Engine.NewSession()
  11483. defer tx.Close()
  11484. fpdetailFnameList := make([]*models.FpdetailFname, 0)
  11485. err := tx.SQL(` SELECT
  11486. TRIM(ftid)ftid,TRIM(fid)fid,
  11487. IFNULL((SELECT fname FROM feed WHERE pastureid =ftdetail.pastureid AND id = ftdetail.fid),ftdetail. fname) fname,
  11488. fweight,sort,
  11489. TRIM(ftdetail.id) id, fweight /(select sum(fweight) from ftdetail where ftid = (select ftid from feedp where barid = ? ) ) sumFweight
  11490. FROM
  11491. ftdetail
  11492. WHERE ( ftid=(select ftid from feedp where barid = ? )) AND is_show = 1
  11493. ORDER BY ftdetail.sort,ftdetail.id `, id, id).Find(&fpdetailFnameList)
  11494. if err != nil {
  11495. logs.Error(err)
  11496. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11497. return
  11498. }
  11499. fpdetailList := make([]*models.Fpdetail, 0)
  11500. err = tx.SQL(`select id,barid,barname,times,weight from fpdetail where barid = ?`, id).Find(&fpdetailList)
  11501. if err != nil {
  11502. logs.Error(err)
  11503. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11504. return
  11505. }
  11506. for _, f := range fpdetailFnameList {
  11507. f.FWeight = 0
  11508. for _, fpd := range fpdetailList {
  11509. value := f.SumFWeight * fpd.Weight
  11510. // 将其四舍五入到小数点后两位
  11511. roundedValue := math.Round(value*100) / 100
  11512. if fpd.Times == 1 {
  11513. f.TimesOne = roundedValue
  11514. } else if fpd.Times == 2 {
  11515. f.TimesTwo = roundedValue
  11516. } else if fpd.Times == 3 {
  11517. f.TimesThree = roundedValue
  11518. } else if fpd.Times == 4 {
  11519. f.TimesFour = roundedValue
  11520. } else if fpd.Times == 5 {
  11521. f.TimesFive = roundedValue
  11522. } else if fpd.Times == 6 {
  11523. f.TimesSix = roundedValue
  11524. }
  11525. f.FWeight += value
  11526. }
  11527. }
  11528. fpdetailFname := new(models.FpdetailFname)
  11529. fpdetailFname.FName = "合计"
  11530. for _, f := range fpdetailFnameList {
  11531. fpdetailFname.TimesOne += f.TimesOne
  11532. fpdetailFname.TimesTwo += f.TimesTwo
  11533. fpdetailFname.TimesThree += f.TimesThree
  11534. fpdetailFname.TimesFour += f.TimesFour
  11535. fpdetailFname.TimesFive += f.TimesFive
  11536. fpdetailFname.TimesSix += f.TimesSix
  11537. fpdetailFname.FWeight += f.FWeight
  11538. f.FWeight = RoundFloat(f.FWeight, 2)
  11539. }
  11540. // 在处理代码中
  11541. fpdetailFname.TimesOne = RoundFloat(fpdetailFname.TimesOne, 2)
  11542. fpdetailFname.TimesTwo = RoundFloat(fpdetailFname.TimesTwo, 2)
  11543. fpdetailFname.TimesThree = RoundFloat(fpdetailFname.TimesThree, 2)
  11544. fpdetailFname.TimesFour = RoundFloat(fpdetailFname.TimesFour, 2)
  11545. fpdetailFname.TimesFive = RoundFloat(fpdetailFname.TimesFive, 2)
  11546. fpdetailFname.TimesSix = RoundFloat(fpdetailFname.TimesSix, 2)
  11547. fpdetailFname.FWeight = RoundFloat(fpdetailFname.FWeight, 2)
  11548. fpdetailFnameList = append(fpdetailFnameList, fpdetailFname)
  11549. appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11550. }
  11551. func RoundFloat(x float64, prec int) float64 {
  11552. output := math.Pow(10, float64(prec))
  11553. return math.Round(x*output) / output
  11554. }
  11555. func GetLyUdData(c *gin.Context) {
  11556. appG := app.Gin{C: c}
  11557. // id := c.Query("id")
  11558. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11559. fsion := gofasion.NewFasion(string(dataByte))
  11560. myDate := fsion.Get("myDate").ValueDefaultStr("")
  11561. times := fsion.Get("Times").ValueDefaultStr("")
  11562. name := fsion.Get("name").ValueDefaultStr("")
  11563. tx := restful.Engine.NewSession()
  11564. defer tx.Close()
  11565. if name == "dateplanlist" {
  11566. data, err := tx.SQL(`select dl.id as did,if(dl.HaveButton=1,1,0) isDo, dl.id as id,dl.ProjName,dl.tmrtname TNAME, '' DNAME,DATE_FORMAT(dl.Mydate,'%Y-%m-%d') Mydate,d2.xxwTempletCode fId,dl.templetName fName, DATE_FORMAT(dl.InTime,'%Y-%m-%d %H:%i:%s') benginTime,DATE_FORMAT(max(d2.Intime),'%Y-%m-%d %H:%i:%s') endDate, dl.Times as Times, dl.Sort ,'是' Status, p.pasturecode kptCattleId from downloadedplan dl
  11567. join pasture p on dl.pastureId=p.pastureid JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId
  11568. where dl.Mydate = ? AND dl.lpplanType =0 and dl.Times= ? GROUP BY dl.id union all
  11569. select dd.id as did,if(dd.HaveButton=1,1,0) isDo, dd.id as id,dd.ProjName,dd.tmrtname TNAME, '' DNAME,DATE_FORMAT(dd.Mydate,'%Y-%m-%d') Mydate,d2.xxwTempletCode fId,dd.templetName fName, DATE_FORMAT(dd.InTime,'%Y-%m-%d %H:%i:%s') benginTime,DATE_FORMAT(max(d2.Intime),'%Y-%m-%d %H:%i:%s') endDate, dd.Times as Times, dd.Sort ,'是' Status, p.pasturecode kptCattleId
  11570. from downloadedplan dl join pasture p on dl.pastureId=p.pastureid
  11571. JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId inner join downloadedplan dd on dd.pid=dl.pid and dd.mydate=dl.mydate and dd.lpplanType=1 and dl.pastureId=dd.pastureId
  11572. where dl.Mydate = ? AND dl.lpplanType =2 and dl.Times= ?
  11573. GROUP BY dl.id order by ProjName `, myDate, times, myDate, times).Query().List()
  11574. fmt.Println(err)
  11575. appG.Response(http.StatusOK, e.SUCCESS, data)
  11576. return
  11577. } else if name == "getAddFeed" {
  11578. data, _ := tx.SQL(`SELECT IF(d.HaveButton=1,1,0) isDo,d.id did,d.ProjName ProjName,date_format(d.mydate,'%Y-%m-%d') loadDate,d.Sort tmrNo,d.Times Times,ftd.xxwTempletCode fId,ftd.tname fName,d.tmrtname TNAME,f.fname FNAME, f.xxwFeedCode feedId,d1.SORT SORT,d1.feedallowratio allowableError,(select round(sum(if(ActualWeightMinus>0,ActualWeightMinus,0)),2) from downloadplandtl1 where PID = d.id and pastureId = d.pastureId ) LWEIGHT,
  11579. round(d1.lweight,2) expWeight,round(if(d1.actualweightminus>0,d1.actualweightminus,0),2) actualWeight,'' DNAME,if((select count(1) from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc) >0 ,(select DATE_FORMAT(InTime,'%Y-%m-%d %H:%i:%s') from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc limit 1),DATE_FORMAT(d.InTime,'%Y-%m-%d %H:%i:%s') ) startTime,
  11580. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM downloadedplan dd
  11581. JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11582. inner join downloadedplan d on dd.pid=d.pid and dd.mydate=d.mydate and d.lpplanType in (0,1) AND d.pastureId = dd.pastureId
  11583. join feedtemplet ftd on ftd.id = d.tempid and ftd.pastureId = d.pastureId
  11584. JOIN feed f ON f.id = d1.fid AND f.pastureId = d.pastureId
  11585. WHERE DATE_FORMAT(dd.Mydate ,'%Y-%m-%d' ) = ? and dd.Times =? and d1.type = 0
  11586. UNION ALL SELECT IF(d.HaveButton=1,1,0) isDo,d.id did,d.ProjName ProjName,date_format(d.mydate,'%Y-%m-%d') loadDate,d.Sort tmrNo,d.Times Times,ftd.xxwTempletCode fId,ftd.tname fName,d.tmrtname TNAME,f.fname FNAME, f.xxwFeedCode feedId,d1.SORT SORT,d1.feedallowratio allowableError,(select round(sum(if(ActualWeightMinus>0,ActualWeightMinus,0)),2) from downloadplandtl1 where PID = d.id and pastureId = d.pastureId and type = 0) LWEIGHT,
  11587. round(d1.LWEIGHT *(ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and ftid = ftdd.ftid and pastureId = d.pastureId )),2) expWeight,
  11588. round((if(d1.ActualWeightMinus>0,d1.ActualWeightMinus,0)) * (ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and pastureId = d.pastureId and ftid = ftdd.ftid )),2) actualWeight,
  11589. '' DNAME ,if((select count(1) from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc) >0 ,(select DATE_FORMAT(InTime,'%Y-%m-%d %H:%i:%s') from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc limit 1),DATE_FORMAT(d.InTime,'%Y-%m-%d %H:%i:%s') ) startTime,
  11590. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM
  11591. downloadedplan dd JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11592. inner join downloadedplan d on dd.pid=d.pid and dd.mydate=d.mydate and d.lpplanType in (0,1) AND d.pastureId = dd.pastureId
  11593. join feedtemplet ftd on ftd.id = d1.fid and ftd.pastureId = d.pastureId
  11594. join ftdetaildate ftdd on ftdd.ftid = ftd.id and ftdd.date = d.Mydate and ftdd.pastureId = d.pastureId
  11595. join feed f on f.id = ftdd.fid and f.pastureId = d.pastureId
  11596. WHERE DATE_FORMAT( dd.Mydate ,'%Y-%m-%d' ) = ? AND dd.Times = ? and d1.type = 0 and d1.feedcode = -1 `, myDate, times, myDate, times).Query().List()
  11597. appG.Response(http.StatusOK, e.SUCCESS, data)
  11598. return
  11599. } else if name == "getDeleteFeed" {
  11600. data, _ := tx.SQL(`SELECT if(d.HaveButton=1,1,0) isDo,date_format(d.mydate,'%Y-%m-%d') as dropDate,d.SORT as tmrNo,d.Times as Times, d2.Fname as penName,d2.cowcount as cowCount,d.tmrtname TNAME, d2.SORT as SORT, d2.LWEIGHT as expWeight,if(d2.ActualWeightMinus>0,d2.ActualWeightMinus,0) as actualWeight,
  11601. date_format(timestamp(d2.InTime,CONCAT('-',d2.processTime)),'%Y-%m-%d %H:%i:%s') as startTime, date_format(d2.InTime,'%Y-%m-%d %H:%i:%s') as endTime,'' as DNAME ,
  11602. (select ProjName from downloadedplan dd where dd.pid=d.pid and dd.mydate=d.mydate and dd.lpplanType in (0,1) AND d.pastureId = dd.pastureId) ProjName
  11603. ,d2.xxwBarCode as penId,if(d.lpplanType=2,(select id from downloadedplan p where p.pid=d.pid and p.mydate=? and p.Times=?
  11604. and p.lpplanType=1 limit 1),d2.pid) Id from downloadedplan d LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID
  11605. and d.pastureId=d2.pastureId where d.mydate=? AND d.lpplanType in (0,2) and d.Times=?`, myDate, times, myDate, times).Query().List()
  11606. appG.Response(http.StatusOK, e.SUCCESS, data)
  11607. return
  11608. }
  11609. // appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11610. }