ops.go 458 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651
  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. tx.SQL(`update feedp fp set barname = (select bname from bar where id = fp.id ) where pastureid = ?`, parammaps["pastureid"]).Execute()
  2981. FpdBatchEditGrfd(fmt.Sprintf("%v", parammaps["pastureid"]), values1)
  2982. // 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 ,
  2983. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2984. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2985. // UNION
  2986. // 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 ,
  2987. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2988. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2989. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2990. // lpplanList := make([]*lpplanStruct, 0)
  2991. // err = tx.SQL(`select id,times,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpplan.pastureid ) = 0 ,
  2992. // ifnull((select maxstirfeed from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),100000),(select ifnull(volume,0) from tmr where id = lpplan.tmrid ) *
  2993. // (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)
  2994. // if err != nil {
  2995. // logs.Error(err, 1)
  2996. // return
  2997. // }
  2998. // lppidlist := []string{}
  2999. // for _, lpp := range lpplanList {
  3000. // lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  3001. // }
  3002. // if len(lppidlist) <= 0 {
  3003. // appG.Response(http.StatusOK, e.SUCCESS, true)
  3004. // return
  3005. // }
  3006. // lpplandtl1AllList := make([]*lpplandtl1, 0)
  3007. // err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  3008. // order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  3009. // if err != nil {
  3010. // // tx.Rollback()
  3011. // logs.Error(err, 2, parammaps["pastureid"])
  3012. // return
  3013. // }
  3014. // for _, lpp := range lpplandtl1AllList {
  3015. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  3016. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  3017. // if err != nil {
  3018. // logs.Error(err)
  3019. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3020. // return
  3021. // }
  3022. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3023. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  3024. // if err != nil {
  3025. // logs.Error(err)
  3026. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3027. // return
  3028. // }
  3029. // }
  3030. // var wg sync.WaitGroup
  3031. // for _, old := range fpdOldDataList {
  3032. // for _, fpd := range fpdDataList {
  3033. // wg.Add(1)
  3034. // go func(old, fpd map[string]interface{}) {
  3035. // updateLppandList := make([]*lpplandtl1, 0)
  3036. // defer wg.Done()
  3037. // if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3038. // fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3039. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3040. // oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3041. // // if weight > oldweight {
  3042. // // return
  3043. // // }
  3044. // var w float64
  3045. // var status int
  3046. // if weight < oldweight {
  3047. // if weight >= 0 {
  3048. // return
  3049. // }
  3050. // w = weight
  3051. // status = 0
  3052. // } else {
  3053. // if oldweight > 0 {
  3054. // return
  3055. // }
  3056. // w = weight
  3057. // status = 1
  3058. // }
  3059. // // fweight = w
  3060. // for _, lpp := range lpplanList {
  3061. // var fweight float64
  3062. // var lweight float64
  3063. // lpplandtl1List := make([]*lpplandtl1, 0)
  3064. // fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3065. // for _, lppland := range lpplandtl1AllList {
  3066. // if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3067. // lpplandtl1List = append(lpplandtl1List, lppland)
  3068. // }
  3069. // }
  3070. // if len(lpplandtl1List) == 0 {
  3071. // continue
  3072. // }
  3073. // for _, lppland := range lpplandtl1List {
  3074. // lweight += lppland.Lweight
  3075. // }
  3076. // if status == 0 {
  3077. // if lweight <= 0 {
  3078. // continue
  3079. // }
  3080. // } else {
  3081. // if lpp.Maxweight <= lweight {
  3082. // continue
  3083. // }
  3084. // }
  3085. // for _, lppland := range lpplandtl1List {
  3086. // if fpdid == lppland.Fpdid {
  3087. // if status == 1 {
  3088. // // if w <= lppland.Lweight {
  3089. // if lpp.Maxweight <= lweight {
  3090. // continue
  3091. // }
  3092. // if w+lweight <= lpp.Maxweight {
  3093. // lppland.Lweight += w
  3094. // lweight += w
  3095. // fweight += w
  3096. // w = 0
  3097. // } else {
  3098. // w = w - (lpp.Maxweight - lweight)
  3099. // n := (lpp.Maxweight - lweight)
  3100. // lppland.Lweight = lppland.Lweight + n
  3101. // lweight += n
  3102. // fweight += n
  3103. // }
  3104. // } else {
  3105. // if lppland.Lweight == 0 {
  3106. // continue
  3107. // }
  3108. // if w+lppland.Lweight >= 0 {
  3109. // lppland.Lweight = lppland.Lweight + w
  3110. // lweight = lweight + w
  3111. // fweight = fweight + w
  3112. // w = 0
  3113. // } else {
  3114. // w = w + lppland.Lweight
  3115. // lweight = lweight - lppland.Lweight
  3116. // fweight = fweight - lppland.Lweight
  3117. // lppland.Lweight = 0
  3118. // }
  3119. // }
  3120. // updateLppandList = append(updateLppandList, lppland)
  3121. // break
  3122. // }
  3123. // }
  3124. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3125. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3126. // WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3127. // if err != nil {
  3128. // // tx.Rollback()
  3129. // logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3130. // return
  3131. // }
  3132. // for _, lppland := range updateLppandList {
  3133. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3134. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3135. // if err != nil {
  3136. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3137. // // tx.Rollback()
  3138. // logs.Error(err, 3)
  3139. // return
  3140. // }
  3141. // // defer wg.Done()
  3142. // }
  3143. // updateLppandList = []*lpplandtl1{}
  3144. // if w == 0 {
  3145. // break
  3146. // }
  3147. // }
  3148. // }
  3149. // }(old, fpd)
  3150. // }
  3151. // }
  3152. // wg.Wait()
  3153. }
  3154. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3155. if err != nil {
  3156. logs.Error(err)
  3157. appG.Response(http.StatusOK, e.ERROR, false)
  3158. return
  3159. }
  3160. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3161. if err != nil {
  3162. logs.Error(err)
  3163. appG.Response(http.StatusOK, e.ERROR, false)
  3164. return
  3165. }
  3166. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3167. if err != nil {
  3168. logs.Error(err)
  3169. appG.Response(http.StatusOK, e.ERROR, false)
  3170. return
  3171. }
  3172. now := createdate
  3173. // for _, oldFpd := range oldFpdDataList {
  3174. for _, newFpd := range newFpdDataList {
  3175. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3176. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3177. // go func() {
  3178. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3179. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3180. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3181. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3182. if err != nil {
  3183. logs.Error(err)
  3184. appG.Response(http.StatusOK, e.ERROR, false)
  3185. return
  3186. }
  3187. // }()
  3188. }
  3189. // break
  3190. // }
  3191. // }
  3192. // }
  3193. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3194. for _, newLpplandtl1 := range newLpplandtl1List {
  3195. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3196. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3197. // go func() {
  3198. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3199. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3200. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3201. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3202. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3203. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3204. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3205. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3206. if err != nil {
  3207. logs.Error(err)
  3208. appG.Response(http.StatusOK, e.ERROR, false)
  3209. return
  3210. }
  3211. // }()
  3212. // }
  3213. // break
  3214. // }
  3215. // }
  3216. }
  3217. // for _, oldFeedp := range oldFeedpList {
  3218. for _, newFeedp := range newFeedpList {
  3219. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3220. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3221. // go func() {
  3222. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3223. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3224. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3225. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3226. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3227. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3228. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3229. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3230. if err != nil {
  3231. logs.Error(err)
  3232. appG.Response(http.StatusOK, e.ERROR, false)
  3233. return
  3234. }
  3235. }
  3236. // ,,parammaps["ftid"])
  3237. // surplus, surplusId, id, pastureId string
  3238. // FtdetailSurplusFt(parammaps["ftid"].)
  3239. ftList1, err := tx.SQL(` SELECT
  3240. f.id,
  3241. f.surplus surplusId,
  3242. f.pastureid,
  3243. s.surplus
  3244. FROM
  3245. feedtemplet f
  3246. JOIN surplus s ON s.id = f.surplus
  3247. WHERE
  3248. f.id = ?`, parammaps["ftid"]).QueryString()
  3249. for _, ft := range ftList1 {
  3250. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3251. }
  3252. appG.Response(http.StatusOK, e.SUCCESS, true)
  3253. }
  3254. type lpplandtlInfo struct {
  3255. Id int64 `xorm:"id"`
  3256. Pastureid int64 `xorm:"pastureid"`
  3257. Lppid int64 `xorm:"lppid"`
  3258. Barid int64 `xorm:"barid"`
  3259. Barname string `xorm:"barname"`
  3260. Fpdid int64 `xorm:"fpdid"`
  3261. Fttype int64 `xorm:"fttype"`
  3262. Lweight float64 `xorm:"lweight"`
  3263. Sort int64 `xorm:"sort"`
  3264. Tmrid int64 `xorm:"tmrid"`
  3265. Tmrname string `xorm:"tmrname"`
  3266. Cowcount int64 `xorm:"cowcount"`
  3267. Ccountradio float64 `xorm:"ccountradio"`
  3268. Background string `xorm:"background"`
  3269. Lweighthis float64 `xorm:"lweighthis"`
  3270. Maxweight float64 `xorm:"maxweight"`
  3271. }
  3272. func UpdateFpdetailBar(c *gin.Context) {
  3273. appG := app.Gin{C: c}
  3274. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3275. fsion := gofasion.NewFasion(string(dataByte))
  3276. pastureid := fsion.Get("pastureid").ValueStr()
  3277. id := fsion.Get("id").ValueStr()
  3278. tx := restful.Engine.NewSession()
  3279. tx.Begin()
  3280. 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 `,
  3281. pastureid, id).Query().List()
  3282. if err != nil {
  3283. logs.Error(err)
  3284. }
  3285. for _, fpd := range fpdList {
  3286. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3287. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3288. pastureid, fpd["id"]).Query().List()
  3289. if err != nil {
  3290. tx.Rollback()
  3291. logs.Error(err)
  3292. appG.Response(http.StatusOK, e.ERROR, false)
  3293. return
  3294. }
  3295. var lweight float64
  3296. for _, lppland := range lpplandList {
  3297. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3298. lweight += lweight1
  3299. }
  3300. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3301. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3302. if fpdweight >= ptuse && lweight == ptuse {
  3303. continue
  3304. } else {
  3305. if lweight <= fpdweight {
  3306. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3307. if err != nil {
  3308. tx.Rollback()
  3309. logs.Error(err)
  3310. appG.Response(http.StatusOK, e.ERROR, false)
  3311. return
  3312. }
  3313. } else {
  3314. weight := fpdweight - lweight
  3315. for _, lppland := range lpplandList {
  3316. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3317. if weight >= lpplandlweight {
  3318. weight = weight - lpplandlweight
  3319. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3320. if err != nil {
  3321. tx.Rollback()
  3322. logs.Error(err)
  3323. appG.Response(http.StatusOK, e.ERROR, false)
  3324. return
  3325. }
  3326. } else {
  3327. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3328. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3329. // if err != nil {
  3330. // tx.Rollback()
  3331. // logs.Error(err)
  3332. // appG.Response(http.StatusOK, e.ERROR, false)
  3333. // return
  3334. // }
  3335. weight = 0
  3336. break
  3337. }
  3338. }
  3339. }
  3340. }
  3341. }
  3342. fsionData := fsion.Get("data").Array()
  3343. for _, list := range fsionData {
  3344. ftmap := make(map[string]interface{})
  3345. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3346. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3347. ftmap["times"] = list.Get("times").ValueInt64()
  3348. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3349. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3350. // fmt.Println(ftmap)
  3351. // /*
  3352. count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3353. and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3354. if count == 1 {
  3355. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3356. and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3357. if err != nil {
  3358. tx.Rollback()
  3359. logs.Error(err)
  3360. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3361. return
  3362. }
  3363. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3364. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3365. if err != nil {
  3366. tx.Rollback()
  3367. logs.Error(err)
  3368. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3369. return
  3370. }
  3371. }
  3372. // */
  3373. fpdDataList, err := tx.SQL(`
  3374. 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 ,
  3375. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3376. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3377. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3378. if err != nil {
  3379. tx.Rollback()
  3380. logs.Error(err)
  3381. }
  3382. for _, fpd := range fpdDataList {
  3383. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3384. fttype := -1
  3385. if fpd["fttype"].(string) == "1" {
  3386. fttype = 1
  3387. }
  3388. var fweight float64
  3389. var lweight float64
  3390. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3391. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  3392. t.maxstirfeed,(select ifnull(volume,0) from tmr where id = lpp.tmrid ) *
  3393. (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  3394. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3395. join tmr t on t.id = lpp.tmrid
  3396. where lppland.fpdid =?
  3397. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3398. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3399. if err != nil {
  3400. tx.Rollback()
  3401. logs.Error(err)
  3402. }
  3403. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3404. var w float64
  3405. var status int
  3406. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3407. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3408. if weight >= 0 {
  3409. continue
  3410. }
  3411. w = weight
  3412. status = 0
  3413. } else {
  3414. // continue
  3415. if weight <= 0 {
  3416. continue
  3417. }
  3418. w = weight
  3419. status = 1
  3420. }
  3421. // for _, lppland := range lpplandtl1List {
  3422. // lweight += lppland.Lweight
  3423. // }
  3424. for _, lppland := range lpplandtl1List {
  3425. lpplandInfo := new(lpplandtlInfo)
  3426. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3427. lweight = lpplandInfo.Lweight
  3428. if status == 1 {
  3429. // if w <= lppland.Lweight {
  3430. if lppland.Maxweight <= lweight {
  3431. continue
  3432. }
  3433. if w+lweight <= lppland.Maxweight {
  3434. lppland.Lweight += w
  3435. lweight += w
  3436. fweight += w
  3437. w = 0
  3438. } else {
  3439. w = w - (lppland.Maxweight - lweight)
  3440. n := (lppland.Maxweight - lweight)
  3441. lppland.Lweight = lppland.Lweight + n
  3442. lweight += n
  3443. fweight += n
  3444. }
  3445. } else {
  3446. if lppland.Lweight == 0 {
  3447. continue
  3448. }
  3449. if w+lppland.Lweight >= 0 {
  3450. lppland.Lweight = lppland.Lweight + w
  3451. lweight = lweight + w
  3452. fweight = fweight + w
  3453. w = 0
  3454. } else {
  3455. w = w + lppland.Lweight
  3456. lweight = lweight - lppland.Lweight
  3457. fweight = fweight - lppland.Lweight
  3458. lppland.Lweight = 0
  3459. }
  3460. }
  3461. if lppland.Lweight > 0 {
  3462. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3463. if err != nil {
  3464. tx.Rollback()
  3465. logs.Error(err)
  3466. return
  3467. }
  3468. } else {
  3469. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3470. if err != nil {
  3471. tx.Rollback()
  3472. logs.Error(err)
  3473. return
  3474. }
  3475. }
  3476. if w == 0 {
  3477. break
  3478. }
  3479. // break
  3480. }
  3481. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3482. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3483. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3484. if err != nil {
  3485. tx.Rollback()
  3486. logs.Error(err)
  3487. }
  3488. if w == 0 {
  3489. break
  3490. }
  3491. }
  3492. }
  3493. }
  3494. tx.Commit()
  3495. now := time.Now()
  3496. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3497. if err != nil {
  3498. logs.Error(err)
  3499. appG.Response(http.StatusOK, e.ERROR, false)
  3500. return
  3501. }
  3502. for _, newLpplandtl1 := range newLpplandtl1List {
  3503. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3504. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3505. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3506. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3507. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3508. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3509. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3510. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3511. if err != nil {
  3512. logs.Error(err)
  3513. appG.Response(http.StatusOK, e.ERROR, false)
  3514. return
  3515. }
  3516. }
  3517. appG.Response(http.StatusOK, e.SUCCESS, true)
  3518. }
  3519. func GetProcessAnalysis(c *gin.Context) {
  3520. appG := app.Gin{C: c}
  3521. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3522. fsion := gofasion.NewFasion(string(dataByte))
  3523. sqlnamestr := fsion.Get("name").ValueStr()
  3524. offset := fsion.Get("offset").ValueDefaultInt(0)
  3525. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3526. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3527. parammaps := fsion.Get("parammaps")
  3528. tx := restful.Engine.NewSession()
  3529. err := tx.Begin()
  3530. defer func() {
  3531. switch {
  3532. case err != nil:
  3533. logging.Error("tx.Begin 事务启动失败__error:", err)
  3534. if tx != nil {
  3535. tx.Rollback()
  3536. }
  3537. default:
  3538. if tx != nil {
  3539. err = tx.Commit()
  3540. }
  3541. }
  3542. if tx != nil {
  3543. tx.Close()
  3544. }
  3545. }()
  3546. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3547. s_params := make([]interface{}, 0)
  3548. paramslist := strings.Split(p, ",")
  3549. if len(paramslist) > 0 && p != "" {
  3550. for _, value := range paramslist {
  3551. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3552. if tempv, exists := c.Get("jwt_username"); exists {
  3553. s_params = append(s_params, tempv.(string))
  3554. } else {
  3555. s_params = append(s_params, "")
  3556. }
  3557. } else {
  3558. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3559. }
  3560. }
  3561. }
  3562. tmrtnameStr := ""
  3563. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3564. if len(tmrtnameStr) == 0 {
  3565. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3566. } else {
  3567. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3568. }
  3569. }
  3570. if len(tmrtnameStr) > 0 {
  3571. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3572. }
  3573. sql += " ORDER BY d.intime"
  3574. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3575. if err != nil {
  3576. logging.Error("GetDataByName err: ", err)
  3577. msg := geterrmsg(err.Error())
  3578. appG.Response(http.StatusOK, e.ERROR, msg)
  3579. } else {
  3580. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3581. }
  3582. }
  3583. func UpdateFeedtempletStatus(c *gin.Context) {
  3584. appG := app.Gin{C: c}
  3585. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3586. fsion := gofasion.NewFasion(string(dataByte))
  3587. parammaps := fsion.Get("parammaps")
  3588. tx := restful.Engine.NewSession()
  3589. tx.Begin()
  3590. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3591. if err != nil {
  3592. tx.Rollback()
  3593. logs.Error(err)
  3594. appG.Response(http.StatusOK, e.ERROR, err)
  3595. return
  3596. }
  3597. tx.Commit()
  3598. appG.Response(http.StatusOK, e.SUCCESS, true)
  3599. }
  3600. func AddFtdry(c *gin.Context) {
  3601. appG := app.Gin{C: c}
  3602. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3603. fsion := gofasion.NewFasion(string(dataByte))
  3604. sqlnamestr := fsion.Get("name").ValueStr()
  3605. s_params := make([]interface{}, 0)
  3606. tx := restful.Engine.NewSession()
  3607. err := tx.Begin()
  3608. defer func() {
  3609. switch {
  3610. case err != nil:
  3611. if tx != nil {
  3612. tx.Rollback()
  3613. }
  3614. default:
  3615. if tx != nil {
  3616. err = tx.Commit()
  3617. }
  3618. }
  3619. if tx != nil {
  3620. tx.Close()
  3621. }
  3622. }()
  3623. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3624. if sql != "" {
  3625. parammaps := fsion.Get("parammaps")
  3626. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3627. paramslist := strings.Split(p, ",")
  3628. if len(paramslist) > 0 && p != "" {
  3629. for _, value := range paramslist {
  3630. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3631. if tempv, exists := c.Get("jwt_username"); exists {
  3632. s_params = append(s_params, tempv.(string))
  3633. } else {
  3634. s_params = append(s_params, "")
  3635. }
  3636. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3637. ids, err := setting.SnowIds.NextId()
  3638. if err != nil {
  3639. ids = time.Now().UnixNano()
  3640. logging.Info("create SnowIds err", err)
  3641. }
  3642. s_params = append(s_params, ids)
  3643. } else {
  3644. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3645. }
  3646. }
  3647. }
  3648. var actweight float64
  3649. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3650. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3651. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3652. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3653. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3654. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3655. 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()
  3656. if err != nil {
  3657. logging.Error("AddFtdry err: ", err)
  3658. msg := geterrmsg(err.Error())
  3659. appG.Response(http.StatusOK, e.ERROR, msg)
  3660. }
  3661. if len(actweightList) > 0 {
  3662. for _, item := range actweightList {
  3663. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3664. if err != nil {
  3665. logging.Error("AddFtdry err: ", err)
  3666. msg := geterrmsg(err.Error())
  3667. appG.Response(http.StatusOK, e.ERROR, msg)
  3668. }
  3669. actweight = fl
  3670. }
  3671. } else {
  3672. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3673. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3674. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3675. if err != nil {
  3676. logging.Error("AddFtdry err: ", err)
  3677. msg := geterrmsg(err.Error())
  3678. appG.Response(http.StatusOK, e.ERROR, msg)
  3679. }
  3680. for _, item := range dryList {
  3681. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3682. if err != nil {
  3683. logging.Error("AddFtdry err: ", err)
  3684. msg := geterrmsg(err.Error())
  3685. appG.Response(http.StatusOK, e.ERROR, msg)
  3686. }
  3687. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3688. }
  3689. }
  3690. if sqlnamestr == "insertFtdry" {
  3691. s_params = append(s_params, actweight)
  3692. } else if sqlnamestr == "updateFtdry" {
  3693. sql = fmt.Sprintf(sql, actweight)
  3694. }
  3695. queryData, err := execDataBySqlT(sql, s_params, tx)
  3696. if err != nil {
  3697. logging.Error("AddFtdry err: ", err)
  3698. msg := geterrmsg(err.Error())
  3699. appG.Response(http.StatusOK, e.ERROR, msg)
  3700. } else {
  3701. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3702. }
  3703. } else {
  3704. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3705. }
  3706. }
  3707. func CheckDates(c *gin.Context) {
  3708. tx := restful.Engine.NewSession()
  3709. defer tx.Close()
  3710. appG := app.Gin{C: c}
  3711. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3712. tempval_ := make(map[string]interface{})
  3713. tempCommon := make(map[string]interface{})
  3714. tempval := make([]map[string]interface{}, 0)
  3715. err := json.Unmarshal(dataByte, &tempval_)
  3716. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3717. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3718. if err != nil {
  3719. } else {
  3720. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3721. tempCommon = v
  3722. }
  3723. if v, ok := tempval_["data"].([]interface{}); ok {
  3724. for _, Tvalue := range v {
  3725. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3726. tempval = append(tempval, v1)
  3727. }
  3728. }
  3729. }
  3730. if err == nil {
  3731. if tempv, exists := c.Get("jwt_username"); exists {
  3732. tempCommon["jwt_username"] = tempv.(string)
  3733. }
  3734. for _, paramvalue := range tempval {
  3735. if _, ok := paramvalue["resultname"]; !ok {
  3736. paramvalue["resultname"] = paramvalue["name"]
  3737. }
  3738. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3739. if err != nil {
  3740. logging.Error("ExecDataParam error:", err)
  3741. }
  3742. }
  3743. if err == nil {
  3744. vmsg := ""
  3745. for _, item := range tempval {
  3746. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3747. for _, childrenList := range list.([]interface{}) {
  3748. for k, children := range childrenList.(map[string]interface{}) {
  3749. if k != "children" {
  3750. continue
  3751. }
  3752. for _, v := range children.([]map[string]interface{}) {
  3753. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3754. if k1 == "list" {
  3755. for _, v2 := range v1.([]map[string]interface{}) {
  3756. if v2["vmsg"].(string) != "1" {
  3757. if len(vmsg) == 0 {
  3758. vmsg = v2["vmsg"].(string)
  3759. } else {
  3760. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3761. }
  3762. }
  3763. }
  3764. }
  3765. }
  3766. }
  3767. }
  3768. }
  3769. }
  3770. }
  3771. if len(vmsg) > 0 {
  3772. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3773. } else {
  3774. appG.Response(http.StatusOK, e.SUCCESS, true)
  3775. }
  3776. } else {
  3777. msg := geterrmsg(err.Error())
  3778. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3779. }
  3780. }
  3781. }
  3782. if err != nil {
  3783. msg := geterrmsg(err.Error())
  3784. appG.Response(http.StatusOK, e.ERROR, msg)
  3785. }
  3786. }
  3787. 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) {
  3788. sqlname := fasion["name"].(string)
  3789. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3790. if v, ok := fasion["type"]; ok {
  3791. sqltype = v.(string)
  3792. }
  3793. sql := ""
  3794. p := ""
  3795. s_params := make([]interface{}, 0)
  3796. if sqltype != "" {
  3797. sql, p = restful.GetSqlByName(sqlname, tx)
  3798. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3799. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3800. paramslist := strings.Split(p, ",")
  3801. if len(paramslist) > 0 && p != "" {
  3802. for _, value := range paramslist {
  3803. ss := ""
  3804. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3805. ids, err := setting.SnowIds.NextId()
  3806. if err != nil {
  3807. ids = time.Now().UnixNano()
  3808. logging.Info("create SnowIds err", err)
  3809. }
  3810. s_params = append(s_params, ids)
  3811. } else {
  3812. if ss == "" && CommonParamMap != nil {
  3813. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3814. ss = valuestring
  3815. tempstrb := strings.IndexAny(valuestring, "@")
  3816. tempstre := strings.IndexAny(valuestring, ".")
  3817. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3818. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3819. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3820. }
  3821. } else {
  3822. ss = ""
  3823. }
  3824. }
  3825. }
  3826. if ss == "" && ParentParamMap != nil {
  3827. ss = getParamValue_(v, value, ParentParamMap)
  3828. }
  3829. if ss == "" && sameParamMap != nil {
  3830. ss = getParamValue(v, value, sameParamMap)
  3831. }
  3832. if ss == "" && ParamMap != nil {
  3833. ss = getParamValue(v, value, ParamMap)
  3834. }
  3835. s_params = append(s_params, ss)
  3836. }
  3837. }
  3838. }
  3839. }
  3840. }
  3841. if sql == "" {
  3842. sqltype = ""
  3843. }
  3844. if sql != "" {
  3845. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3846. if err != nil {
  3847. return nil, err
  3848. }
  3849. // fmt.Println(tempValParam)
  3850. return tempValParam.(map[string]interface{}), nil
  3851. } else {
  3852. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3853. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3854. if err != nil {
  3855. return nil, err
  3856. }
  3857. return nil, err
  3858. }
  3859. }
  3860. return nil, nil
  3861. }
  3862. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3863. var err error
  3864. subarray, ok := fasion["children"]
  3865. if ok {
  3866. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3867. tempVal_arrary := make([]map[string]interface{}, 0)
  3868. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3869. tempVal_ := make(map[string]interface{})
  3870. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3871. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3872. } else {
  3873. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3874. }
  3875. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3876. if err != nil {
  3877. return err
  3878. }
  3879. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3880. }
  3881. v.(map[string]interface{})["children"] = tempVal_arrary
  3882. }
  3883. }
  3884. return nil
  3885. }
  3886. func FpdImportExcel(c *gin.Context) {
  3887. appG := app.Gin{C: c}
  3888. inputdata := ""
  3889. c.Request.ParseForm()
  3890. params := c.Request.Form
  3891. file, _, err := c.Request.FormFile("file")
  3892. if err != nil {
  3893. appG.Response(http.StatusOK, e.ERROR, err)
  3894. return
  3895. }
  3896. sqlnamestrs := params.Get("name")
  3897. sheetname := params.Get("sheetname")
  3898. pastureid := params.Get("pastureid")
  3899. // importParams := params.Get("importParams")
  3900. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3901. // 必输项参数 (字符串格式 "field1,field2,field3")
  3902. requiredParams := params.Get("requiredParams")
  3903. // 日期参数
  3904. dateParams := params.Get("dateParams")
  3905. // 数字参数
  3906. numParams := params.Get("numParams")
  3907. //将字符串分割开
  3908. dateParamslist := strings.Split(dateParams, ",")
  3909. requiredParamslist := strings.Split(requiredParams, ",")
  3910. numParamslist := strings.Split(numParams, ",")
  3911. queryData := make([]interface{}, 0)
  3912. sqlslist := strings.Split(sqlnamestrs, ",")
  3913. xlsx1, err := excelize.OpenReader(file)
  3914. if err != nil {
  3915. fmt.Println(err)
  3916. return
  3917. }
  3918. ok := 0
  3919. error := 0
  3920. isdone := true
  3921. tx := restful.Engine.NewSession()
  3922. defer tx.Close()
  3923. languageStatus := GetLanguageStatus()
  3924. if languageStatus == "0" {
  3925. 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
  3926. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3927. if err != nil {
  3928. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3929. return
  3930. }
  3931. rows := xlsx1.GetRows(sheetname)
  3932. // 限制10000条,多余的截取掉
  3933. if len(rows) > 10000 {
  3934. rows = rows[:10000]
  3935. }
  3936. dataList := make(map[string][]*upFpdetail, 0)
  3937. for i, row := range rows {
  3938. if i > 0 {
  3939. entry := make(map[string]interface{})
  3940. outentry := make(map[string]interface{})
  3941. for j, colCell := range rows[0] {
  3942. for k, colCell1 := range row {
  3943. if j == k {
  3944. outentry[colCell] = colCell1
  3945. entry[colCell] = colCell1
  3946. }
  3947. }
  3948. }
  3949. inputdata = ""
  3950. a := ""
  3951. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3952. //校验日期格式
  3953. for _, v := range dateParamslist {
  3954. if v == "" {
  3955. continue
  3956. }
  3957. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3958. dtime, err := TransfTime(d.(string))
  3959. if err != nil {
  3960. a = strings.Trim(v, " ")
  3961. break
  3962. }
  3963. outentry[strings.Trim(v, " ")] = dtime
  3964. }
  3965. }
  3966. if a != "" {
  3967. outentry["error_msg"] = a + " 格式错误"
  3968. error++
  3969. queryData = append(queryData, outentry)
  3970. continue
  3971. }
  3972. a = ""
  3973. //校验必填格式
  3974. for _, v := range requiredParamslist {
  3975. if v == "" {
  3976. continue
  3977. }
  3978. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3979. a = strings.Trim(v, " ")
  3980. break
  3981. }
  3982. }
  3983. if a != "" {
  3984. outentry["error_msg"] = a + " 未填或格式错误"
  3985. error++
  3986. queryData = append(queryData, outentry)
  3987. continue
  3988. }
  3989. a = ""
  3990. //校验数字格式
  3991. for _, v := range numParamslist {
  3992. if v == "" {
  3993. continue
  3994. }
  3995. d, ok := outentry[strings.Trim(v, " ")]
  3996. if !ok || d == "" {
  3997. outentry[strings.Trim(v, " ")] = 0
  3998. } else {
  3999. var fl float64
  4000. switch d.(type) {
  4001. case string:
  4002. fl, err = strconv.ParseFloat(d.(string), 64)
  4003. }
  4004. if err != nil || fl < 0 {
  4005. a = strings.Trim(v, " ")
  4006. break
  4007. }
  4008. }
  4009. }
  4010. if a != "" {
  4011. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  4012. error++
  4013. queryData = append(queryData, outentry)
  4014. continue
  4015. }
  4016. errExist := false
  4017. for _, sqlnamestr := range sqlslist {
  4018. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4019. paramslist := strings.Split(paramslists, ",")
  4020. if len(paramslist) > 0 {
  4021. s_params := make([]interface{}, 0)
  4022. for _, value := range paramslist {
  4023. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4024. if tempv, exists := c.Get("jwt_username"); exists {
  4025. s_params = append(s_params, tempv.(string))
  4026. } else {
  4027. s_params = append(s_params, "")
  4028. }
  4029. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4030. s_params = append(s_params, pastureid)
  4031. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4032. ids, err := setting.SnowIds.NextId()
  4033. if err != nil {
  4034. ids = time.Now().UnixNano()
  4035. logging.Info("create SnowIds err", err)
  4036. }
  4037. s_params = append(s_params, ids)
  4038. } else {
  4039. if outentry[strings.Trim(value, " ")] == nil {
  4040. s_params = append(s_params, "")
  4041. } else {
  4042. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4043. }
  4044. }
  4045. }
  4046. outentry["input"] = inputdata
  4047. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4048. if err != nil {
  4049. errExist = true
  4050. // if tx != nil {
  4051. // tx.Rollback()
  4052. // }
  4053. // if tx != nil {
  4054. // tx.Close()
  4055. // }
  4056. msg := geterrmsg(err.Error())
  4057. outentry["error_msg"] = msg
  4058. error++
  4059. queryData = append(queryData, outentry)
  4060. isdone = true
  4061. break
  4062. } else {
  4063. if len(returnmsgmap1) > 0 {
  4064. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4065. // if tx != nil {
  4066. // tx.Rollback()
  4067. // }
  4068. // if tx != nil {
  4069. // tx.Close()
  4070. // }
  4071. msg := geterrmsg(va.(string))
  4072. outentry["error_msg"] = msg
  4073. error++
  4074. queryData = append(queryData, outentry)
  4075. isdone = true
  4076. break
  4077. }
  4078. }
  4079. isdone = false
  4080. }
  4081. }
  4082. }
  4083. fmt.Println(outentry["栏舍名称"])
  4084. if !errExist {
  4085. dataexcel := make(map[string]interface{}, 0)
  4086. if _, ok := outentry["栏舍名称"]; ok {
  4087. dataexcel["barname"] = outentry["栏舍名称"]
  4088. }
  4089. if _, ok := outentry["实际牛头数"]; ok {
  4090. dataexcel["ccount"] = outentry["实际牛头数"]
  4091. }
  4092. // if _, ok := outentry["实际羊只数"]; ok {
  4093. // dataexcel["ccount"] = outentry["实际羊只数"]
  4094. // }
  4095. if _, ok := outentry["系数(%)"]; ok {
  4096. dataexcel["ratio"] = outentry["系数(%)"]
  4097. }
  4098. if _, ok := outentry["配方模板"]; ok {
  4099. dataexcel["ftname"] = outentry["配方模板"]
  4100. }
  4101. if _, ok := outentry["补料配方"]; ok {
  4102. dataexcel["ptsfname"] = outentry["补料配方"]
  4103. }
  4104. if _, ok := outentry["第一班比例(%)"]; ok {
  4105. dataexcel["1"] = outentry["第一班比例(%)"]
  4106. if fmt.Sprintf("%v", dataexcel["1"]) == "" {
  4107. dataexcel["1"] = 0
  4108. }
  4109. } else {
  4110. dataexcel["1"] = 0
  4111. }
  4112. if _, ok := outentry["第二班比例(%)"]; ok {
  4113. dataexcel["2"] = outentry["第二班比例(%)"]
  4114. if fmt.Sprintf("%v", dataexcel["2"]) == "" {
  4115. dataexcel["2"] = 0
  4116. }
  4117. } else {
  4118. dataexcel["2"] = 0
  4119. }
  4120. if _, ok := outentry["第三班比例(%)"]; ok {
  4121. dataexcel["3"] = outentry["第三班比例(%)"]
  4122. if fmt.Sprintf("%v", dataexcel["3"]) == "" {
  4123. dataexcel["3"] = 0
  4124. }
  4125. } else {
  4126. dataexcel["3"] = 0
  4127. }
  4128. if _, ok := outentry["第四班比例(%)"]; ok {
  4129. dataexcel["4"] = outentry["第四班比例(%)"]
  4130. if fmt.Sprintf("%v", dataexcel["4"]) == "" {
  4131. dataexcel["4"] = 0
  4132. }
  4133. } else {
  4134. dataexcel["4"] = 0
  4135. }
  4136. if _, ok := outentry["第五班比例(%)"]; ok {
  4137. dataexcel["5"] = outentry["第五班比例(%)"]
  4138. if fmt.Sprintf("%v", dataexcel["5"]) == "" {
  4139. dataexcel["5"] = 0
  4140. }
  4141. } else {
  4142. dataexcel["5"] = 0
  4143. }
  4144. if _, ok := outentry["第六班比例(%)"]; ok {
  4145. dataexcel["6"] = outentry["第六班比例(%)"]
  4146. if fmt.Sprintf("%v", dataexcel["6"]) == "" {
  4147. dataexcel["6"] = 0
  4148. }
  4149. } else {
  4150. dataexcel["6"] = 0
  4151. }
  4152. dataWeight := new(models.FpdetailEdit)
  4153. // dataWeightMap := make(map[string]interface{}, 0)
  4154. if _, ok := outentry["第一班重量"]; ok {
  4155. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4156. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4157. }
  4158. if _, ok := outentry["第二班重量"]; ok {
  4159. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4160. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4161. }
  4162. if _, ok := outentry["第三班重量"]; ok {
  4163. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4164. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4165. }
  4166. if _, ok := outentry["第四班重量"]; ok {
  4167. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4168. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4169. }
  4170. if _, ok := outentry["第五班重量"]; ok {
  4171. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4172. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4173. }
  4174. if _, ok := outentry["第六班重量"]; ok {
  4175. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4176. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4177. }
  4178. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4179. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4180. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4181. // fmt.Println(err)
  4182. if fmt.Sprintf("%v", dataexcel["ccount"]) == "0" {
  4183. dataWeight.Weight1 = 0
  4184. dataWeight.Weight2 = 0
  4185. dataWeight.Weight3 = 0
  4186. dataWeight.Weight4 = 0
  4187. dataWeight.Weight5 = 0
  4188. dataWeight.Weight6 = 0
  4189. }
  4190. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4191. if weight > 0 {
  4192. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4193. if err != nil {
  4194. logs.Error(err)
  4195. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4196. return
  4197. }
  4198. if !existbar {
  4199. continue
  4200. }
  4201. _, 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()
  4202. if err != nil {
  4203. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4204. return
  4205. }
  4206. _, 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()
  4207. if err != nil {
  4208. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4209. return
  4210. }
  4211. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4212. if err != nil {
  4213. logs.Error(err)
  4214. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4215. return
  4216. }
  4217. if !existft {
  4218. continue
  4219. }
  4220. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4221. if err != nil {
  4222. logs.Error(err)
  4223. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4224. return
  4225. }
  4226. if !ftexist {
  4227. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4228. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4229. if err != nil {
  4230. logs.Error(err)
  4231. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4232. return
  4233. }
  4234. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4235. if err != nil {
  4236. logs.Error(err)
  4237. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4238. return
  4239. }
  4240. }
  4241. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4242. if err != nil {
  4243. logs.Error(err)
  4244. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4245. return
  4246. }
  4247. if !exist {
  4248. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4249. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4250. if err != nil {
  4251. logs.Error(err)
  4252. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4253. return
  4254. }
  4255. }
  4256. var feedpargs []interface{}
  4257. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4258. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4259. if _, ok := dataexcel["ftname"]; ok {
  4260. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4261. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4262. // upFeedpSql += `,ftweight = ? `
  4263. // feedpargs = append(feedpargs, weight)
  4264. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4265. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4266. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4267. } else {
  4268. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4269. }
  4270. if _, ok := dataexcel["ptsfname"]; ok {
  4271. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4272. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4273. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4274. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4275. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4276. } else {
  4277. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4278. }
  4279. upFeedpSql += " where barname = ? and pastureid = ? "
  4280. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4281. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4282. if err != nil {
  4283. logs.Error(err)
  4284. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4285. return
  4286. }
  4287. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4288. if err != nil {
  4289. logs.Error(err)
  4290. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4291. return
  4292. }
  4293. if !exist1 {
  4294. _, 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) `,
  4295. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4296. if err != nil {
  4297. logs.Error(err)
  4298. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4299. return
  4300. }
  4301. }
  4302. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4303. if err != nil {
  4304. logs.Error(err)
  4305. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4306. return
  4307. }
  4308. if !exist2 {
  4309. _, 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) `,
  4310. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4311. if err != nil {
  4312. logs.Error(err)
  4313. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4314. return
  4315. }
  4316. }
  4317. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4318. if err != nil {
  4319. logs.Error(err)
  4320. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4321. return
  4322. }
  4323. if !exist3 {
  4324. _, 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) `,
  4325. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4326. if err != nil {
  4327. logs.Error(err)
  4328. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4329. return
  4330. }
  4331. }
  4332. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4333. if err != nil {
  4334. logs.Error(err)
  4335. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4336. return
  4337. }
  4338. if !exist4 {
  4339. _, 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) `,
  4340. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4341. if err != nil {
  4342. logs.Error(err)
  4343. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4344. return
  4345. }
  4346. }
  4347. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4348. if err != nil {
  4349. logs.Error(err)
  4350. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4351. return
  4352. }
  4353. if !exist5 {
  4354. _, 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) `,
  4355. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4356. if err != nil {
  4357. logs.Error(err)
  4358. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4359. return
  4360. }
  4361. }
  4362. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4363. if err != nil {
  4364. logs.Error(err)
  4365. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4366. return
  4367. }
  4368. if !exist6 {
  4369. _, 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) `,
  4370. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4371. if err != nil {
  4372. logs.Error(err)
  4373. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4374. return
  4375. }
  4376. }
  4377. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4378. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4379. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4380. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4381. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4382. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4383. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4384. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4385. and pastureid = ? and times = ?`
  4386. var fpdargs1 []interface{}
  4387. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4388. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4389. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4390. if err != nil {
  4391. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4392. return
  4393. }
  4394. var fpdargs2 []interface{}
  4395. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4396. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4397. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4398. if err != nil {
  4399. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4400. return
  4401. }
  4402. var fpdargs3 []interface{}
  4403. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4404. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4405. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4406. if err != nil {
  4407. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4408. return
  4409. }
  4410. var fpdargs4 []interface{}
  4411. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4412. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4413. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4414. if err != nil {
  4415. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4416. return
  4417. }
  4418. var fpdargs5 []interface{}
  4419. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4420. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4421. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4422. if err != nil {
  4423. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4424. return
  4425. }
  4426. var fpdargs6 []interface{}
  4427. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4428. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4429. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4430. if err != nil {
  4431. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4432. return
  4433. }
  4434. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4435. 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()
  4436. if err != nil {
  4437. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4438. return
  4439. }
  4440. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4441. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4442. upFpdetailList := make([]*upFpdetail, 0)
  4443. for _, newfpd := range newList {
  4444. for _, oldfpd := range oldFpdList {
  4445. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4446. var oldweight, newweight float64
  4447. if oldfpd["weight"] != nil {
  4448. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4449. }
  4450. if newfpd["weight"] != nil {
  4451. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4452. }
  4453. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4454. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4455. Old: oldweight,
  4456. New: newweight,
  4457. Times: newfpd["times"].(int64),
  4458. Ptid: newfpd["ptid"].(int64),
  4459. Fweight: fweight,
  4460. Id: oldfpd["id"].(int64),
  4461. })
  4462. break
  4463. }
  4464. }
  4465. }
  4466. // fmt.Println(dataexcel["barname"])
  4467. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4468. } else {
  4469. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4470. if err != nil {
  4471. logs.Error(err)
  4472. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4473. return
  4474. }
  4475. if !existbar {
  4476. continue
  4477. }
  4478. _, 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()
  4479. if err != nil {
  4480. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4481. return
  4482. }
  4483. _, 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()
  4484. if err != nil {
  4485. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4486. return
  4487. }
  4488. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4489. if err != nil {
  4490. logs.Error(err)
  4491. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4492. return
  4493. }
  4494. if !existft {
  4495. continue
  4496. }
  4497. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4498. if err != nil {
  4499. logs.Error(err)
  4500. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4501. return
  4502. }
  4503. if !ftexist {
  4504. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4505. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4506. if err != nil {
  4507. logs.Error(err)
  4508. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4509. return
  4510. }
  4511. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4512. if err != nil {
  4513. logs.Error(err)
  4514. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4515. return
  4516. }
  4517. }
  4518. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4519. if err != nil {
  4520. logs.Error(err)
  4521. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4522. return
  4523. }
  4524. if !exist {
  4525. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4526. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4527. if err != nil {
  4528. logs.Error(err)
  4529. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4530. return
  4531. }
  4532. }
  4533. var feedpargs []interface{}
  4534. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4535. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4536. if _, ok := dataexcel["ftname"]; ok {
  4537. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4538. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4539. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4540. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4541. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4542. } else {
  4543. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4544. }
  4545. if _, ok := dataexcel["ptsfname"]; ok {
  4546. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4547. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4548. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4549. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4550. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4551. } else {
  4552. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4553. }
  4554. upFeedpSql += " where barname = ? and pastureid = ? "
  4555. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4556. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4557. if err != nil {
  4558. logs.Error(err)
  4559. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4560. return
  4561. }
  4562. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4563. if err != nil {
  4564. logs.Error(err)
  4565. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4566. return
  4567. }
  4568. if !exist1 {
  4569. _, 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) `,
  4570. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4571. if err != nil {
  4572. logs.Error(err)
  4573. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4574. return
  4575. }
  4576. }
  4577. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4578. if err != nil {
  4579. logs.Error(err)
  4580. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4581. return
  4582. }
  4583. if !exist2 {
  4584. _, 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) `,
  4585. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4586. if err != nil {
  4587. logs.Error(err)
  4588. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4589. return
  4590. }
  4591. }
  4592. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4593. if err != nil {
  4594. logs.Error(err)
  4595. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4596. return
  4597. }
  4598. if !exist3 {
  4599. _, 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) `,
  4600. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4601. if err != nil {
  4602. logs.Error(err)
  4603. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4604. return
  4605. }
  4606. }
  4607. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4608. if err != nil {
  4609. logs.Error(err)
  4610. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4611. return
  4612. }
  4613. if !exist4 {
  4614. _, 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) `,
  4615. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4616. if err != nil {
  4617. logs.Error(err)
  4618. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4619. return
  4620. }
  4621. }
  4622. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4623. if err != nil {
  4624. logs.Error(err)
  4625. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4626. return
  4627. }
  4628. if !exist5 {
  4629. _, 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) `,
  4630. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4631. if err != nil {
  4632. logs.Error(err)
  4633. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4634. return
  4635. }
  4636. }
  4637. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4638. if err != nil {
  4639. logs.Error(err)
  4640. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4641. return
  4642. }
  4643. if !exist6 {
  4644. _, 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) `,
  4645. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4646. if err != nil {
  4647. logs.Error(err)
  4648. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4649. return
  4650. }
  4651. }
  4652. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4653. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4654. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4655. and pastureid = ? and times = ?`
  4656. var fpdargs1 []interface{}
  4657. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4658. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4659. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4660. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4661. if err != nil {
  4662. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4663. return
  4664. }
  4665. var fpdargs2 []interface{}
  4666. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4667. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4668. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4669. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4670. if err != nil {
  4671. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4672. return
  4673. }
  4674. var fpdargs3 []interface{}
  4675. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4676. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4677. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4678. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4679. if err != nil {
  4680. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4681. return
  4682. }
  4683. var fpdargs4 []interface{}
  4684. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4685. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4686. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4687. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4688. if err != nil {
  4689. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4690. return
  4691. }
  4692. var fpdargs5 []interface{}
  4693. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4694. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4695. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4696. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4697. if err != nil {
  4698. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4699. return
  4700. }
  4701. var fpdargs6 []interface{}
  4702. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4703. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4704. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4705. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4706. if err != nil {
  4707. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4708. return
  4709. }
  4710. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4711. 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()
  4712. if err != nil {
  4713. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4714. return
  4715. }
  4716. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4717. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4718. upFpdetailList := make([]*upFpdetail, 0)
  4719. for _, newfpd := range newList {
  4720. for _, oldfpd := range oldFpdList {
  4721. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4722. var oldweight, newweight float64
  4723. if oldfpd["weight"] != nil {
  4724. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4725. }
  4726. if newfpd["weight"] != nil {
  4727. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4728. }
  4729. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4730. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4731. Old: oldweight,
  4732. New: newweight,
  4733. Times: newfpd["times"].(int64),
  4734. Ptid: newfpd["ptid"].(int64),
  4735. Fweight: fweight,
  4736. Id: oldfpd["id"].(int64),
  4737. })
  4738. break
  4739. }
  4740. }
  4741. }
  4742. // fmt.Println(dataexcel["barname"])
  4743. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4744. }
  4745. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4746. }
  4747. }
  4748. if !isdone {
  4749. ok++
  4750. isdone = true
  4751. }
  4752. }
  4753. for barname, v := range dataList {
  4754. // for _, v1 := range v {
  4755. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4756. // and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4757. // if count == 1 {
  4758. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4759. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4760. // if err != nil {
  4761. // logs.Error(err)
  4762. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4763. // return
  4764. // }
  4765. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4766. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4767. // if err != nil {
  4768. // logs.Error(err)
  4769. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4770. // return
  4771. // }
  4772. // }
  4773. // }
  4774. // /*
  4775. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  4776. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  4777. if err != nil {
  4778. logs.Error(err)
  4779. return
  4780. }
  4781. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4782. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  4783. if err != nil {
  4784. logs.Error(err)
  4785. return
  4786. }
  4787. // */
  4788. updateFpdetailByBar(pastureid, barname, v)
  4789. }
  4790. } else {
  4791. 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
  4792. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4793. if err != nil {
  4794. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4795. return
  4796. }
  4797. rows := xlsx1.GetRows(sheetname)
  4798. // 限制10000条,多余的截取掉
  4799. if len(rows) > 10000 {
  4800. rows = rows[:10000]
  4801. }
  4802. dataList := make(map[string][]*upFpdetail, 0)
  4803. for i, row := range rows {
  4804. if i > 0 {
  4805. entry := make(map[string]interface{})
  4806. outentry := make(map[string]interface{})
  4807. for j, colCell := range rows[0] {
  4808. for k, colCell1 := range row {
  4809. if j == k {
  4810. outentry[colCell] = colCell1
  4811. entry[colCell] = colCell1
  4812. }
  4813. }
  4814. }
  4815. inputdata = ""
  4816. a := ""
  4817. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4818. //校验日期格式
  4819. for _, v := range dateParamslist {
  4820. if v == "" {
  4821. continue
  4822. }
  4823. if d, ok := outentry[v]; ok {
  4824. dtime, err := TransfTime(d.(string))
  4825. if err != nil {
  4826. a = v
  4827. break
  4828. }
  4829. outentry[v] = dtime
  4830. }
  4831. }
  4832. if a != "" {
  4833. outentry["error_msg"] = a + " format error"
  4834. error++
  4835. queryData = append(queryData, outentry)
  4836. continue
  4837. }
  4838. a = ""
  4839. //校验必填格式
  4840. for _, v := range requiredParamslist {
  4841. if v == "" {
  4842. continue
  4843. }
  4844. if d, ok := outentry[v]; !ok || d == "" {
  4845. a = v
  4846. break
  4847. }
  4848. }
  4849. if a != "" {
  4850. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4851. error++
  4852. queryData = append(queryData, outentry)
  4853. continue
  4854. }
  4855. a = ""
  4856. //校验数字格式
  4857. for _, v := range numParamslist {
  4858. if v == "" {
  4859. continue
  4860. }
  4861. d, ok := outentry[v]
  4862. if !ok || d == "" {
  4863. outentry[v] = 0
  4864. } else {
  4865. var fl float64
  4866. switch d.(type) {
  4867. case string:
  4868. fl, err = strconv.ParseFloat(d.(string), 64)
  4869. }
  4870. if err != nil || fl < 0 {
  4871. a = v
  4872. break
  4873. }
  4874. }
  4875. }
  4876. if a != "" {
  4877. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4878. error++
  4879. queryData = append(queryData, outentry)
  4880. continue
  4881. }
  4882. errExist := false
  4883. for _, sqlnamestr := range sqlslist {
  4884. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4885. paramslist := strings.Split(paramslists, ",")
  4886. if len(paramslist) > 0 {
  4887. s_params := make([]interface{}, 0)
  4888. for _, value := range paramslist {
  4889. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4890. if tempv, exists := c.Get("jwt_username"); exists {
  4891. s_params = append(s_params, tempv.(string))
  4892. } else {
  4893. s_params = append(s_params, "")
  4894. }
  4895. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4896. s_params = append(s_params, pastureid)
  4897. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4898. ids, err := setting.SnowIds.NextId()
  4899. if err != nil {
  4900. ids = time.Now().UnixNano()
  4901. logging.Info("create SnowIds err", err)
  4902. }
  4903. s_params = append(s_params, ids)
  4904. } else {
  4905. if outentry[strings.Trim(value, " ")] == nil {
  4906. s_params = append(s_params, "")
  4907. } else {
  4908. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4909. }
  4910. }
  4911. }
  4912. outentry["input"] = inputdata
  4913. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4914. if err != nil {
  4915. errExist = true
  4916. // if tx != nil {
  4917. // tx.Rollback()
  4918. // }
  4919. // if tx != nil {
  4920. // tx.Close()
  4921. // }
  4922. msg := geterrmsg(err.Error())
  4923. outentry["error_msg"] = msg
  4924. error++
  4925. queryData = append(queryData, outentry)
  4926. isdone = true
  4927. break
  4928. } else {
  4929. if len(returnmsgmap1) > 0 {
  4930. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4931. // if tx != nil {
  4932. // tx.Rollback()
  4933. // }
  4934. // if tx != nil {
  4935. // tx.Close()
  4936. // }
  4937. msg := geterrmsg(va.(string))
  4938. outentry["error_msg"] = msg
  4939. error++
  4940. queryData = append(queryData, outentry)
  4941. isdone = true
  4942. break
  4943. }
  4944. }
  4945. isdone = false
  4946. }
  4947. }
  4948. }
  4949. if !errExist {
  4950. dataexcel := make(map[string]interface{}, 0)
  4951. if _, ok := outentry["Pen Name"]; ok {
  4952. dataexcel["barname"] = outentry["Pen Name"]
  4953. }
  4954. if _, ok := outentry["Actual Cattle Number"]; ok {
  4955. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4956. }
  4957. if _, ok := outentry["Coefficient(%)"]; ok {
  4958. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4959. }
  4960. if _, ok := outentry["Formula Template"]; ok {
  4961. dataexcel["ftname"] = outentry["Formula Template"]
  4962. }
  4963. if _, ok := outentry["Supplement Formula"]; ok {
  4964. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4965. }
  4966. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4967. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4968. }
  4969. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4970. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4971. }
  4972. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4973. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4974. }
  4975. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4976. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4977. }
  4978. if _, ok := outentry["Fifth Shift Ratio(%)"]; ok {
  4979. dataexcel["5"] = outentry["Fifth Shift Ratio(%)"]
  4980. }
  4981. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4982. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4983. }
  4984. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4985. if err != nil {
  4986. logs.Error(err)
  4987. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4988. return
  4989. }
  4990. if !existbar {
  4991. continue
  4992. }
  4993. _, 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()
  4994. if err != nil {
  4995. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4996. return
  4997. }
  4998. _, 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()
  4999. if err != nil {
  5000. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5001. return
  5002. }
  5003. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  5004. if err != nil {
  5005. logs.Error(err)
  5006. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  5007. return
  5008. }
  5009. if !existft {
  5010. continue
  5011. }
  5012. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  5013. if err != nil {
  5014. logs.Error(err)
  5015. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5016. return
  5017. }
  5018. if !ftexist {
  5019. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  5020. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5021. if err != nil {
  5022. logs.Error(err)
  5023. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5024. return
  5025. }
  5026. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5027. if err != nil {
  5028. logs.Error(err)
  5029. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5030. return
  5031. }
  5032. }
  5033. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5034. if err != nil {
  5035. logs.Error(err)
  5036. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5037. return
  5038. }
  5039. if !exist {
  5040. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  5041. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  5042. if err != nil {
  5043. logs.Error(err)
  5044. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5045. return
  5046. }
  5047. }
  5048. var feedpargs []interface{}
  5049. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  5050. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  5051. if _, ok := dataexcel["ftname"]; ok {
  5052. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  5053. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  5054. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  5055. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  5056. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5057. } else {
  5058. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  5059. }
  5060. if _, ok := dataexcel["ptsfname"]; ok {
  5061. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  5062. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  5063. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  5064. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  5065. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5066. } else {
  5067. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  5068. }
  5069. upFeedpSql += " where barname = ? and pastureid = ? "
  5070. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  5071. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  5072. if err != nil {
  5073. logs.Error(err)
  5074. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5075. return
  5076. }
  5077. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  5078. if err != nil {
  5079. logs.Error(err)
  5080. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5081. return
  5082. }
  5083. if !exist1 {
  5084. _, 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) `,
  5085. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5086. if err != nil {
  5087. logs.Error(err)
  5088. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5089. return
  5090. }
  5091. }
  5092. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5093. if err != nil {
  5094. logs.Error(err)
  5095. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5096. return
  5097. }
  5098. if !exist2 {
  5099. _, 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) `,
  5100. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5101. if err != nil {
  5102. logs.Error(err)
  5103. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5104. return
  5105. }
  5106. }
  5107. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5108. if err != nil {
  5109. logs.Error(err)
  5110. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5111. return
  5112. }
  5113. if !exist3 {
  5114. _, 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) `,
  5115. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5116. if err != nil {
  5117. logs.Error(err)
  5118. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5119. return
  5120. }
  5121. }
  5122. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5123. if err != nil {
  5124. logs.Error(err)
  5125. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5126. return
  5127. }
  5128. if !exist4 {
  5129. _, 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) `,
  5130. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5131. if err != nil {
  5132. logs.Error(err)
  5133. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5134. return
  5135. }
  5136. }
  5137. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5138. if err != nil {
  5139. logs.Error(err)
  5140. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5141. return
  5142. }
  5143. if !exist5 {
  5144. _, 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) `,
  5145. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5146. if err != nil {
  5147. logs.Error(err)
  5148. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5149. return
  5150. }
  5151. }
  5152. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5153. if err != nil {
  5154. logs.Error(err)
  5155. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5156. return
  5157. }
  5158. if !exist6 {
  5159. _, 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) `,
  5160. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5161. if err != nil {
  5162. logs.Error(err)
  5163. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5164. return
  5165. }
  5166. }
  5167. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5168. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5169. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5170. and pastureid = ? and times = ?`
  5171. var fpdargs1 []interface{}
  5172. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5173. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5174. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5175. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5176. if err != nil {
  5177. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5178. return
  5179. }
  5180. var fpdargs2 []interface{}
  5181. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5182. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5183. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5184. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5185. if err != nil {
  5186. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5187. return
  5188. }
  5189. var fpdargs3 []interface{}
  5190. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5191. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5192. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5193. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5194. if err != nil {
  5195. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5196. return
  5197. }
  5198. var fpdargs4 []interface{}
  5199. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5200. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5201. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5202. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5203. if err != nil {
  5204. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5205. return
  5206. }
  5207. var fpdargs5 []interface{}
  5208. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5209. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5210. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5211. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5212. if err != nil {
  5213. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5214. return
  5215. }
  5216. var fpdargs6 []interface{}
  5217. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5218. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5219. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5220. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5221. if err != nil {
  5222. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5223. return
  5224. }
  5225. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5226. 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()
  5227. if err != nil {
  5228. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5229. return
  5230. }
  5231. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5232. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5233. upFpdetailList := make([]*upFpdetail, 0)
  5234. for _, newfpd := range newList {
  5235. for _, oldfpd := range oldFpdList {
  5236. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5237. var oldweight, newweight float64
  5238. if oldfpd["weight"] != nil {
  5239. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5240. }
  5241. if newfpd["weight"] != nil {
  5242. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5243. }
  5244. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5245. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5246. Old: oldweight,
  5247. New: newweight,
  5248. Times: newfpd["times"].(int64),
  5249. Ptid: newfpd["ptid"].(int64),
  5250. Fweight: fweight,
  5251. Id: oldfpd["id"].(int64),
  5252. })
  5253. break
  5254. }
  5255. }
  5256. }
  5257. // fmt.Println(dataexcel["barname"])
  5258. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5259. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5260. }
  5261. }
  5262. if !isdone {
  5263. ok++
  5264. isdone = true
  5265. }
  5266. }
  5267. for barname, v := range dataList {
  5268. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5269. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5270. if err != nil {
  5271. logs.Error(err)
  5272. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5273. return
  5274. }
  5275. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5276. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5277. if err != nil {
  5278. logs.Error(err)
  5279. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5280. return
  5281. }
  5282. updateFpdetailByBar(pastureid, barname, v)
  5283. }
  5284. }
  5285. data := make(map[string]interface{})
  5286. data["result"] = queryData
  5287. data["success"] = ok
  5288. data["err_count"] = error
  5289. appG.Response(http.StatusOK, e.SUCCESS, data)
  5290. }
  5291. type upFpdetail struct {
  5292. Old float64
  5293. New float64
  5294. Times int64
  5295. Ptid int64
  5296. Fweight float64
  5297. Id int64
  5298. // Ptsid string
  5299. }
  5300. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5301. tx := restful.Engine.NewSession()
  5302. defer tx.Close()
  5303. tx.Begin()
  5304. 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 `,
  5305. pastureid, barname).Query().List()
  5306. if err != nil {
  5307. logs.Error(err)
  5308. }
  5309. for _, fpd := range fpdList {
  5310. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5311. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5312. pastureid, fpd["id"], fpd["times"]).Query().List()
  5313. if err != nil {
  5314. tx.Rollback()
  5315. logs.Error(err)
  5316. return err
  5317. }
  5318. var lweight float64
  5319. for _, lppland := range lpplandList {
  5320. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5321. lweight += lweight1
  5322. }
  5323. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5324. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5325. if fpdweight >= ptuse && lweight == ptuse {
  5326. continue
  5327. } else {
  5328. if lweight <= fpdweight {
  5329. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5330. if err != nil {
  5331. tx.Rollback()
  5332. logs.Error(err)
  5333. return err
  5334. }
  5335. } else {
  5336. weight := lweight - fpdweight
  5337. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5338. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5339. if err != nil {
  5340. tx.Rollback()
  5341. logs.Error(err)
  5342. return err
  5343. }
  5344. for _, lppland := range lpplandList {
  5345. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5346. if weight >= lpplandlweight {
  5347. weight = weight - lpplandlweight
  5348. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5349. if err != nil {
  5350. tx.Rollback()
  5351. logs.Error(err)
  5352. return err
  5353. }
  5354. } else {
  5355. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5356. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5357. if err != nil {
  5358. tx.Rollback()
  5359. logs.Error(err)
  5360. return err
  5361. }
  5362. weight = 0
  5363. break
  5364. }
  5365. }
  5366. }
  5367. }
  5368. }
  5369. for _, list := range dataList {
  5370. ftmap := make(map[string]interface{})
  5371. ftmap["old"] = list.Old
  5372. ftmap["new"] = list.New
  5373. ftmap["times"] = list.Times
  5374. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5375. ftmap["ptsid"] = ""
  5376. // fmt.Println(ftmap)
  5377. // 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 ,
  5378. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5379. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5380. // UNION
  5381. fpdDataList, err := tx.SQL(`
  5382. 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 ,
  5383. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5384. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5385. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5386. if err != nil {
  5387. tx.Rollback()
  5388. logs.Error(err)
  5389. }
  5390. for _, fpd := range fpdDataList {
  5391. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5392. // fttype := -1
  5393. // if fpd["fttype"].(string) == "1" {
  5394. fttype := 1
  5395. // }
  5396. var fweight float64
  5397. var lweight float64
  5398. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5399. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  5400. t.maxstirfeed,t.volume * (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  5401. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5402. join tmr t on t.id = lpp.tmrid
  5403. where lppland.fpdid =?
  5404. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5405. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5406. if err != nil {
  5407. tx.Rollback()
  5408. logs.Error(err)
  5409. }
  5410. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5411. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5412. // 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
  5413. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5414. var w float64
  5415. var status int
  5416. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5417. if weight >= 0 {
  5418. continue
  5419. }
  5420. w = weight
  5421. status = 0
  5422. } else {
  5423. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5424. // continue
  5425. // }
  5426. w = weight
  5427. status = 1
  5428. }
  5429. // for _, lppland := range lpplandtl1List {
  5430. // lweight += lppland.Lweight
  5431. // }
  5432. for _, lppland := range lpplandtl1List {
  5433. lpplandInfo := new(lpplandtlInfo)
  5434. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5435. lweight = lpplandInfo.Lweight
  5436. if status == 1 {
  5437. // if w <= lppland.Lweight {
  5438. if lppland.Maxweight <= lweight {
  5439. continue
  5440. }
  5441. if w+lweight <= lppland.Maxweight {
  5442. lppland.Lweight += w
  5443. lweight += w
  5444. fweight += w
  5445. w = 0
  5446. } else {
  5447. w = w - (lppland.Maxweight - lweight)
  5448. n := (lppland.Maxweight - lweight)
  5449. lppland.Lweight = lppland.Lweight + n
  5450. lweight += n
  5451. fweight += n
  5452. }
  5453. } else {
  5454. if lppland.Lweight == 0 {
  5455. continue
  5456. }
  5457. if w+lppland.Lweight >= 0 {
  5458. lppland.Lweight = lppland.Lweight + w
  5459. lweight = lweight + w
  5460. fweight = fweight + w
  5461. w = 0
  5462. } else {
  5463. w = w + lppland.Lweight
  5464. lweight = lweight - lppland.Lweight
  5465. fweight = fweight - lppland.Lweight
  5466. lppland.Lweight = 0
  5467. }
  5468. }
  5469. if lppland.Lweight > 0 {
  5470. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5471. if err != nil {
  5472. tx.Rollback()
  5473. logs.Error(err)
  5474. return err
  5475. }
  5476. } else {
  5477. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5478. if err != nil {
  5479. tx.Rollback()
  5480. logs.Error(err)
  5481. return err
  5482. }
  5483. }
  5484. if w == 0 {
  5485. break
  5486. }
  5487. }
  5488. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5489. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5490. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5491. if err != nil {
  5492. tx.Rollback()
  5493. logs.Error(err)
  5494. }
  5495. if w == 0 {
  5496. break
  5497. }
  5498. }
  5499. }
  5500. }
  5501. err = tx.Commit()
  5502. if err != nil {
  5503. logs.Error(err)
  5504. tx.Rollback()
  5505. return err
  5506. }
  5507. now := time.Now()
  5508. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5509. if err != nil {
  5510. logs.Error(err)
  5511. return nil
  5512. }
  5513. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5514. if err != nil {
  5515. logs.Error(err)
  5516. return nil
  5517. }
  5518. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5519. if err != nil {
  5520. logs.Error(err)
  5521. return nil
  5522. }
  5523. for _, newLpplandtl1 := range newLpplandtl1List {
  5524. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5525. background,cowcount,ccountradio,lweighthis,createdate)
  5526. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5527. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5528. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5529. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5530. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5531. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5532. if err != nil {
  5533. logs.Error(err)
  5534. // appG.Response(http.StatusOK, e.ERROR, false)
  5535. return err
  5536. }
  5537. }
  5538. for _, newFpd := range newFpdDataList {
  5539. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5540. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5541. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5542. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5543. if err != nil {
  5544. logs.Error(err)
  5545. // appG.Response(http.StatusOK, e.ERROR, false)
  5546. return err
  5547. }
  5548. }
  5549. for _, newFeedp := range newFeedpList {
  5550. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5551. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5552. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5553. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5554. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5555. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5556. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5557. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5558. if err != nil {
  5559. logs.Error(err)
  5560. // appG.Response(http.StatusOK, e.ERROR, false)
  5561. return err
  5562. }
  5563. }
  5564. return nil
  5565. }
  5566. func DeleteFTdetail(c *gin.Context) {
  5567. appG := app.Gin{C: c}
  5568. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5569. fsion := gofasion.NewFasion(string(dataByte))
  5570. parammaps := fsion.Get("parammaps")
  5571. pastureid := parammaps.Get("pastureid").ValueStr()
  5572. ftid := parammaps.Get("ftid").ValueStr()
  5573. tx := restful.Engine.NewSession()
  5574. defer tx.Close()
  5575. tx.Begin()
  5576. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5577. if err != nil {
  5578. tx.Rollback()
  5579. logs.Error(err)
  5580. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5581. return
  5582. }
  5583. if parammaps.Get("type").ValueStr() == "1" {
  5584. _, err := tx.SQL(`UPDATE feedp fp
  5585. set
  5586. fp.ftweight= IFNULL(IF(
  5587. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5588. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5589. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5590. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5591. ),0),fp.feedweight = IFNULL(IF(
  5592. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5593. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5594. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5595. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5596. ),0) +ifnull(fp.supplyweight,0)
  5597. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5598. if err != nil {
  5599. tx.Rollback()
  5600. logs.Error(err)
  5601. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5602. return
  5603. }
  5604. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5605. _, err = tx.SQL(`
  5606. UPDATE fpdetail fpd
  5607. INNER JOIN feedp fp
  5608. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5609. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5610. ptuse= 0
  5611. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5612. if err != nil {
  5613. tx.Rollback()
  5614. logs.Error(err)
  5615. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5616. return
  5617. }
  5618. } else {
  5619. _, err := tx.SQL(`UPDATE feedp fp
  5620. SET
  5621. fp.supplyweight= IFNULL(IF(
  5622. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5623. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5624. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5625. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5626. ),0),fp.feedweight = IFNULL(IF(
  5627. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5628. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5629. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5630. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5631. ),0) + ifnull(fp.supplyweight,0)
  5632. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5633. if err != nil {
  5634. tx.Rollback()
  5635. logs.Error(err)
  5636. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5637. return
  5638. }
  5639. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5640. _, err = tx.SQL(`
  5641. UPDATE fpdetail fpd
  5642. INNER JOIN feedp fp
  5643. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5644. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5645. ptsrate = 0
  5646. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5647. if err != nil {
  5648. tx.Rollback()
  5649. logs.Error(err)
  5650. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5651. return
  5652. }
  5653. }
  5654. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5655. if err != nil {
  5656. tx.Rollback()
  5657. logs.Error(err)
  5658. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5659. return
  5660. }
  5661. err = tx.Commit()
  5662. if err != nil {
  5663. tx.Rollback()
  5664. logs.Error(err)
  5665. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5666. return
  5667. }
  5668. appG.Response(http.StatusOK, e.SUCCESS, true)
  5669. }
  5670. func DeleteSpillageAll(c *gin.Context) {
  5671. appG := app.Gin{C: c}
  5672. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5673. fsion := gofasion.NewFasion(string(dataByte))
  5674. parammaps := fsion.Get("parammaps")
  5675. pastureid := parammaps.Get("pastureid").ValueStr()
  5676. times := parammaps.Get("times").ValueStr()
  5677. barid := parammaps.Get("barid").ValueStr()
  5678. tx := restful.Engine.NewSession()
  5679. defer tx.Close()
  5680. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5681. if err != nil {
  5682. logs.Error(err)
  5683. appG.Response(http.StatusOK, e.ERROR, false)
  5684. return
  5685. }
  5686. now := time.Now()
  5687. for _, item := range lpplandtl1List {
  5688. go func(item map[string]interface{}) {
  5689. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5690. background,cowcount,ccountradio,lweighthis,createdate)
  5691. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5692. item["pastureid"], item["lppid"], item["barid"],
  5693. item["barname"], item["fpdid"], item["fttype"],
  5694. item["lweight"], item["sort"], item["tmrid"],
  5695. item["tmrname"], item["background"], item["cowcount"],
  5696. item["ccountradio"], item["lweighthis"], now).Execute()
  5697. if err != nil {
  5698. logs.Error(err)
  5699. appG.Response(http.StatusOK, e.ERROR, false)
  5700. return
  5701. }
  5702. }(item)
  5703. }
  5704. tx.Begin()
  5705. _, 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()
  5706. if err != nil {
  5707. tx.Rollback()
  5708. logs.Error(err)
  5709. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5710. return
  5711. }
  5712. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5713. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5714. if err != nil {
  5715. tx.Rollback()
  5716. logs.Error(err)
  5717. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5718. return
  5719. }
  5720. err = tx.Commit()
  5721. if err != nil {
  5722. tx.Rollback()
  5723. logs.Error(err)
  5724. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5725. return
  5726. }
  5727. appG.Response(http.StatusOK, e.SUCCESS, true)
  5728. }
  5729. func GetTMRListEnableTypeAll(c *gin.Context) {
  5730. appG := app.Gin{C: c}
  5731. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5732. fsion := gofasion.NewFasion(string(dataByte))
  5733. parammaps := fsion.Get("parammaps")
  5734. pastureid := parammaps.Get("pastureid").ValueStr()
  5735. tx := restful.Engine.NewSession()
  5736. defer tx.Close()
  5737. dataList, err := tx.SQL(`SELECT
  5738. eqcode,
  5739. tname,
  5740. datacaptureno,
  5741. trim(tclassid) tclassid,
  5742. concat(tname,' / ',eqcode) tmrmix,
  5743. d.label tclassname,
  5744. maxstirfeed,
  5745. remark,
  5746. tmr.enable,
  5747. TRIM(tmr.id) id,
  5748. TRIM(tmr.pastureid)pastureid
  5749. FROM
  5750. tmr
  5751. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5752. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5753. ORDER BY id DESC`, pastureid).Query().List()
  5754. if err != nil {
  5755. logs.Error(err)
  5756. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5757. return
  5758. }
  5759. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5760. if err != nil {
  5761. logs.Error(err)
  5762. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5763. return
  5764. }
  5765. var carNum int64
  5766. for _, sysopt := range sysoptData {
  5767. if sysopt["inforvalue"] == nil {
  5768. carNum = 1
  5769. } else {
  5770. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5771. }
  5772. }
  5773. id := 200
  5774. n := 0
  5775. for i := carNum; i > 0; i-- {
  5776. id++
  5777. n++
  5778. data := make(map[string]interface{}, 0)
  5779. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5780. data["tname"] = fmt.Sprintf("任意车%d", n)
  5781. data["datacaptureno"] = -2
  5782. data["tclassid"] = -2
  5783. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5784. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5785. data["maxstirfeed"] = 100000
  5786. data["remark"] = fmt.Sprintf("任意车%d", n)
  5787. data["enable"] = 1
  5788. data["id"] = fmt.Sprintf("%d", id)
  5789. data["pastureid"] = pastureid
  5790. // data := make(map[string]interface{}, 0)
  5791. // data["eqcode"] = fmt.Sprintf("AnyCar%d", n)
  5792. // data["tname"] = fmt.Sprintf("AnyCar%d", n)
  5793. // data["datacaptureno"] = -2
  5794. // data["tclassid"] = -2
  5795. // data["tmrmix"] = fmt.Sprintf("AnyCar%d", n)
  5796. // data["tclassname"] = fmt.Sprintf("AnyCar%d", n)
  5797. // data["maxstirfeed"] = 100000
  5798. // data["remark"] = fmt.Sprintf("AnyCar%d", n)
  5799. // data["enable"] = 1
  5800. // data["id"] = fmt.Sprintf("%d", id)
  5801. // data["pastureid"] = pastureid
  5802. dataList = append(dataList, data)
  5803. }
  5804. // UNION ALL
  5805. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5806. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5807. }
  5808. func GetFeedpHistory(c *gin.Context) {
  5809. appG := app.Gin{C: c}
  5810. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5811. fsion := gofasion.NewFasion(string(dataByte))
  5812. // parammaps := fsion.Get("parammaps")
  5813. bar := fsion.Get("barname").ValueStr()
  5814. startDate := fsion.Get("startDate").ValueStr()
  5815. endDate := fsion.Get("endDate").ValueStr()
  5816. tx := restful.Engine.NewSession()
  5817. defer tx.Close()
  5818. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5819. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5820. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5821. if err != nil {
  5822. logs.Error(err)
  5823. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5824. return
  5825. }
  5826. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5827. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5828. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5829. if err != nil {
  5830. logs.Error(err)
  5831. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5832. return
  5833. }
  5834. for _, feedp := range feedpList {
  5835. // LastftList, err := tx.SQL(` select tname ,id
  5836. // from feedtemplethistory where id = ?
  5837. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5838. // if err != nil {
  5839. // logs.Error(err)
  5840. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5841. // return
  5842. // }
  5843. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5844. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5845. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5846. if err != nil {
  5847. logs.Error(err)
  5848. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5849. return
  5850. }
  5851. var ftname interface{}
  5852. ftnamestatus := 0
  5853. ftname = feedp["ftname"]
  5854. var lastftid int64
  5855. if len(nextfeedpList) > 0 {
  5856. for _, ft := range nextfeedpList {
  5857. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5858. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5859. lastftid = ft["ftid"].(int64)
  5860. ftnamestatus = 1
  5861. break
  5862. }
  5863. }
  5864. }
  5865. for i, fpd := range fpdList {
  5866. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5867. fpd["weightstatus"] = 0
  5868. fpd["tratiostatus"] = 0
  5869. fpd["ftnamestatus"] = ftnamestatus
  5870. for k, fpd2 := range fpdList {
  5871. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5872. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5873. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5874. fpd["weightstatus"] = 1
  5875. }
  5876. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5877. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5878. fpd["tratiostatus"] = 1
  5879. }
  5880. break
  5881. }
  5882. }
  5883. fpd["barid"] = feedp["barid"]
  5884. fpd["barname"] = feedp["barname"]
  5885. fpd["ccount"] = feedp["ccount"]
  5886. fpd["ratio"] = feedp["ratio"]
  5887. fpd["ccountratio"] = feedp["ccountratio"]
  5888. fpd["ftid"] = feedp["ftid"]
  5889. fpd["ftname"] = ftname
  5890. fpd["ccountstatus"] = 0
  5891. fpd["ccountratiostatus"] = 0
  5892. fpd["ratiostatus"] = 0
  5893. fpd["ftnamestatus"] = 0
  5894. fpd["lastftid"] = lastftid
  5895. for _, next := range nextfeedpList {
  5896. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5897. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5898. fpd["ccountstatus"] = 1
  5899. }
  5900. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5901. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5902. fpd["ccountratiostatus"] = 1
  5903. }
  5904. if next["ratio"].(string) != fpd["ratio"].(string) {
  5905. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5906. fpd["ratiostatus"] = 1
  5907. }
  5908. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5909. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5910. // fpd["ftnamestatus"] = 1
  5911. // }
  5912. }
  5913. }
  5914. }
  5915. }
  5916. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5917. }
  5918. // func GetLpplandtl1History(c *gin.Context) {
  5919. // appG := app.Gin{C: c}
  5920. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5921. // fsion := gofasion.NewFasion(string(dataByte))
  5922. // // parammaps := fsion.Get("parammaps")
  5923. // barid := fsion.Get("barid").ValueStr()
  5924. // startDate := fsion.Get("startDate").ValueStr()
  5925. // endDate := fsion.Get("endDate").ValueStr()
  5926. // tx := restful.Engine.NewSession()
  5927. // defer tx.Close()
  5928. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5929. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5930. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5931. // // if err != nil {
  5932. // // logs.Error(err)
  5933. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5934. // // return
  5935. // // }
  5936. // // for _, feedp := range feedpList {
  5937. // // fmt.Println(feedp)
  5938. // // for i, fpd := range fpdList {
  5939. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5940. // // for k, fpd2 := range fpdList {
  5941. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5942. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5943. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5944. // // }
  5945. // // break
  5946. // // }
  5947. // // }
  5948. // // fpd["barid"] = feedp["barid"]
  5949. // // fpd["barname"] = feedp["barname"]
  5950. // // fpd["ccount"] = feedp["ccount"]
  5951. // // fpd["ratio"] = feedp["ratio"]
  5952. // // fpd["ccountratio"] = feedp["ccountratio"]
  5953. // // fpd["ftid"] = feedp["ftid"]
  5954. // // fpd["ftname"] = feedp["ftname"]
  5955. // // }
  5956. // // }
  5957. // // }
  5958. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5959. // }
  5960. func GetRemind(c *gin.Context) {
  5961. appG := app.Gin{C: c}
  5962. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5963. fsion := gofasion.NewFasion(string(dataByte))
  5964. parammaps := fsion.Get("parammaps")
  5965. pastureid := parammaps.Get("pastureid").ValueStr()
  5966. tx := restful.Engine.NewSession()
  5967. defer tx.Close()
  5968. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5969. if err != nil {
  5970. logs.Error(err)
  5971. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5972. return
  5973. }
  5974. // pastureid = "3"
  5975. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5976. if err != nil {
  5977. logs.Error(err)
  5978. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5979. return
  5980. }
  5981. defer resp.Body.Close()
  5982. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5983. buf.ReadFrom(resp.Body)
  5984. fmt.Println(string(buf.Bytes()))
  5985. respMap := make(map[string]interface{}, 0)
  5986. err = json.Unmarshal(buf.Bytes(), &respMap)
  5987. if err != nil {
  5988. logs.Error(err)
  5989. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5990. return
  5991. }
  5992. for _, data := range dataList {
  5993. r := make(map[string]interface{}, 0)
  5994. r["sys_name"] = ""
  5995. r["service_id"] = ""
  5996. r["pasture_id"] = ""
  5997. r["type_name"] = ""
  5998. r["remind_type_id"] = ""
  5999. r["remind_type"] = ""
  6000. r["push_date"] = ""
  6001. r["push_time"] = ""
  6002. r["interval_time"] = ""
  6003. r["push_limit"] = ""
  6004. r["template_id"] = ""
  6005. r["roles_id"] = ""
  6006. r["users_id"] = ""
  6007. r["date_type"] = ""
  6008. r["cycle_type"] = ""
  6009. data["data"] = r
  6010. for _, resp := range respMap["data"].([]interface{}) {
  6011. resp1 := resp.(map[string]interface{})
  6012. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  6013. if resp1["push_time"] == nil {
  6014. resp1["push_time"] = ""
  6015. }
  6016. data["data"] = resp1
  6017. break
  6018. }
  6019. }
  6020. }
  6021. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  6022. }
  6023. type NoticeMsgtype struct {
  6024. SysName string `json:"sys_name"`
  6025. PastureId int64 `json:"pasture_id"`
  6026. ServiceId int64 `json:"service_id"`
  6027. TypeName string `json:"type_name"`
  6028. RemindType int64 `json:"remind_type"`
  6029. PushDate int64 `json:"push_date"`
  6030. PushTime string `json:"push_time"`
  6031. IntervalTime int64 `json:"interval_time"`
  6032. PushLimit int64 `json:"push_limit"`
  6033. TemplateId string `json:"template_id"`
  6034. UsersId string `json:"users_id"`
  6035. DateType int64 `json:"date_type"`
  6036. CycleType int64 `json:"cycle_type"`
  6037. DelayTime int64 `json:"delay_time"`
  6038. Status int64 `json:"status"`
  6039. }
  6040. func UpdateRemind(c *gin.Context) {
  6041. appG := app.Gin{C: c}
  6042. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6043. parammaps := gofasion.NewFasion(string(dataByte))
  6044. // parammaps := fsion.Get("parammaps")
  6045. // user := parammaps.Get("user").ValueStr()
  6046. id := parammaps.Get("id").ValueInt64()
  6047. noticeMsgtype := new(NoticeMsgtype)
  6048. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  6049. noticeMsgtype.ServiceId = id
  6050. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  6051. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  6052. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  6053. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  6054. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  6055. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  6056. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  6057. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  6058. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  6059. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  6060. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  6061. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  6062. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  6063. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  6064. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  6065. //TODO
  6066. noticeMsgtype.SysName = "tmrWatch"
  6067. userList := parammaps.Get("user").Array()
  6068. var userstr []string
  6069. for _, user := range userList {
  6070. userstr = append(userstr, user.ValueStr())
  6071. }
  6072. tx := restful.Engine.NewSession()
  6073. defer tx.Close()
  6074. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  6075. if err != nil {
  6076. logs.Error(err)
  6077. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6078. return
  6079. }
  6080. // var jsonStr = []byte(noticeMsgtype
  6081. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  6082. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  6083. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  6084. req.Header.Set("Content-Type", "application/json")
  6085. client := &http.Client{}
  6086. resp, err := client.Do(req)
  6087. if err != nil {
  6088. logs.Error(err)
  6089. }
  6090. defer resp.Body.Close()
  6091. body, _ := ioutil.ReadAll(resp.Body)
  6092. fmt.Println("response Body:", string(body))
  6093. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  6094. if err != nil {
  6095. logs.Error(err)
  6096. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6097. return
  6098. }
  6099. defer getresp.Body.Close()
  6100. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6101. buf.ReadFrom(getresp.Body)
  6102. // fmt.Println(string(buf.Bytes()))
  6103. respMap := make(map[string]interface{}, 0)
  6104. err = json.Unmarshal(buf.Bytes(), &respMap)
  6105. if err != nil {
  6106. logs.Error(err)
  6107. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6108. return
  6109. }
  6110. for _, resp := range respMap["data"].([]interface{}) {
  6111. resp1 := resp.(map[string]interface{})
  6112. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6113. if err != nil {
  6114. logs.Error(err)
  6115. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6116. return
  6117. }
  6118. }
  6119. appG.Response(http.StatusOK, e.SUCCESS, true)
  6120. }
  6121. func GetSpillageallHistory(c *gin.Context) {
  6122. appG := app.Gin{C: c}
  6123. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6124. parammaps := gofasion.NewFasion(string(dataByte))
  6125. barname := parammaps.Get("barname").ValueStr()
  6126. pastureid := parammaps.Get("pastureid").ValueStr()
  6127. startdate := parammaps.Get("startDate").ValueStr()
  6128. enddate := parammaps.Get("endDate").ValueStr()
  6129. tx := restful.Engine.NewSession()
  6130. defer tx.Close()
  6131. 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
  6132. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6133. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6134. if err != nil {
  6135. logs.Error(err)
  6136. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6137. return
  6138. }
  6139. respMap := make([]map[string]interface{}, 0)
  6140. data := make(map[interface{}]interface{})
  6141. for _, history := range historyList {
  6142. data[history["createdate"]] = history["createdate"]
  6143. }
  6144. createList := []string{}
  6145. for _, v := range data {
  6146. createList = append(createList, v.(string))
  6147. }
  6148. // sort.Sort()
  6149. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6150. sort.Slice(createList, func(i, j int) bool {
  6151. return createList[i] > createList[j]
  6152. })
  6153. for _, v := range createList {
  6154. a := make(map[string]interface{})
  6155. a["createdate"] = data[v]
  6156. // createList = append(createList, v.(string))
  6157. respMap = append(respMap, a)
  6158. }
  6159. number := 0
  6160. dataMap := make([]interface{}, 0)
  6161. for k, resp := range respMap {
  6162. createdate := resp["createdate"].(string)
  6163. var nextcreatedate string
  6164. if len(respMap) > k+1 {
  6165. nextcreatedate = respMap[k+1]["createdate"].(string)
  6166. }
  6167. // dataList := make(map[string][]interface{})
  6168. // list := make(map[string]interface{})
  6169. times := make(map[interface{}]int)
  6170. for _, history := range historyList {
  6171. // List := make(map[interface{}][]interface{})
  6172. i := 0
  6173. if history["createdate"].(string) == createdate {
  6174. times[history["times"]]++
  6175. data := make(map[string]interface{})
  6176. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6177. // exist := false
  6178. if nextcreatedate != "" {
  6179. for _, history1 := range historyList {
  6180. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6181. history1["times"].(int64) == history["times"].(int64) {
  6182. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6183. break
  6184. // exist = true
  6185. }
  6186. }
  6187. }
  6188. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6189. i++
  6190. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6191. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6192. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6193. // resp["times"] = history["times"]
  6194. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6195. data1 := make(map[string]interface{})
  6196. data1["times"] = history["times"]
  6197. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6198. data1["createdate"] = resp["createdate"]
  6199. // fmt.Println(dataList)
  6200. dataMap = append(dataMap, data1)
  6201. }
  6202. if i > number {
  6203. number = i
  6204. }
  6205. // respMap = append(respMap, dataList)
  6206. }
  6207. // for k, data := range dataList {
  6208. // resp[k] = data
  6209. // }
  6210. // resp["data"] = dataList
  6211. }
  6212. // resp := make(map[string]interface{})
  6213. // sort.Strings(createList)
  6214. //
  6215. // for _, create := range createList {
  6216. // for _, r := range respMap {
  6217. // if create == r["createdate"].(string) {
  6218. // resp[create] = r
  6219. // break
  6220. // }
  6221. // }
  6222. // }
  6223. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6224. var trainsList []interface{}
  6225. for i := 0; i < number; i++ {
  6226. trains := make(map[string]interface{})
  6227. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6228. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6229. trainsList = append(trainsList, trains)
  6230. }
  6231. respdata := make(map[string]interface{})
  6232. respdata["data"] = dataMap
  6233. respdata["trains"] = trainsList
  6234. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6235. }
  6236. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6237. appG := app.Gin{C: c}
  6238. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6239. parammaps := gofasion.NewFasion(string(dataByte))
  6240. ftid := parammaps.Get("ftid").ValueInt64()
  6241. lastftid := parammaps.Get("lastftid").ValueInt64()
  6242. pastureid := parammaps.Get("pastureid").ValueInt64()
  6243. // createdate := parammaps.Get("createdate").ValueStr()
  6244. tx := restful.Engine.NewSession()
  6245. defer tx.Close()
  6246. data := make(map[string]interface{})
  6247. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6248. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6249. if err != nil {
  6250. logs.Error(err)
  6251. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6252. return
  6253. }
  6254. feedtemplet := make(map[string]interface{})
  6255. for _, f := range feedtempletList {
  6256. feedtemplet = f
  6257. }
  6258. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  6259. if err != nil {
  6260. logs.Error(err)
  6261. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6262. return
  6263. }
  6264. feedtemplet["fit"] = fitList
  6265. data["current"] = feedtemplet
  6266. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6267. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6268. if err != nil {
  6269. logs.Error(err)
  6270. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6271. return
  6272. }
  6273. lastfeedtemplet := make(map[string]interface{})
  6274. for _, f := range lastfeedtempletList {
  6275. lastfeedtemplet = f
  6276. }
  6277. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  6278. if err != nil {
  6279. logs.Error(err)
  6280. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6281. return
  6282. }
  6283. lastfeedtemplet["fit"] = lastfitList
  6284. data["last"] = lastfeedtemplet
  6285. appG.Response(http.StatusOK, e.SUCCESS, data)
  6286. }
  6287. func GetFeedtempletHistory(c *gin.Context) {
  6288. appG := app.Gin{C: c}
  6289. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6290. parammaps := gofasion.NewFasion(string(dataByte))
  6291. ftid := parammaps.Get("ftid").ValueStr()
  6292. pastureid := parammaps.Get("pastureid").ValueInt64()
  6293. start := parammaps.Get("startdate").ValueStr()
  6294. end := parammaps.Get("enddate").ValueStr()
  6295. tx := restful.Engine.NewSession()
  6296. defer tx.Close()
  6297. 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 ?
  6298. and id = ? and pastureid = ? order by createdate desc `,
  6299. start, end, ftid, pastureid).Query().List()
  6300. if err != nil {
  6301. logs.Error(err)
  6302. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6303. return
  6304. }
  6305. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6306. ftid, pastureid).Query().List()
  6307. if err != nil {
  6308. logs.Error(err)
  6309. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6310. return
  6311. }
  6312. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6313. for i, ft := range ftList {
  6314. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6315. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6316. (select empname from user where id = fit.userId) empname,
  6317. 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
  6318. where fit.fitid = ?
  6319. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6320. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6321. if err != nil {
  6322. logs.Error(err)
  6323. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6324. return
  6325. }
  6326. ft["createdate"] = ft["createdate1"]
  6327. // data["tname"] = ft["tname"]
  6328. // data["tcode"] = ft["tcode"]
  6329. // data["tcolor"] = ft["tcolor"]
  6330. // data["fttype"] = ft["fttype"]
  6331. // data["ccname"] = ft["ccname"]
  6332. // data["source"] = ft["source"]
  6333. // data["version"] = ft["version"]
  6334. // data["remark"] = ft["remark"]
  6335. for n, ft2 := range ftList {
  6336. if i < n {
  6337. if ft["tname"].(string) != ft2["tname"].(string) {
  6338. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6339. }
  6340. if _, ok := ft["tcode"]; ok {
  6341. if _, ok := ft2["tcode"]; ok {
  6342. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6343. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6344. }
  6345. }
  6346. }
  6347. if _, ok := ft["tcolor"]; ok {
  6348. if _, ok := ft2["tcolor"]; ok {
  6349. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6350. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6351. }
  6352. }
  6353. }
  6354. if _, ok := ft["fttype"]; ok {
  6355. if _, ok := ft2["fttype"]; ok {
  6356. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6357. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6358. }
  6359. }
  6360. }
  6361. if _, ok := ft["ccname"]; ok {
  6362. if _, ok := ft2["ccname"]; ok {
  6363. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6364. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6365. }
  6366. }
  6367. }
  6368. if _, ok := ft["source"]; ok {
  6369. if _, ok := ft2["source"]; ok {
  6370. if ft["source"].(string) != ft2["source"].(string) {
  6371. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6372. }
  6373. }
  6374. }
  6375. if _, ok := ft["version"]; ok {
  6376. if _, ok := ft2["version"]; ok {
  6377. if ft["version"].(int64) != ft2["version"].(int64) {
  6378. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6379. }
  6380. }
  6381. }
  6382. if _, ok := ft["remark"]; ok {
  6383. if _, ok := ft2["remark"]; ok {
  6384. if ft["remark"].(string) != ft2["remark"].(string) {
  6385. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6386. }
  6387. }
  6388. }
  6389. break
  6390. }
  6391. }
  6392. dataList := make([]map[string]interface{}, 0)
  6393. if len(fithisList) > 0 {
  6394. for _, fit := range fithisList {
  6395. data := make(map[string]interface{})
  6396. data["feedgroup"] = fit["feedgroup"]
  6397. data["fname"] = fit["fname"]
  6398. data["empname"] = fit["empname"]
  6399. if fit["Eweight"] != nil {
  6400. if fit["Eweight"].(string) != fit["weight"].(string) {
  6401. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6402. } else {
  6403. data["fweight"] = fit["Eweight"]
  6404. }
  6405. data["fweightstatus"] = 1
  6406. } else {
  6407. data["fweight"] = fit["weight"]
  6408. data["fweightstatus"] = 0
  6409. }
  6410. data["autosecond"] = fit["autosecond"]
  6411. // data["tname"] = ft["tname"]
  6412. // data["tcode"] = ft["tcode"]
  6413. // data["tcolor"] = ft["tcolor"]
  6414. // data["fttype"] = ft["fttype"]
  6415. // data["ccname"] = ft["ccname"]
  6416. // data["source"] = ft["source"]
  6417. // data["version"] = ft["version"]
  6418. // data["remark"] = ft["remark"]
  6419. // data["createdate"] = ft["createdate1"]
  6420. // ft["fit"] = data
  6421. dataList = append(dataList, data)
  6422. }
  6423. } else {
  6424. for _, fit := range ftdetailList {
  6425. data := make(map[string]interface{})
  6426. data["feedgroup"] = fit["feedgroup"]
  6427. data["fname"] = fit["fname"]
  6428. // if fit["Eweight"] != nil {
  6429. // data["weight"] = fit["Eweight"]
  6430. // } else {
  6431. data["fweight"] = fit["fweight"]
  6432. // }
  6433. data["autosecond"] = fit["autosecond"]
  6434. // ft["fit"] = data
  6435. dataList = append(dataList, data)
  6436. }
  6437. }
  6438. ft["fit"] = dataList
  6439. }
  6440. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6441. }
  6442. func UpdateMaterialTMR(c *gin.Context) {
  6443. appG := app.Gin{C: c}
  6444. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6445. parammaps := gofasion.NewFasion(string(dataByte))
  6446. tmrid := parammaps.Get("tmrid").ValueStr()
  6447. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6448. lppid := parammaps.Get("lppid").ValueStr()
  6449. times := parammaps.Get("times").ValueStr()
  6450. pastureid := parammaps.Get("pastureid").ValueStr()
  6451. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6452. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6453. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6454. tx := restful.Engine.NewSession()
  6455. defer tx.Close()
  6456. tx.Begin()
  6457. if tmrid != "1000" {
  6458. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6459. if err != nil {
  6460. logs.Error(err)
  6461. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6462. return
  6463. }
  6464. var maxstirfeed float64
  6465. for _, tmr := range tmrList {
  6466. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6467. }
  6468. if status == 0 {
  6469. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6470. if err != nil {
  6471. tx.Rollback()
  6472. logs.Error(err)
  6473. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6474. return
  6475. }
  6476. var lweight float64
  6477. for _, item := range lpplandtl1List {
  6478. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6479. lweight += fl
  6480. }
  6481. if lweight > maxstirfeed {
  6482. lweight = lweight - maxstirfeed
  6483. } else {
  6484. lweight = 0
  6485. }
  6486. if lweight > 0 {
  6487. lweight1 := lweight / float64(len(lpplandtl1List))
  6488. number := 0
  6489. for _, item := range lpplandtl1List {
  6490. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6491. if lweight1 >= fl {
  6492. number++
  6493. }
  6494. }
  6495. lweight := lweight / float64((len(lpplandtl1List) - number))
  6496. for _, item := range lpplandtl1List {
  6497. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6498. if lweight1 >= fl {
  6499. continue
  6500. }
  6501. if tmrtype == "1" {
  6502. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6503. if err != nil {
  6504. tx.Rollback()
  6505. logs.Error(err)
  6506. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6507. return
  6508. }
  6509. } else if tmrtype == "2" {
  6510. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6511. if err != nil {
  6512. tx.Rollback()
  6513. logs.Error(err)
  6514. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6515. return
  6516. }
  6517. }
  6518. if item["fttype"].(int64) == 0 {
  6519. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6520. if err != nil {
  6521. tx.Rollback()
  6522. logs.Error(err)
  6523. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6524. return
  6525. }
  6526. } else {
  6527. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6528. if err != nil {
  6529. tx.Rollback()
  6530. logs.Error(err)
  6531. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6532. return
  6533. }
  6534. }
  6535. }
  6536. } else {
  6537. for _, item := range lpplandtl1List {
  6538. // 自走式
  6539. if tmrtype == "1" {
  6540. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6541. if err != nil {
  6542. logs.Error(err)
  6543. tx.Rollback()
  6544. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6545. return
  6546. }
  6547. } else if tmrtype == "2" {
  6548. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6549. if err != nil {
  6550. logs.Error(err)
  6551. tx.Rollback()
  6552. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6553. return
  6554. }
  6555. }
  6556. }
  6557. }
  6558. } else if status == 1 {
  6559. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6560. if err != nil {
  6561. logs.Error(err)
  6562. tx.Rollback()
  6563. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6564. return
  6565. }
  6566. var lweight float64
  6567. for _, item := range lpplandtl1List {
  6568. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6569. lweight += fl
  6570. }
  6571. if lweight > maxstirfeed {
  6572. lweight = lweight - maxstirfeed
  6573. } else {
  6574. lweight = 0
  6575. }
  6576. for _, item := range lpplandtl1List {
  6577. if lweight > 0 {
  6578. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6579. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6580. if fl >= lweight {
  6581. item["lweight"] = fl - lweight
  6582. lweight = 0
  6583. if tmrtype == "1" {
  6584. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6585. if err != nil {
  6586. logs.Error(err)
  6587. tx.Rollback()
  6588. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6589. return
  6590. }
  6591. } else if tmrtype == "2" {
  6592. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6593. if err != nil {
  6594. logs.Error(err)
  6595. tx.Rollback()
  6596. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6597. return
  6598. }
  6599. }
  6600. if item["fttype"].(int64) == 0 {
  6601. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6602. if err != nil {
  6603. logs.Error(err)
  6604. tx.Rollback()
  6605. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6606. return
  6607. }
  6608. } else {
  6609. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6610. if err != nil {
  6611. logs.Error(err)
  6612. tx.Rollback()
  6613. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6614. return
  6615. }
  6616. }
  6617. } else {
  6618. lweight = lweight - fl
  6619. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6620. if err != nil {
  6621. logs.Error(err)
  6622. tx.Rollback()
  6623. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6624. return
  6625. }
  6626. if item["fttype"].(int64) == 0 {
  6627. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6628. if err != nil {
  6629. logs.Error(err)
  6630. tx.Rollback()
  6631. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6632. return
  6633. }
  6634. } else {
  6635. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6636. if err != nil {
  6637. logs.Error(err)
  6638. tx.Rollback()
  6639. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6640. return
  6641. }
  6642. }
  6643. }
  6644. } else {
  6645. // 自走式
  6646. if tmrtype == "1" {
  6647. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6648. if err != nil {
  6649. logs.Error(err)
  6650. tx.Rollback()
  6651. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6652. return
  6653. }
  6654. } else if tmrtype == "2" {
  6655. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6656. if err != nil {
  6657. logs.Error(err)
  6658. tx.Rollback()
  6659. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6660. return
  6661. }
  6662. }
  6663. }
  6664. }
  6665. } else {
  6666. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6667. if err != nil {
  6668. logs.Error(err)
  6669. tx.Rollback()
  6670. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6671. return
  6672. }
  6673. for _, item := range lpplandtl1List {
  6674. if item["fttype"].(int64) == 0 {
  6675. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6676. if err != nil {
  6677. logs.Error(err)
  6678. tx.Rollback()
  6679. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6680. return
  6681. }
  6682. } else {
  6683. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6684. if err != nil {
  6685. logs.Error(err)
  6686. tx.Rollback()
  6687. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6688. return
  6689. }
  6690. }
  6691. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6692. if err != nil {
  6693. logs.Error(err)
  6694. tx.Rollback()
  6695. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6696. return
  6697. }
  6698. }
  6699. }
  6700. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6701. if err != nil {
  6702. logs.Error(err)
  6703. tx.Rollback()
  6704. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6705. return
  6706. }
  6707. } else {
  6708. if status == 2 {
  6709. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6710. if err != nil {
  6711. logs.Error(err)
  6712. tx.Rollback()
  6713. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6714. return
  6715. }
  6716. for _, item := range lpplandtl1List {
  6717. if item["fttype"].(int64) == 0 {
  6718. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6719. if err != nil {
  6720. logs.Error(err)
  6721. tx.Rollback()
  6722. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6723. return
  6724. }
  6725. } else {
  6726. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6727. if err != nil {
  6728. logs.Error(err)
  6729. tx.Rollback()
  6730. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6731. return
  6732. }
  6733. }
  6734. }
  6735. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6736. if err != nil {
  6737. logs.Error(err)
  6738. tx.Rollback()
  6739. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6740. return
  6741. }
  6742. } else {
  6743. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6744. if err != nil {
  6745. logs.Error(err)
  6746. tx.Rollback()
  6747. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6748. return
  6749. }
  6750. }
  6751. }
  6752. err := tx.Commit()
  6753. if err != nil {
  6754. logs.Error(err)
  6755. tx.Rollback()
  6756. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6757. return
  6758. }
  6759. appG.Response(http.StatusOK, e.SUCCESS, true)
  6760. }
  6761. func UpdateMaterialTMRDate(c *gin.Context) {
  6762. appG := app.Gin{C: c}
  6763. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6764. parammaps := gofasion.NewFasion(string(dataByte))
  6765. tmrid := parammaps.Get("tmrid").ValueStr()
  6766. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6767. lppid := parammaps.Get("lppid").ValueStr()
  6768. times := parammaps.Get("times").ValueStr()
  6769. pastureid := parammaps.Get("pastureid").ValueStr()
  6770. date := parammaps.Get("date").ValueStr()
  6771. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6772. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6773. tx := restful.Engine.NewSession()
  6774. defer tx.Close()
  6775. tx.Begin()
  6776. if tmrid != "1000" {
  6777. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6778. if err != nil {
  6779. logs.Error(err)
  6780. tx.Rollback()
  6781. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6782. return
  6783. }
  6784. var maxstirfeed float64
  6785. for _, tmr := range tmrList {
  6786. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6787. }
  6788. if status == 0 {
  6789. 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()
  6790. if err != nil {
  6791. logs.Error(err)
  6792. tx.Rollback()
  6793. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6794. return
  6795. }
  6796. var lweight float64
  6797. for _, item := range lpplandtl1List {
  6798. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6799. lweight += fl
  6800. }
  6801. if lweight > maxstirfeed {
  6802. lweight = lweight - maxstirfeed
  6803. } else {
  6804. lweight = 0
  6805. }
  6806. if lweight > 0 {
  6807. lweight1 := lweight / float64(len(lpplandtl1List))
  6808. number := 0
  6809. for _, item := range lpplandtl1List {
  6810. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6811. if lweight1 >= fl {
  6812. number++
  6813. }
  6814. }
  6815. lweight := lweight / float64((len(lpplandtl1List) - number))
  6816. for _, item := range lpplandtl1List {
  6817. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6818. if lweight1 >= fl {
  6819. continue
  6820. }
  6821. if tmrtype == "1" {
  6822. _, 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()
  6823. if err != nil {
  6824. logs.Error(err)
  6825. tx.Rollback()
  6826. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6827. return
  6828. }
  6829. } else if tmrtype == "2" {
  6830. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6831. if err != nil {
  6832. logs.Error(err)
  6833. tx.Rollback()
  6834. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6835. return
  6836. }
  6837. }
  6838. if item["fttype"].(int64) == 0 {
  6839. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6840. if err != nil {
  6841. logs.Error(err)
  6842. tx.Rollback()
  6843. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6844. return
  6845. }
  6846. } else {
  6847. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6848. if err != nil {
  6849. logs.Error(err)
  6850. tx.Rollback()
  6851. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6852. return
  6853. }
  6854. }
  6855. }
  6856. } else {
  6857. for _, item := range lpplandtl1List {
  6858. // 自走式
  6859. if tmrtype == "1" {
  6860. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6861. if err != nil {
  6862. logs.Error(err)
  6863. tx.Rollback()
  6864. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6865. return
  6866. }
  6867. } else if tmrtype == "2" {
  6868. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6869. if err != nil {
  6870. logs.Error(err)
  6871. tx.Rollback()
  6872. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6873. return
  6874. }
  6875. }
  6876. }
  6877. }
  6878. } else if status == 1 {
  6879. 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()
  6880. if err != nil {
  6881. logs.Error(err)
  6882. tx.Rollback()
  6883. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6884. return
  6885. }
  6886. var lweight float64
  6887. for _, item := range lpplandtl1List {
  6888. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6889. lweight += fl
  6890. }
  6891. if lweight > maxstirfeed {
  6892. lweight = lweight - maxstirfeed
  6893. } else {
  6894. lweight = 0
  6895. }
  6896. for _, item := range lpplandtl1List {
  6897. if lweight > 0 {
  6898. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6899. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6900. if fl >= lweight {
  6901. item["lweight"] = fl - lweight
  6902. lweight = 0
  6903. if tmrtype == "1" {
  6904. _, 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()
  6905. if err != nil {
  6906. logs.Error(err)
  6907. tx.Rollback()
  6908. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6909. return
  6910. }
  6911. } else if tmrtype == "2" {
  6912. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6913. if err != nil {
  6914. logs.Error(err)
  6915. tx.Rollback()
  6916. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6917. return
  6918. }
  6919. }
  6920. if item["fttype"].(int64) == 0 {
  6921. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6922. if err != nil {
  6923. logs.Error(err)
  6924. tx.Rollback()
  6925. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6926. return
  6927. }
  6928. } else {
  6929. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6930. if err != nil {
  6931. logs.Error(err)
  6932. tx.Rollback()
  6933. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6934. return
  6935. }
  6936. }
  6937. } else {
  6938. lweight = lweight - fl
  6939. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6940. if err != nil {
  6941. logs.Error(err)
  6942. tx.Rollback()
  6943. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6944. return
  6945. }
  6946. if item["fttype"].(int64) == 0 {
  6947. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6948. if err != nil {
  6949. logs.Error(err)
  6950. tx.Rollback()
  6951. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6952. return
  6953. }
  6954. } else {
  6955. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6956. if err != nil {
  6957. logs.Error(err)
  6958. tx.Rollback()
  6959. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6960. return
  6961. }
  6962. }
  6963. }
  6964. } else {
  6965. // 自走式
  6966. if tmrtype == "1" {
  6967. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6968. if err != nil {
  6969. logs.Error(err)
  6970. tx.Rollback()
  6971. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6972. return
  6973. }
  6974. } else if tmrtype == "2" {
  6975. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6976. if err != nil {
  6977. logs.Error(err)
  6978. tx.Rollback()
  6979. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6980. return
  6981. }
  6982. }
  6983. }
  6984. }
  6985. } else {
  6986. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6987. if err != nil {
  6988. logs.Error(err)
  6989. tx.Rollback()
  6990. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6991. return
  6992. }
  6993. for _, item := range lpplandtl1List {
  6994. if item["fttype"].(int64) == 0 {
  6995. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6996. if err != nil {
  6997. logs.Error(err)
  6998. tx.Rollback()
  6999. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7000. return
  7001. }
  7002. } else {
  7003. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7004. if err != nil {
  7005. logs.Error(err)
  7006. tx.Rollback()
  7007. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7008. return
  7009. }
  7010. }
  7011. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  7012. if err != nil {
  7013. logs.Error(err)
  7014. tx.Rollback()
  7015. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7016. return
  7017. }
  7018. }
  7019. }
  7020. _, 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()
  7021. if err != nil {
  7022. logs.Error(err)
  7023. tx.Rollback()
  7024. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7025. return
  7026. }
  7027. } else {
  7028. if status == 2 {
  7029. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  7030. if err != nil {
  7031. logs.Error(err)
  7032. tx.Rollback()
  7033. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7034. return
  7035. }
  7036. for _, item := range lpplandtl1List {
  7037. if item["fttype"].(int64) == 0 {
  7038. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7039. if err != nil {
  7040. logs.Error(err)
  7041. tx.Rollback()
  7042. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7043. return
  7044. }
  7045. } else {
  7046. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7047. if err != nil {
  7048. logs.Error(err)
  7049. tx.Rollback()
  7050. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7051. return
  7052. }
  7053. }
  7054. }
  7055. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  7056. if err != nil {
  7057. logs.Error(err)
  7058. tx.Rollback()
  7059. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7060. return
  7061. }
  7062. } else {
  7063. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  7064. if err != nil {
  7065. logs.Error(err)
  7066. tx.Rollback()
  7067. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7068. return
  7069. }
  7070. }
  7071. }
  7072. err := tx.Commit()
  7073. if err != nil {
  7074. logs.Error(err)
  7075. tx.Rollback()
  7076. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7077. return
  7078. }
  7079. appG.Response(http.StatusOK, e.SUCCESS, true)
  7080. }
  7081. func Decimal(value float64) float64 {
  7082. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  7083. return value
  7084. }
  7085. func UpdateDailyData(c *gin.Context) {
  7086. appG := app.Gin{C: c}
  7087. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7088. parammaps := gofasion.NewFasion(string(dataByte))
  7089. pid := parammaps.Get("pid").ValueDefaultStr("0")
  7090. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  7091. sort := parammaps.Get("sort").ValueDefaultStr("0")
  7092. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  7093. date := parammaps.Get("date").ValueStr()
  7094. tx := restful.Engine.NewSession()
  7095. defer tx.Close()
  7096. 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()
  7097. if err != nil {
  7098. logs.Error("UpdateDailyData-error-0:", err)
  7099. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7100. return
  7101. }
  7102. if count > 0 {
  7103. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7104. return
  7105. }
  7106. tx.Begin()
  7107. if location == 0 {
  7108. fid := parammaps.Get("fid").ValueStr()
  7109. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  7110. if err != nil {
  7111. logs.Error("UpdateDailyData-error-1:", err)
  7112. tx.Rollback()
  7113. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7114. return
  7115. }
  7116. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7117. if err != nil {
  7118. logs.Error("UpdateDailyData-error-1:", err)
  7119. tx.Rollback()
  7120. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7121. return
  7122. }
  7123. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7124. if err != nil {
  7125. fmt.Println("Error:", err)
  7126. return
  7127. }
  7128. actualWeight := weight - num
  7129. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7130. if err != nil {
  7131. logs.Error("UpdateDailyData-error-2:", err)
  7132. tx.Rollback()
  7133. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7134. return
  7135. }
  7136. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7137. if err != nil {
  7138. logs.Error("UpdateDailyData-error-3:", err)
  7139. tx.Rollback()
  7140. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7141. return
  7142. }
  7143. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7144. if err != nil {
  7145. logs.Error("UpdateDailyData-error-4:", err)
  7146. tx.Rollback()
  7147. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7148. return
  7149. }
  7150. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7151. if err != nil {
  7152. logs.Error("UpdateDailyData-error-5:", err)
  7153. tx.Rollback()
  7154. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7155. return
  7156. }
  7157. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7158. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7159. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7160. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7161. if err != nil {
  7162. fmt.Println("Error:", err)
  7163. return
  7164. }
  7165. // actual := actualWeight / float64(len(downloadedplanList))
  7166. for _, item := range downloadedplanList {
  7167. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7168. if err != nil {
  7169. fmt.Println("Error:", err)
  7170. return
  7171. }
  7172. actual := itemLweight / lweight * actualWeight
  7173. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7174. if err != nil {
  7175. logs.Error("UpdateDailyData-error-6:", err)
  7176. tx.Rollback()
  7177. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7178. return
  7179. }
  7180. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7181. if err != nil {
  7182. logs.Error("UpdateDailyData-error-7:", err)
  7183. tx.Rollback()
  7184. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7185. return
  7186. }
  7187. _, 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()
  7188. if err != nil {
  7189. logs.Error("UpdateDailyData-error-8:", err)
  7190. tx.Rollback()
  7191. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7192. return
  7193. }
  7194. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7195. if err != nil {
  7196. logs.Error("UpdateDailyData-error-9:", err)
  7197. tx.Rollback()
  7198. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7199. return
  7200. }
  7201. }
  7202. } else {
  7203. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7204. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7205. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7206. // if err != nil {
  7207. // fmt.Println("Error:", err)
  7208. // return
  7209. // }
  7210. for _, item := range downloadedplanList {
  7211. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7212. if err != nil {
  7213. logs.Error("UpdateDailyData-error-6:", err)
  7214. tx.Rollback()
  7215. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7216. return
  7217. }
  7218. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7219. item["lweight"], actualWeight, item["id"]).Execute()
  7220. if err != nil {
  7221. logs.Error("UpdateDailyData-error-7:", err)
  7222. tx.Rollback()
  7223. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7224. return
  7225. }
  7226. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7227. where pid = ?`, item["id"]).Execute()
  7228. if err != nil {
  7229. logs.Error("UpdateDailyData-error-8:", err)
  7230. tx.Rollback()
  7231. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7232. return
  7233. }
  7234. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7235. if err != nil {
  7236. logs.Error("UpdateDailyData-error-9:", err)
  7237. tx.Rollback()
  7238. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7239. return
  7240. }
  7241. }
  7242. }
  7243. } else {
  7244. fbarid := parammaps.Get("fbarid").ValueStr()
  7245. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7246. if err != nil {
  7247. logs.Error("UpdateDailyData-error-10:", err)
  7248. tx.Rollback()
  7249. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7250. return
  7251. }
  7252. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7253. if err != nil {
  7254. logs.Error("UpdateDailyData-error-1:", err)
  7255. tx.Rollback()
  7256. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7257. return
  7258. }
  7259. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7260. if err != nil {
  7261. fmt.Println("Error:", err)
  7262. return
  7263. }
  7264. actualWeight := weight - num
  7265. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7266. if err != nil {
  7267. logs.Error("UpdateDailyData-error-11:", err)
  7268. tx.Rollback()
  7269. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7270. return
  7271. }
  7272. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  7273. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7274. if err != nil {
  7275. logs.Error("UpdateDailyData-error-12:", err)
  7276. tx.Rollback()
  7277. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7278. return
  7279. }
  7280. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7281. where pid = ? `, pid).Execute()
  7282. if err != nil {
  7283. logs.Error("UpdateDailyData-error-13:", err)
  7284. tx.Rollback()
  7285. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7286. return
  7287. }
  7288. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7289. if err != nil {
  7290. logs.Error("UpdateDailyData-error-14:", err)
  7291. tx.Rollback()
  7292. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7293. return
  7294. }
  7295. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7296. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7297. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7298. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7299. if err != nil {
  7300. fmt.Println("Error:", err)
  7301. return
  7302. }
  7303. for _, item := range downloadedplanList {
  7304. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7305. if err != nil {
  7306. fmt.Println("Error:", err)
  7307. return
  7308. }
  7309. actual := itemLweight / lweight * actualWeight
  7310. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7311. if err != nil {
  7312. logs.Error("UpdateDailyData-error-6:", err)
  7313. tx.Rollback()
  7314. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7315. return
  7316. }
  7317. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7318. if err != nil {
  7319. logs.Error("UpdateDailyData-error-7:", err)
  7320. tx.Rollback()
  7321. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7322. return
  7323. }
  7324. _, 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()
  7325. if err != nil {
  7326. logs.Error("UpdateDailyData-error-8:", err)
  7327. tx.Rollback()
  7328. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7329. return
  7330. }
  7331. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7332. if err != nil {
  7333. logs.Error("UpdateDailyData-error-9:", err)
  7334. tx.Rollback()
  7335. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7336. return
  7337. }
  7338. }
  7339. } else {
  7340. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7341. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7342. for _, item := range downloadedplanList {
  7343. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7344. // if err != nil {
  7345. // fmt.Println("Error:", err)
  7346. // return
  7347. // }
  7348. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7349. if err != nil {
  7350. logs.Error("UpdateDailyData-error-6:", err)
  7351. tx.Rollback()
  7352. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7353. return
  7354. }
  7355. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7356. item["lweight"], actualWeight, item["id"]).Execute()
  7357. if err != nil {
  7358. logs.Error("UpdateDailyData-error-7:", err)
  7359. tx.Rollback()
  7360. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7361. return
  7362. }
  7363. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7364. where pid = ?`, item["id"]).Execute()
  7365. if err != nil {
  7366. logs.Error("UpdateDailyData-error-8:", err)
  7367. tx.Rollback()
  7368. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7369. return
  7370. }
  7371. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7372. if err != nil {
  7373. logs.Error("UpdateDailyData-error-9:", err)
  7374. tx.Rollback()
  7375. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7376. return
  7377. }
  7378. }
  7379. }
  7380. }
  7381. err = tx.Commit()
  7382. if err != nil {
  7383. logs.Error("UpdateDailyData-error-20:", err)
  7384. tx.Rollback()
  7385. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7386. return
  7387. }
  7388. appG.Response(http.StatusOK, e.SUCCESS, true)
  7389. }
  7390. func GetFormulaStatistics(c *gin.Context) {
  7391. appG := app.Gin{C: c}
  7392. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7393. parammaps := gofasion.NewFasion(string(dataByte))
  7394. startTime := parammaps.Get("startTime").ValueStr()
  7395. endTime := parammaps.Get("endTime").ValueStr()
  7396. pastureId := parammaps.Get("pastureId").ValueStr()
  7397. tx := restful.Engine.NewSession()
  7398. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7399. if err != nil {
  7400. logs.Error("GetFormulaStatistics-error-1:", err)
  7401. tx.Rollback()
  7402. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7403. return
  7404. }
  7405. var feedtemplet, dateList []string
  7406. for _, f := range feedtempletList {
  7407. feedtemplet = append(feedtemplet, f["tname"].(string))
  7408. }
  7409. layout := "2006-01-02"
  7410. // s := "2023-05-01"
  7411. // e := "2023-05-23"
  7412. start, err := time.Parse(layout, startTime)
  7413. if err != nil {
  7414. fmt.Println(err)
  7415. return
  7416. }
  7417. end, err := time.Parse(layout, endTime)
  7418. if err != nil {
  7419. fmt.Println(err)
  7420. return
  7421. }
  7422. end = end.AddDate(0, 0, 1)
  7423. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7424. dateList = append(dateList, d.Format("2006-01-02"))
  7425. }
  7426. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7427. 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= ?
  7428. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7429. if err != nil {
  7430. logs.Error("GetFormulaStatistics-error-2:", err)
  7431. tx.Rollback()
  7432. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7433. return
  7434. }
  7435. var data2 [][]interface{}
  7436. for _, f := range feedtemplet {
  7437. var data1 []interface{}
  7438. for _, date := range dateList {
  7439. exist := false
  7440. for _, item := range downloadedplanList {
  7441. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7442. data1 = append(data1, item["total"])
  7443. exist = true
  7444. break
  7445. }
  7446. }
  7447. if !exist {
  7448. data1 = append(data1, 0)
  7449. }
  7450. }
  7451. data2 = append(data2, data1)
  7452. }
  7453. //前端让加的
  7454. feedtemplet = append(feedtemplet, "")
  7455. {
  7456. var data1 []interface{}
  7457. for _, f := range dateList {
  7458. // f = f + "\n"
  7459. fmt.Println(f)
  7460. data1 = append(data1, 0)
  7461. }
  7462. data2 = append(data2, data1)
  7463. }
  7464. resp := make(map[string]interface{}, 0)
  7465. resp["xdata"] = dateList
  7466. resp["data1"] = feedtemplet
  7467. resp["data2"] = data2
  7468. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7469. }
  7470. func GetPlanData(c *gin.Context) {
  7471. appG := app.Gin{C: c}
  7472. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7473. fsion := gofasion.NewFasion(string(dataByte))
  7474. sqlnamestr := fsion.Get("name").ValueStr()
  7475. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7476. offset := fsion.Get("offset").ValueDefaultInt(0)
  7477. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7478. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7479. month := fsion.Get("month").ValueDefaultStr("map")
  7480. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7481. tx := restful.Engine.NewSession()
  7482. err := tx.Begin()
  7483. defer func() {
  7484. switch {
  7485. case err != nil:
  7486. if tx != nil {
  7487. tx.Rollback()
  7488. }
  7489. default:
  7490. if tx != nil {
  7491. err = tx.Commit()
  7492. }
  7493. }
  7494. if tx != nil {
  7495. tx.Close()
  7496. }
  7497. }()
  7498. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7499. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7500. if sql != "" {
  7501. s_params := make([]interface{}, 0)
  7502. if fsion.HasKey("parammaps") {
  7503. parammaps := fsion.Get("parammaps")
  7504. paramslist := strings.Split(p, ",")
  7505. if len(paramslist) > 0 && p != "" {
  7506. for _, value := range paramslist {
  7507. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7508. if tempv, exists := c.Get("jwt_username"); exists {
  7509. s_params = append(s_params, tempv.(string))
  7510. } else {
  7511. s_params = append(s_params, "")
  7512. }
  7513. } else {
  7514. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7515. }
  7516. }
  7517. }
  7518. }
  7519. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7520. if err != nil {
  7521. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7522. } else {
  7523. paramslist1 := strings.Split(p1, ",")
  7524. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7525. s_params1 := make([]interface{}, 0)
  7526. if len(paramslist1) > 0 && p1 != "" {
  7527. for _, v := range paramslist1 {
  7528. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7529. }
  7530. }
  7531. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7532. for _, item := range arr {
  7533. trgaddressList := []string{}
  7534. if _, ok := item["trgaddress"]; ok {
  7535. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7536. for _, str := range trgaddressList1 {
  7537. if str != "" {
  7538. trgaddressList = append(trgaddressList, str)
  7539. }
  7540. }
  7541. }
  7542. item["trgaddressList"] = trgaddressList
  7543. }
  7544. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7545. }
  7546. // var wg sync.WaitGroup
  7547. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7548. // wg.Add(1)
  7549. // go func(value map[string]interface{}) {
  7550. // defer wg.Done()
  7551. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7552. // }(value)
  7553. // }
  7554. // wg.Wait()
  7555. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7556. }
  7557. } else {
  7558. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7559. }
  7560. }
  7561. func PostPlanData(c *gin.Context) {
  7562. appG := app.Gin{C: c}
  7563. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7564. fsion := gofasion.NewFasion(string(dataByte))
  7565. logging.Info("PostRJSBData err: ", string(dataByte))
  7566. s_params := make([]interface{}, 0)
  7567. tx := restful.Engine.NewSession()
  7568. err := tx.Begin()
  7569. defer func() {
  7570. switch {
  7571. case err != nil:
  7572. if tx != nil {
  7573. tx.Rollback()
  7574. }
  7575. default:
  7576. if tx != nil {
  7577. err = tx.Commit()
  7578. }
  7579. }
  7580. if tx != nil {
  7581. tx.Close()
  7582. }
  7583. }()
  7584. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7585. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7586. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7587. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7588. if !fsion.HasKey("parammaps") {
  7589. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7590. return
  7591. }
  7592. parammaps := fsion.Get("parammaps")
  7593. // paramslist := strings.Split(p, ",")
  7594. // if len(paramslist) > 0 && p != "" {
  7595. // for _, value := range paramslist {
  7596. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7597. // }
  7598. // }
  7599. // _, err = tx.SQL(sql, s_params...).Execute()
  7600. // if err != nil {
  7601. // logging.Error("PostRJSBData err: ", err)
  7602. // msg := geterrmsg(err.Error())
  7603. // appG.Response(http.StatusOK, e.ERROR, msg)
  7604. // return
  7605. // }
  7606. s_params = make([]interface{}, 0)
  7607. paramslist := strings.Split(p1, ",")
  7608. if len(paramslist) > 0 && p1 != "" {
  7609. for _, value := range paramslist {
  7610. // if value == "ID" {
  7611. // id := parammaps.Get("ID").ValueStr()
  7612. // pastureid := parammaps.Get("pastureid").ValueStr()
  7613. // 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
  7614. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7615. // if err != nil {
  7616. // logging.Error("PostRJSBData err: ", err)
  7617. // msg := geterrmsg(err.Error())
  7618. // appG.Response(http.StatusOK, e.ERROR, msg)
  7619. // return
  7620. // }
  7621. // for _, item := range datalist {
  7622. // id = item["id"]
  7623. // }
  7624. // s_params = append(s_params, id)
  7625. // } else {
  7626. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7627. // }
  7628. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7629. }
  7630. }
  7631. _, err = tx.SQL(sql1, s_params...).Execute()
  7632. if err != nil {
  7633. logging.Error("PostRJSBData1 err: ", err)
  7634. msg := geterrmsg(err.Error())
  7635. appG.Response(http.StatusOK, e.ERROR, msg)
  7636. return
  7637. }
  7638. s_params = make([]interface{}, 0)
  7639. paramslist = strings.Split(p2, ",")
  7640. if len(paramslist) > 0 && p2 != "" {
  7641. for _, value := range paramslist {
  7642. if value == "ID" {
  7643. id := parammaps.Get("ID").ValueStr()
  7644. pastureid := parammaps.Get("pastureid").ValueStr()
  7645. 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
  7646. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7647. if err != nil {
  7648. logging.Error("PostRJSBData err: ", err)
  7649. msg := geterrmsg(err.Error())
  7650. appG.Response(http.StatusOK, e.ERROR, msg)
  7651. return
  7652. }
  7653. for _, item := range datalist {
  7654. id = item["id"]
  7655. }
  7656. s_params = append(s_params, id)
  7657. } else {
  7658. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7659. }
  7660. }
  7661. }
  7662. _, err = tx.SQL(sql2, s_params...).Execute()
  7663. if err != nil {
  7664. logging.Error("PostRJSBData2 err: ", err)
  7665. msg := geterrmsg(err.Error())
  7666. appG.Response(http.StatusOK, e.ERROR, msg)
  7667. return
  7668. }
  7669. s_params = make([]interface{}, 0)
  7670. paramslist = strings.Split(p3, ",")
  7671. if len(paramslist) > 0 && p3 != "" {
  7672. for _, value := range paramslist {
  7673. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7674. }
  7675. }
  7676. _, err = tx.SQL(sql3, s_params...).Execute()
  7677. if err != nil {
  7678. logging.Error("PostRJSBData3 err: ", err)
  7679. msg := geterrmsg(err.Error())
  7680. appG.Response(http.StatusOK, e.ERROR, msg)
  7681. return
  7682. }
  7683. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7684. }
  7685. func CheckFeedTrgaddress(c *gin.Context) {
  7686. appG := app.Gin{C: c}
  7687. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7688. fsion := gofasion.NewFasion(string(dataByte))
  7689. fclassid := fsion.Get("fclassid").ValueStr()
  7690. feedId := fsion.Get("feedId").ValueStr()
  7691. backup1 := fsion.Get("backup1").ValueStr()
  7692. backup1List := strings.Split(backup1, ",")
  7693. tx := restful.Engine.NewSession()
  7694. defer tx.Close()
  7695. // if backup1 != "" {
  7696. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7697. for _, feed := range feedList {
  7698. if feed["backup1"] == "" {
  7699. continue
  7700. }
  7701. feedbackupList := strings.Split(feed["backup1"], ",")
  7702. for _, feedbackup := range feedbackupList {
  7703. for _, backup := range backup1List {
  7704. if feedbackup == backup {
  7705. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7706. return
  7707. }
  7708. }
  7709. }
  7710. }
  7711. // }
  7712. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7713. }
  7714. func ThiGetDataByName(c *gin.Context) {
  7715. appG := app.Gin{C: c}
  7716. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7717. fsion := gofasion.NewFasion(string(dataByte))
  7718. sqlnamestr := fsion.Get("name").ValueStr()
  7719. offset := fsion.Get("offset").ValueDefaultInt(0)
  7720. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7721. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7722. tx := restful.Engine.NewSession()
  7723. err := tx.Begin()
  7724. defer func() {
  7725. switch {
  7726. case err != nil:
  7727. logging.Error("tx.Begin 事务启动失败__error:", err)
  7728. if tx != nil {
  7729. tx.Rollback()
  7730. }
  7731. default:
  7732. if tx != nil {
  7733. err = tx.Commit()
  7734. }
  7735. }
  7736. if tx != nil {
  7737. tx.Close()
  7738. }
  7739. }()
  7740. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7741. if sql != "" {
  7742. s_params := make([]interface{}, 0)
  7743. if fsion.HasKey("parammaps") {
  7744. parammaps := fsion.Get("parammaps")
  7745. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7746. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7747. }
  7748. paramslist := strings.Split(p, ",")
  7749. if len(paramslist) > 0 && p != "" {
  7750. for _, value := range paramslist {
  7751. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7752. if tempv, exists := c.Get("jwt_username"); exists {
  7753. s_params = append(s_params, tempv.(string))
  7754. } else {
  7755. s_params = append(s_params, "")
  7756. }
  7757. } else {
  7758. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7759. }
  7760. }
  7761. }
  7762. } else if fsion.HasKey("params") {
  7763. params := fsion.Get("params").Array()
  7764. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7765. for _, v_params := range params {
  7766. s_params = append(s_params, v_params.ValueStr())
  7767. }
  7768. }
  7769. if returntype == "xlsx" {
  7770. var xlsxfile *xlsx.File
  7771. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7772. //c.File("c:/dd.xlsx")
  7773. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7774. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7775. c.Header("Content-Transfer-Encoding", "binary")
  7776. _ = xlsxfile.Write(c.Writer)
  7777. } else {
  7778. if sqlnamestr == "getHomepageStr" {
  7779. parammaps := fsion.Get("parammaps")
  7780. pastureid := parammaps.Get("pastureid").ValueStr()
  7781. var montimeList []float64
  7782. var montime float64
  7783. var wg sync.WaitGroup
  7784. now := time.Now()
  7785. for i := 0; i < 30; i++ {
  7786. wg.Add(1)
  7787. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7788. go func(nowstr string) {
  7789. defer wg.Done()
  7790. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7791. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7792. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7793. montimeList = append(montimeList, m)
  7794. }(nowstr)
  7795. }
  7796. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7797. if err != nil {
  7798. logging.Error("GetDataByName err: ", err)
  7799. msg := geterrmsg(err.Error())
  7800. appG.Response(http.StatusOK, e.ERROR, msg)
  7801. }
  7802. wg.Wait()
  7803. for _, m := range montimeList {
  7804. montime += m
  7805. }
  7806. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7807. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7808. return
  7809. }
  7810. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7811. if err != nil {
  7812. logging.Error("GetDataByName err: ", err)
  7813. msg := geterrmsg(err.Error())
  7814. appG.Response(http.StatusOK, e.ERROR, msg)
  7815. } else {
  7816. if sqlnamestr == "getFeedTrgaddressList" {
  7817. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7818. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7819. trgaddressList := []string{}
  7820. for _, str := range trgaddressList1 {
  7821. if str != "" {
  7822. trgaddressList = append(trgaddressList, str)
  7823. }
  7824. }
  7825. item["trgaddressList"] = trgaddressList
  7826. }
  7827. }
  7828. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7829. }
  7830. }
  7831. } else {
  7832. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7833. }
  7834. }
  7835. // func ToggleCcount(c *gin.Context) {
  7836. // appG := app.Gin{C: c}
  7837. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7838. // fsion := gofasion.NewFasion(string(dataByte))
  7839. // // 0 实际 1 软件
  7840. // status := fsion.Get("status").ValueDefaultInt64(0)
  7841. // pastureId := fsion.Get("pastureId").ValueStr()
  7842. // tx := restful.Engine.NewSession()
  7843. // err := tx.Begin()
  7844. // defer func() {
  7845. // switch {
  7846. // case err != nil:
  7847. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7848. // if tx != nil {
  7849. // tx.Rollback()
  7850. // }
  7851. // default:
  7852. // if tx != nil {
  7853. // err = tx.Commit()
  7854. // }
  7855. // }
  7856. // if tx != nil {
  7857. // tx.Close()
  7858. // }
  7859. // }()
  7860. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7861. // if err != nil {
  7862. // logs.Error(err)
  7863. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7864. // return
  7865. // }
  7866. // for _, bar := range barList {
  7867. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7868. // if err != nil {
  7869. // logs.Error(err)
  7870. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7871. // return
  7872. // }
  7873. // if !exist {
  7874. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7875. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7876. // if err != nil {
  7877. // logs.Error(err)
  7878. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7879. // return
  7880. // }
  7881. // }
  7882. // }
  7883. // if status == 0 {
  7884. // tx.Exec(`update feedp set ccount = actualcount `)
  7885. // }else{
  7886. // tx.Exec(`update feedp set ccount = softccount `)
  7887. // }
  7888. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7889. // if err != nil {
  7890. // logs.Error(err)
  7891. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7892. // return
  7893. // }
  7894. // for _, feedpData :=range feedpList{
  7895. // var feedpargs []interface{}
  7896. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7897. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7898. // if _, ok := feedpData["ftname"]; ok {
  7899. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7900. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7901. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7902. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7903. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7904. // } else {
  7905. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7906. // }
  7907. // if _, ok := feedpData["ptsfname"]; ok {
  7908. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7909. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7910. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7911. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7912. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7913. // } else {
  7914. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7915. // }
  7916. // upFeedpSql += " where barname = ? and pastureid = ? "
  7917. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7918. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7919. // if err != nil {
  7920. // logs.Error(err)
  7921. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7922. // return
  7923. // }
  7924. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7925. // if err != nil {
  7926. // logs.Error(err)
  7927. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7928. // return
  7929. // }
  7930. // if !exist1 {
  7931. // _, 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) `,
  7932. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7933. // if err != nil {
  7934. // logs.Error(err)
  7935. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7936. // return
  7937. // }
  7938. // }
  7939. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7940. // if err != nil {
  7941. // logs.Error(err)
  7942. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7943. // return
  7944. // }
  7945. // if !exist2 {
  7946. // _, 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) `,
  7947. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7948. // if err != nil {
  7949. // logs.Error(err)
  7950. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7951. // return
  7952. // }
  7953. // }
  7954. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7955. // if err != nil {
  7956. // logs.Error(err)
  7957. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7958. // return
  7959. // }
  7960. // if !exist3 {
  7961. // _, 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) `,
  7962. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7963. // if err != nil {
  7964. // logs.Error(err)
  7965. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7966. // return
  7967. // }
  7968. // }
  7969. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7970. // if err != nil {
  7971. // logs.Error(err)
  7972. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7973. // return
  7974. // }
  7975. // if !exist4 {
  7976. // _, 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) `,
  7977. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7978. // if err != nil {
  7979. // logs.Error(err)
  7980. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7981. // return
  7982. // }
  7983. // }
  7984. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7985. // if err != nil {
  7986. // logs.Error(err)
  7987. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7988. // return
  7989. // }
  7990. // if !exist5 {
  7991. // _, 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) `,
  7992. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7993. // if err != nil {
  7994. // logs.Error(err)
  7995. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7996. // return
  7997. // }
  7998. // }
  7999. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  8000. // if err != nil {
  8001. // logs.Error(err)
  8002. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8003. // return
  8004. // }
  8005. // if !exist6 {
  8006. // _, 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) `,
  8007. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  8008. // if err != nil {
  8009. // logs.Error(err)
  8010. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8011. // return
  8012. // }
  8013. // }
  8014. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8015. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8016. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8017. // and pastureid = ? and times = ?`
  8018. // var fpdargs1 []interface{}
  8019. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8020. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8021. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8022. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8023. // if err != nil {
  8024. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8025. // return
  8026. // }
  8027. // var fpdargs2 []interface{}
  8028. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8029. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8030. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8031. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8032. // if err != nil {
  8033. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8034. // return
  8035. // }
  8036. // var fpdargs3 []interface{}
  8037. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8038. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8039. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8040. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8041. // if err != nil {
  8042. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8043. // return
  8044. // }
  8045. // var fpdargs4 []interface{}
  8046. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8047. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8048. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8049. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8050. // if err != nil {
  8051. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8052. // return
  8053. // }
  8054. // var fpdargs5 []interface{}
  8055. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8056. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8057. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8058. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8059. // if err != nil {
  8060. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8061. // return
  8062. // }
  8063. // var fpdargs6 []interface{}
  8064. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8065. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8066. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8067. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8068. // if err != nil {
  8069. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8070. // return
  8071. // }
  8072. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8073. // 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()
  8074. // if err != nil {
  8075. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8076. // return
  8077. // }
  8078. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8079. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8080. // upFpdetailList := make([]*upFpdetail, 0)
  8081. // for _, newfpd := range newList {
  8082. // for _, oldfpd := range oldFpdList {
  8083. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8084. // var oldweight, newweight float64
  8085. // if oldfpd["weight"] != nil {
  8086. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8087. // }
  8088. // if newfpd["weight"] != nil {
  8089. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8090. // }
  8091. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8092. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  8093. // Old: oldweight,
  8094. // New: newweight,
  8095. // Times: newfpd["times"].(int64),
  8096. // Ptid: newfpd["ptid"].(int64),
  8097. // Fweight: fweight,
  8098. // Id: oldfpd["id"].(int64),
  8099. // })
  8100. // break
  8101. // }
  8102. // }
  8103. // }
  8104. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8105. // }
  8106. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8107. // }
  8108. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8109. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8110. if err != nil {
  8111. return err
  8112. }
  8113. for _, item := range feedpList {
  8114. // if item["ftid"].(string) != data["ftid"].(string) {
  8115. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8116. if err != nil {
  8117. return err
  8118. }
  8119. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8120. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8121. if err != nil {
  8122. return err
  8123. }
  8124. // }
  8125. }
  8126. return nil
  8127. }
  8128. func PostPlanDatas(c *gin.Context) {
  8129. appG := app.Gin{C: c}
  8130. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8131. fsions := gofasion.NewFasion(string(dataByte))
  8132. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8133. tx := restful.Engine.NewSession()
  8134. err := tx.Begin()
  8135. defer func() {
  8136. switch {
  8137. case err != nil:
  8138. if tx != nil {
  8139. tx.Rollback()
  8140. }
  8141. default:
  8142. if tx != nil {
  8143. err = tx.Commit()
  8144. }
  8145. }
  8146. if tx != nil {
  8147. tx.Close()
  8148. }
  8149. }()
  8150. pastureId := fsions.Get("pastureid").ValueStr()
  8151. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8152. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8153. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8154. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8155. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8156. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8157. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8158. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8159. for _, parammaps := range fsions.Get("arrList").Array() {
  8160. fmt.Println(parammaps.Json())
  8161. if parammaps.Json() == "null" {
  8162. continue
  8163. }
  8164. // if !fsion.HasKey("arrList") {
  8165. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8166. // return
  8167. // continue
  8168. // }
  8169. // parammaps := fsion.Get("arrList")
  8170. s_params := make([]interface{}, 0)
  8171. // paramslist := strings.Split(p, ",")
  8172. // if len(paramslist) > 0 && p != "" {
  8173. // for _, value := range paramslist {
  8174. // if value == "pastureid" {
  8175. // s_params = append(s_params, pastureId)
  8176. // } else {
  8177. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8178. // }
  8179. // }
  8180. // }
  8181. // _, err = tx.SQL(sql, s_params...).Execute()
  8182. // if err != nil {
  8183. // logging.Error("PostRJSBData err: ", err)
  8184. // msg := geterrmsg(err.Error())
  8185. // appG.Response(http.StatusOK, e.ERROR, msg)
  8186. // return
  8187. // }
  8188. s_params = make([]interface{}, 0)
  8189. paramslist := strings.Split(p1, ",")
  8190. if len(paramslist) > 0 && p1 != "" {
  8191. for _, value := range paramslist {
  8192. // if value == "ID" {
  8193. // id := parammaps.Get("ID").ValueStr()
  8194. // pastureid := parammaps.Get("pastureid").ValueStr()
  8195. // 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
  8196. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8197. // if err != nil {
  8198. // logging.Error("PostRJSBData err: ", err)
  8199. // msg := geterrmsg(err.Error())
  8200. // appG.Response(http.StatusOK, e.ERROR, msg)
  8201. // return
  8202. // }
  8203. // for _, item := range datalist {
  8204. // id = item["id"]
  8205. // }
  8206. // s_params = append(s_params, id)
  8207. // } else {
  8208. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8209. // }
  8210. if value == "pastureid" {
  8211. s_params = append(s_params, pastureId)
  8212. } else {
  8213. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8214. }
  8215. }
  8216. }
  8217. _, err = tx.SQL(sql1, s_params...).Execute()
  8218. if err != nil {
  8219. logging.Error("PostRJSBData1 err: ", err)
  8220. msg := geterrmsg(err.Error())
  8221. appG.Response(http.StatusOK, e.ERROR, msg)
  8222. return
  8223. }
  8224. s_params = make([]interface{}, 0)
  8225. paramslist = strings.Split(p2, ",")
  8226. if len(paramslist) > 0 && p2 != "" {
  8227. for _, value := range paramslist {
  8228. if value == "ID" {
  8229. id := parammaps.Get("ID").ValueStr()
  8230. pastureid := parammaps.Get("pastureid").ValueStr()
  8231. 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
  8232. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8233. if err != nil {
  8234. logging.Error("PostRJSBData err: ", err)
  8235. msg := geterrmsg(err.Error())
  8236. appG.Response(http.StatusOK, e.ERROR, msg)
  8237. return
  8238. }
  8239. for _, item := range datalist {
  8240. id = item["id"]
  8241. }
  8242. s_params = append(s_params, id)
  8243. } else if value == "pastureid" {
  8244. s_params = append(s_params, pastureId)
  8245. } else {
  8246. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8247. }
  8248. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8249. }
  8250. }
  8251. _, err = tx.SQL(sql2, s_params...).Execute()
  8252. if err != nil {
  8253. logging.Error("PostRJSBData2 err: ", err)
  8254. msg := geterrmsg(err.Error())
  8255. appG.Response(http.StatusOK, e.ERROR, msg)
  8256. return
  8257. }
  8258. s_params = make([]interface{}, 0)
  8259. paramslist = strings.Split(p3, ",")
  8260. if len(paramslist) > 0 && p3 != "" {
  8261. for _, value := range paramslist {
  8262. if value == "pastureid" {
  8263. s_params = append(s_params, pastureId)
  8264. } else {
  8265. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8266. }
  8267. }
  8268. }
  8269. _, err = tx.SQL(sql3, s_params...).Execute()
  8270. if err != nil {
  8271. logging.Error("PostRJSBData3 err: ", err)
  8272. msg := geterrmsg(err.Error())
  8273. appG.Response(http.StatusOK, e.ERROR, msg)
  8274. return
  8275. }
  8276. }
  8277. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8278. }
  8279. func FpdBatchEdit(c *gin.Context) {
  8280. appG := app.Gin{C: c}
  8281. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8282. fsions := gofasion.NewFasion(string(dataByte))
  8283. barList := fsions.Get("barList").Array()
  8284. pastureid := fsions.Get("pastureId").ValueStr()
  8285. tx := restful.Engine.NewSession()
  8286. defer tx.Close()
  8287. 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
  8288. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8289. if err != nil {
  8290. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8291. return
  8292. }
  8293. for _, barFsions := range barList {
  8294. dataexcel := make(map[string]interface{}, 0)
  8295. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8296. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8297. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8298. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8299. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8300. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8301. continue
  8302. }
  8303. // /*
  8304. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8305. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8306. if err != nil {
  8307. logs.Error(err)
  8308. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8309. return
  8310. }
  8311. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8312. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8313. if err != nil {
  8314. logs.Error(err)
  8315. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8316. return
  8317. }
  8318. // */
  8319. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8320. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8321. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8322. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8323. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8324. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8325. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8326. if err != nil {
  8327. logs.Error(err)
  8328. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8329. return
  8330. }
  8331. if !ftexist {
  8332. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8333. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8334. if err != nil {
  8335. logs.Error(err)
  8336. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8337. return
  8338. }
  8339. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8340. if err != nil {
  8341. logs.Error(err)
  8342. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8343. return
  8344. }
  8345. }
  8346. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8347. if err != nil {
  8348. logs.Error(err)
  8349. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8350. return
  8351. }
  8352. if !exist {
  8353. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8354. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8355. if err != nil {
  8356. logs.Error(err)
  8357. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8358. return
  8359. }
  8360. }
  8361. var feedpargs []interface{}
  8362. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8363. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8364. if _, ok := dataexcel["ftname"]; ok {
  8365. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8366. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8367. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8368. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8369. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8370. } else {
  8371. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8372. }
  8373. if _, ok := dataexcel["ptsfname"]; ok {
  8374. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8375. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8376. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8377. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8378. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8379. } else {
  8380. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8381. }
  8382. upFeedpSql += " where barname = ? and pastureid = ? "
  8383. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8384. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8385. if err != nil {
  8386. logs.Error(err)
  8387. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8388. return
  8389. }
  8390. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8391. if err != nil {
  8392. logs.Error(err)
  8393. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8394. return
  8395. }
  8396. if !exist1 {
  8397. _, 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) `,
  8398. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8399. if err != nil {
  8400. logs.Error(err)
  8401. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8402. return
  8403. }
  8404. }
  8405. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8406. if err != nil {
  8407. logs.Error(err)
  8408. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8409. return
  8410. }
  8411. if !exist2 {
  8412. _, 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) `,
  8413. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8414. if err != nil {
  8415. logs.Error(err)
  8416. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8417. return
  8418. }
  8419. }
  8420. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8421. if err != nil {
  8422. logs.Error(err)
  8423. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8424. return
  8425. }
  8426. if !exist3 {
  8427. _, 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) `,
  8428. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8429. if err != nil {
  8430. logs.Error(err)
  8431. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8432. return
  8433. }
  8434. }
  8435. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8436. if err != nil {
  8437. logs.Error(err)
  8438. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8439. return
  8440. }
  8441. if !exist4 {
  8442. _, 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) `,
  8443. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8444. if err != nil {
  8445. logs.Error(err)
  8446. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8447. return
  8448. }
  8449. }
  8450. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8451. if err != nil {
  8452. logs.Error(err)
  8453. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8454. return
  8455. }
  8456. if !exist5 {
  8457. _, 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) `,
  8458. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8459. if err != nil {
  8460. logs.Error(err)
  8461. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8462. return
  8463. }
  8464. }
  8465. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8466. if err != nil {
  8467. logs.Error(err)
  8468. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8469. return
  8470. }
  8471. if !exist6 {
  8472. _, 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) `,
  8473. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8474. if err != nil {
  8475. logs.Error(err)
  8476. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8477. return
  8478. }
  8479. }
  8480. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8481. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8482. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8483. and pastureid = ? and times = ?`
  8484. var fpdargs1 []interface{}
  8485. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8486. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8487. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8488. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8489. if err != nil {
  8490. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8491. return
  8492. }
  8493. var fpdargs2 []interface{}
  8494. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8495. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8496. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8497. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8498. if err != nil {
  8499. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8500. return
  8501. }
  8502. var fpdargs3 []interface{}
  8503. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8504. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8505. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8506. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8507. if err != nil {
  8508. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8509. return
  8510. }
  8511. var fpdargs4 []interface{}
  8512. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8513. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8514. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8515. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8516. if err != nil {
  8517. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8518. return
  8519. }
  8520. var fpdargs5 []interface{}
  8521. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8522. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8523. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8524. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8525. if err != nil {
  8526. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8527. return
  8528. }
  8529. var fpdargs6 []interface{}
  8530. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8531. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8532. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8533. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8534. if err != nil {
  8535. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8536. return
  8537. }
  8538. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8539. 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()
  8540. if err != nil {
  8541. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8542. return
  8543. }
  8544. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8545. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8546. upFpdetailList := make([]*upFpdetail, 0)
  8547. for _, newfpd := range newList {
  8548. for _, oldfpd := range oldFpdList {
  8549. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8550. var oldweight, newweight float64
  8551. if oldfpd["weight"] != nil {
  8552. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8553. }
  8554. if newfpd["weight"] != nil {
  8555. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8556. }
  8557. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8558. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8559. Old: oldweight,
  8560. New: newweight,
  8561. Times: newfpd["times"].(int64),
  8562. Ptid: newfpd["ptid"].(int64),
  8563. Fweight: fweight,
  8564. Id: oldfpd["id"].(int64),
  8565. })
  8566. break
  8567. }
  8568. }
  8569. }
  8570. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8571. }
  8572. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8573. }
  8574. func UdBarSync(c *gin.Context) {
  8575. appG := app.Gin{C: c}
  8576. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8577. fsions := gofasion.NewFasion(string(dataByte))
  8578. pastureid := fsions.Get("pastureId").ValueStr()
  8579. tx := restful.Engine.NewSession()
  8580. defer tx.Close()
  8581. pastureinfo := new(udPastureInfo)
  8582. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8583. if err != nil {
  8584. logs.Error(err)
  8585. return
  8586. }
  8587. // gm.UdBarSync(pastureid, pastureinfo.Werks)
  8588. jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8589. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8590. }
  8591. func UdFeedSync(c *gin.Context) {
  8592. appG := app.Gin{C: c}
  8593. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8594. fsions := gofasion.NewFasion(string(dataByte))
  8595. pastureid := fsions.Get("pastureId").ValueStr()
  8596. tx := restful.Engine.NewSession()
  8597. defer tx.Close()
  8598. pastureinfo := new(udPastureInfo)
  8599. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8600. if err != nil {
  8601. logs.Error(err)
  8602. return
  8603. }
  8604. // gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8605. jpud.UdFeedSync(pastureid, pastureinfo.Werks)
  8606. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8607. }
  8608. func UdFeedtempletPush(c *gin.Context) {
  8609. appG := app.Gin{C: c}
  8610. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8611. fsions := gofasion.NewFasion(string(dataByte))
  8612. pastureid := fsions.Get("pastureId").ValueStr()
  8613. date := fsions.Get("date").ValueStr()
  8614. tx := restful.Engine.NewSession()
  8615. defer tx.Close()
  8616. pastureinfo := new(udPastureInfo)
  8617. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8618. if err != nil {
  8619. logs.Error(err)
  8620. return
  8621. }
  8622. // gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8623. jpud.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8624. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8625. }
  8626. func UdUtirPush(c *gin.Context) {
  8627. appG := app.Gin{C: c}
  8628. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8629. fsions := gofasion.NewFasion(string(dataByte))
  8630. pastureid := fsions.Get("pastureId").ValueStr()
  8631. date := fsions.Get("date").ValueStr()
  8632. tx := restful.Engine.NewSession()
  8633. defer tx.Close()
  8634. pastureinfo := new(udPastureInfo)
  8635. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8636. if err != nil {
  8637. logs.Error(err)
  8638. return
  8639. }
  8640. // gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8641. jpud.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8642. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8643. }
  8644. func UdBarFeedRemainPush(c *gin.Context) {
  8645. appG := app.Gin{C: c}
  8646. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8647. fsions := gofasion.NewFasion(string(dataByte))
  8648. pastureid := fsions.Get("pastureId").ValueStr()
  8649. date := fsions.Get("date").ValueStr()
  8650. tx := restful.Engine.NewSession()
  8651. defer tx.Close()
  8652. pastureinfo := new(udPastureInfo)
  8653. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8654. if err != nil {
  8655. logs.Error(err)
  8656. return
  8657. }
  8658. // gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8659. jpud.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8660. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8661. }
  8662. func UdMaterialIssuePush(c *gin.Context) {
  8663. appG := app.Gin{C: c}
  8664. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8665. fsions := gofasion.NewFasion(string(dataByte))
  8666. pastureid := fsions.Get("pastureId").ValueStr()
  8667. date := fsions.Get("date").ValueStr()
  8668. tx := restful.Engine.NewSession()
  8669. defer tx.Close()
  8670. pastureinfo := new(udPastureInfo)
  8671. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8672. if err != nil {
  8673. logs.Error(err)
  8674. return
  8675. }
  8676. // gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8677. jpud.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8678. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8679. }
  8680. //搅拌
  8681. func YmyUtirPush(c *gin.Context) {
  8682. appG := app.Gin{C: c}
  8683. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8684. fsions := gofasion.NewFasion(string(dataByte))
  8685. pastureid := fsions.Get("pastureId").ValueStr()
  8686. date := fsions.Get("date").ValueStr()
  8687. tx := restful.Engine.NewSession()
  8688. defer tx.Close()
  8689. pastureinfo := new(udPastureInfo)
  8690. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8691. if err != nil {
  8692. logs.Error(err)
  8693. return
  8694. }
  8695. ymy.YmyUtirPush(pastureid, pastureinfo.Werks, date)
  8696. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8697. }
  8698. //撒料
  8699. func YmyMaterialIssuePush(c *gin.Context) {
  8700. appG := app.Gin{C: c}
  8701. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8702. fsions := gofasion.NewFasion(string(dataByte))
  8703. pastureid := fsions.Get("pastureId").ValueStr()
  8704. date := fsions.Get("date").ValueStr()
  8705. tx := restful.Engine.NewSession()
  8706. defer tx.Close()
  8707. pastureinfo := new(udPastureInfo)
  8708. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8709. if err != nil {
  8710. logs.Error(err)
  8711. return
  8712. }
  8713. ymy.YmyMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8714. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8715. }
  8716. func YmyFeedtempletPush(c *gin.Context) {
  8717. appG := app.Gin{C: c}
  8718. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8719. fsions := gofasion.NewFasion(string(dataByte))
  8720. pastureid := fsions.Get("pastureId").ValueStr()
  8721. date := fsions.Get("date").ValueStr()
  8722. tx := restful.Engine.NewSession()
  8723. defer tx.Close()
  8724. pastureinfo := new(udPastureInfo)
  8725. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8726. if err != nil {
  8727. logs.Error(err)
  8728. return
  8729. }
  8730. ymy.YmyFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8731. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8732. }
  8733. //饲料
  8734. func YmySyncFeed(c *gin.Context) {
  8735. appG := app.Gin{C: c}
  8736. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8737. fsions := gofasion.NewFasion(string(dataByte))
  8738. pastureid := fsions.Get("pastureId").ValueStr()
  8739. // date := fsions.Get("date").ValueStr()
  8740. tx := restful.Engine.NewSession()
  8741. defer tx.Close()
  8742. ymy.YmySyncFeed(pastureid)
  8743. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8744. }
  8745. // 栏舍
  8746. func YmySyncBar(c *gin.Context) {
  8747. appG := app.Gin{C: c}
  8748. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8749. fsions := gofasion.NewFasion(string(dataByte))
  8750. pastureid := fsions.Get("pastureId").ValueStr()
  8751. // date := fsions.Get("date").ValueStr()
  8752. tx := restful.Engine.NewSession()
  8753. defer tx.Close()
  8754. pastureinfo := new(udPastureInfo)
  8755. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8756. if err != nil {
  8757. logs.Error(err)
  8758. return
  8759. }
  8760. ymy.YmySyncBar(pastureinfo.Werks, pastureid)
  8761. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8762. }
  8763. func DelFeedTemplet(c *gin.Context) {
  8764. appG := app.Gin{C: c}
  8765. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8766. fsions := gofasion.NewFasion(string(dataByte))
  8767. ftId := fsions.Get("ftId").ValueStr()
  8768. // userId := fsions.Get("userId").ValueStr()
  8769. tx := restful.Engine.NewSession()
  8770. defer tx.Close()
  8771. _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
  8772. if err != nil {
  8773. logs.Error(err)
  8774. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8775. return
  8776. }
  8777. /*
  8778. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8779. if err != nil {
  8780. logs.Error(err)
  8781. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8782. return
  8783. }
  8784. */
  8785. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8786. if err != nil {
  8787. logs.Error(err)
  8788. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8789. return
  8790. }
  8791. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8792. if err != nil {
  8793. logs.Error(err)
  8794. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8795. return
  8796. }
  8797. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8798. if count > 0 {
  8799. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8800. if err != nil {
  8801. logs.Error(err)
  8802. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8803. return
  8804. }
  8805. }
  8806. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8807. if err != nil {
  8808. logs.Error(err)
  8809. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8810. return
  8811. }
  8812. // var barIdStr []string
  8813. // for _, bar := range barIdList {
  8814. // barIdStr = append(barIdStr, bar["barid"])
  8815. // }
  8816. // if len(barIdStr) > 0 {
  8817. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8818. // if err != nil {
  8819. // logs.Error(err)
  8820. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8821. // return
  8822. // }
  8823. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8824. // if err != nil {
  8825. // logs.Error(err)
  8826. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8827. // return
  8828. // }
  8829. // now := time.Now()
  8830. // for _, newFpd := range newFpdDataList {
  8831. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8832. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8833. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8834. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8835. // if err != nil {
  8836. // logs.Error(err)
  8837. // appG.Response(http.StatusOK, e.ERROR, false)
  8838. // return
  8839. // }
  8840. // }
  8841. // for _, newFeedp := range newFeedpList {
  8842. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8843. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8844. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8845. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8846. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8847. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8848. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8849. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8850. // if err != nil {
  8851. // logs.Error(err)
  8852. // appG.Response(http.StatusOK, e.ERROR, false)
  8853. // return
  8854. // }
  8855. // }
  8856. // }
  8857. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8858. }
  8859. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8860. sysOpt := new(models.SysOpt)
  8861. tx.Table("sysopt").Where("inforname = ?", "separateVehicles").Get(sysOpt)
  8862. lweight := 0.0
  8863. if sysOpt.InforValue != "" {
  8864. lweight, _ = strconv.ParseFloat(sysOpt.InforValue, 64)
  8865. } else if sysOpt.InforValue == "" || sysOpt.InforValue == "0" {
  8866. return
  8867. }
  8868. fmt.Println(sysOpt)
  8869. data := fasion["parammaps"].(map[string]interface{})
  8870. // plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(2) ").Count()
  8871. downloadedplanList := make([]*models.DownloadedPlan, 0)
  8872. tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype = 2 ").Find(&downloadedplanList)
  8873. fmt.Println(lweight)
  8874. for _, downloadedplan := range downloadedplanList {
  8875. if downloadedplan.LWeight < lweight {
  8876. break
  8877. }
  8878. downloadplandtl1List := make([]*models.DownloadPlanDtl1, 0)
  8879. downloadplandtl1ExecList := make([]*models.DownloadPlanDtl1Exec, 0)
  8880. downloadplandtl2List := make([]*models.DownloadPlanDtl2, 0)
  8881. tx.Table("downloadplandtl1").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1List)
  8882. tx.Table("downloadplandtl2").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl2List)
  8883. tx.Table("downloadplandtl1_exec").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1ExecList)
  8884. lweightCount := math.Floor(downloadedplan.LWeight / lweight)
  8885. for i := 0; i <= int(lweightCount); i++ {
  8886. if i == 0 {
  8887. tx.Exec(` update downloadedplan set lweight = ? where id = ? `, lweight, downloadedplan.ID)
  8888. for _, downloadplandtl1 := range downloadplandtl1List {
  8889. tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl1.LWeight, downloadplandtl1.ID)
  8890. }
  8891. for _, downloadplandtl2 := range downloadplandtl2List {
  8892. tx.Exec(` update downloadplandtl2 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8893. }
  8894. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  8895. tx.Exec(` update downloadplandtl1_exec set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8896. }
  8897. // && downloadedplan.LWeight >lweight
  8898. } else if i < int(lweightCount) {
  8899. parts := strings.Split(downloadedplan.ProjName, ".")
  8900. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  8901. data := &models.DownloadedPlan{
  8902. PastureID: downloadedplan.PastureID,
  8903. MyDate: downloadedplan.MyDate,
  8904. ProjName: strings.Join(parts, "."),
  8905. DataCaptureNo: downloadedplan.DataCaptureNo,
  8906. TmrID: downloadedplan.TmrID,
  8907. TmrtName: downloadedplan.TmrtName,
  8908. HaveButton: downloadedplan.HaveButton,
  8909. InButtonType: downloadedplan.InButtonType,
  8910. PlanTime: downloadedplan.PlanTime,
  8911. InTime: downloadedplan.InTime,
  8912. CompletedTime: downloadedplan.CompletedTime,
  8913. IsCompleted: downloadedplan.IsCompleted,
  8914. LpPlanType: downloadedplan.LpPlanType,
  8915. Times: downloadedplan.Times,
  8916. Sort: downloadedplan.Sort,
  8917. Remark: downloadedplan.Remark,
  8918. ItemNum: downloadedplan.ItemNum,
  8919. OutItems: downloadedplan.OutItems,
  8920. FeedPName: downloadedplan.FeedPName,
  8921. FeedPCount: downloadedplan.FeedPCount,
  8922. Pid: downloadedplan.Pid,
  8923. TempID: downloadedplan.TempID,
  8924. TempletName: downloadedplan.TempletName,
  8925. PtsTempID: downloadedplan.PtsTempID,
  8926. PtsTempletName: downloadedplan.PtsTempletName,
  8927. ThoWeight: downloadedplan.ThoWeight,
  8928. FpWeight: downloadedplan.FpWeight,
  8929. LWeight: lweight,
  8930. IWeight: downloadedplan.IWeight,
  8931. OWeight: downloadedplan.OWeight,
  8932. TVersion: downloadedplan.TVersion,
  8933. PtVersion: downloadedplan.PtVersion,
  8934. Enable: downloadedplan.Enable,
  8935. IsUse: downloadedplan.IsUse,
  8936. OldTmrID: downloadedplan.OldTmrID,
  8937. DriverID: downloadedplan.DriverID,
  8938. Artificial: downloadedplan.Artificial,
  8939. }
  8940. _, err := tx.Insert(data)
  8941. fmt.Println(data, err)
  8942. for _, downloadplandtl1 := range downloadplandtl1List {
  8943. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8944. d1 := &models.DownloadPlanDtl1{
  8945. PastureID: downloadplandtl1.PastureID,
  8946. Pid: data.ID,
  8947. Flpid: downloadplandtl1.Flpid,
  8948. Fid: downloadplandtl1.Fid,
  8949. LWeight: lweight / downloadedplan.LWeight * downloadplandtl1.LWeight,
  8950. Sort: downloadplandtl1.Sort,
  8951. ButtonType: downloadplandtl1.ButtonType,
  8952. OptDevice: downloadplandtl1.OptDevice,
  8953. FeedCode: downloadplandtl1.FeedCode,
  8954. FName: downloadplandtl1.FName,
  8955. FeedSort: downloadplandtl1.FeedSort,
  8956. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  8957. StirDelay: downloadplandtl1.StirDelay,
  8958. FWeight: downloadplandtl1.FWeight,
  8959. TmrLoadName: downloadplandtl1.TmrLoadName,
  8960. DryFeed: downloadplandtl1.DryFeed,
  8961. PriceFeed: downloadplandtl1.PriceFeed,
  8962. OutWeight: downloadplandtl1.OutWeight,
  8963. ErrRatio: downloadplandtl1.ErrRatio,
  8964. Date: downloadplandtl1.Date,
  8965. ButtonSucc: downloadplandtl1.ButtonSucc,
  8966. Type: downloadplandtl1.Type,
  8967. Deviation: downloadplandtl1.Deviation,
  8968. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  8969. }
  8970. tx.Insert(d1)
  8971. }
  8972. for _, downloadplandtl2 := range downloadplandtl2List {
  8973. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8974. d2 := &models.DownloadPlanDtl2{
  8975. PastureID: downloadplandtl2.PastureID,
  8976. Pid: data.ID,
  8977. Flpid: downloadplandtl2.Flpid,
  8978. Fbarid: downloadplandtl2.Fbarid,
  8979. FName: downloadplandtl2.FName,
  8980. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8981. LWeightHis: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8982. RemainLeftW: downloadplandtl2.RemainLeftW,
  8983. AllowRW: downloadplandtl2.AllowRW,
  8984. Sort: downloadplandtl2.Sort,
  8985. HaveButton: downloadplandtl2.HaveButton,
  8986. BeginTag: downloadplandtl2.BeginTag,
  8987. EndTag: downloadplandtl2.EndTag,
  8988. ButtonType: downloadplandtl2.ButtonType,
  8989. OptDevice: downloadplandtl2.OptDevice,
  8990. CowCount: downloadplandtl2.CowCount,
  8991. CowClassID: downloadplandtl2.CowClassID,
  8992. CowClassName: downloadplandtl2.CowClassName,
  8993. BigCowName: downloadplandtl2.BigCowName,
  8994. PWeight: downloadplandtl2.PWeight,
  8995. CCountRatio: downloadplandtl2.CCountRatio,
  8996. SumRTime: downloadplandtl2.SumRTime,
  8997. FeedTempletID: downloadplandtl2.FeedTempletID,
  8998. FeedTempletName: downloadplandtl2.FeedTempletName,
  8999. DryWeight: downloadplandtl2.DryWeight,
  9000. SumWeight: downloadplandtl2.SumWeight,
  9001. PriceWeight: downloadplandtl2.PriceWeight,
  9002. // ProcessTime :downloadplandtl2.ProcessTime ,
  9003. Fpid: downloadplandtl2.Fpid,
  9004. UseInBarType: downloadplandtl2.UseInBarType,
  9005. Date: downloadplandtl2.Date,
  9006. AllowRatio: downloadplandtl2.AllowRatio,
  9007. ErrRatio: downloadplandtl2.ErrRatio,
  9008. ButtonSucc: downloadplandtl2.ButtonSucc,
  9009. Type: downloadplandtl2.Type,
  9010. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9011. XxwBarCode: downloadplandtl2.XxwBarCode,
  9012. }
  9013. _, err := tx.Insert(d2)
  9014. fmt.Println(err)
  9015. }
  9016. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9017. d2 := &models.DownloadPlanDtl1Exec{
  9018. PastureID: downloadplandtl2.PastureID,
  9019. Pid: data.ID,
  9020. Flpid: downloadplandtl2.Flpid,
  9021. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9022. HaveButton: downloadplandtl2.HaveButton,
  9023. ButtonType: downloadplandtl2.ButtonType,
  9024. OptDevice: downloadplandtl2.OptDevice,
  9025. Sort: downloadplandtl2.Sort,
  9026. FName: downloadplandtl2.FName,
  9027. FCount: downloadplandtl2.FCount,
  9028. TmrLoadName: downloadplandtl2.TmrLoadName,
  9029. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9030. StirDelay: downloadplandtl2.StirDelay,
  9031. ButtonSucc: downloadplandtl2.ButtonSucc,
  9032. ErrRatio: downloadplandtl2.ErrRatio,
  9033. Date: downloadplandtl2.Date,
  9034. Type: downloadplandtl2.Type,
  9035. Deviation: downloadplandtl2.Deviation,
  9036. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9037. }
  9038. _, err := tx.Insert(d2)
  9039. fmt.Println(err)
  9040. }
  9041. } else {
  9042. parts := strings.Split(downloadedplan.ProjName, ".")
  9043. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  9044. if downloadedplan.LWeight-float64(i)*lweight <= 0 {
  9045. continue
  9046. }
  9047. data := &models.DownloadedPlan{
  9048. PastureID: downloadedplan.PastureID,
  9049. MyDate: downloadedplan.MyDate,
  9050. ProjName: strings.Join(parts, "."),
  9051. DataCaptureNo: downloadedplan.DataCaptureNo,
  9052. TmrID: downloadedplan.TmrID,
  9053. TmrtName: downloadedplan.TmrtName,
  9054. HaveButton: downloadedplan.HaveButton,
  9055. InButtonType: downloadedplan.InButtonType,
  9056. PlanTime: downloadedplan.PlanTime,
  9057. InTime: downloadedplan.InTime,
  9058. CompletedTime: downloadedplan.CompletedTime,
  9059. IsCompleted: downloadedplan.IsCompleted,
  9060. LpPlanType: downloadedplan.LpPlanType,
  9061. Times: downloadedplan.Times,
  9062. Sort: downloadedplan.Sort,
  9063. Remark: downloadedplan.Remark,
  9064. ItemNum: downloadedplan.ItemNum,
  9065. OutItems: downloadedplan.OutItems,
  9066. FeedPName: downloadedplan.FeedPName,
  9067. FeedPCount: downloadedplan.FeedPCount,
  9068. Pid: downloadedplan.Pid,
  9069. TempID: downloadedplan.TempID,
  9070. TempletName: downloadedplan.TempletName,
  9071. PtsTempID: downloadedplan.PtsTempID,
  9072. PtsTempletName: downloadedplan.PtsTempletName,
  9073. ThoWeight: downloadedplan.ThoWeight,
  9074. FpWeight: downloadedplan.FpWeight,
  9075. LWeight: downloadedplan.LWeight - float64(i)*lweight,
  9076. IWeight: downloadedplan.IWeight,
  9077. OWeight: downloadedplan.OWeight,
  9078. TVersion: downloadedplan.TVersion,
  9079. PtVersion: downloadedplan.PtVersion,
  9080. Enable: downloadedplan.Enable,
  9081. IsUse: downloadedplan.IsUse,
  9082. OldTmrID: downloadedplan.OldTmrID,
  9083. DriverID: downloadedplan.DriverID,
  9084. Artificial: downloadedplan.Artificial,
  9085. }
  9086. _, err := tx.Insert(data)
  9087. fmt.Println(data, err)
  9088. for _, downloadplandtl1 := range downloadplandtl1List {
  9089. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9090. d1 := &models.DownloadPlanDtl1{
  9091. PastureID: downloadplandtl1.PastureID,
  9092. Pid: data.ID,
  9093. Flpid: downloadplandtl1.Flpid,
  9094. Fid: downloadplandtl1.Fid,
  9095. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl1.LWeight,
  9096. Sort: downloadplandtl1.Sort,
  9097. ButtonType: downloadplandtl1.ButtonType,
  9098. OptDevice: downloadplandtl1.OptDevice,
  9099. FeedCode: downloadplandtl1.FeedCode,
  9100. FName: downloadplandtl1.FName,
  9101. FeedSort: downloadplandtl1.FeedSort,
  9102. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  9103. StirDelay: downloadplandtl1.StirDelay,
  9104. FWeight: downloadplandtl1.FWeight,
  9105. TmrLoadName: downloadplandtl1.TmrLoadName,
  9106. DryFeed: downloadplandtl1.DryFeed,
  9107. PriceFeed: downloadplandtl1.PriceFeed,
  9108. OutWeight: downloadplandtl1.OutWeight,
  9109. ErrRatio: downloadplandtl1.ErrRatio,
  9110. Date: downloadplandtl1.Date,
  9111. ButtonSucc: downloadplandtl1.ButtonSucc,
  9112. Type: downloadplandtl1.Type,
  9113. Deviation: downloadplandtl1.Deviation,
  9114. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  9115. }
  9116. tx.Insert(d1)
  9117. }
  9118. for _, downloadplandtl2 := range downloadplandtl2List {
  9119. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9120. d2 := &models.DownloadPlanDtl2{
  9121. PastureID: downloadplandtl2.PastureID,
  9122. Pid: data.ID,
  9123. Flpid: downloadplandtl2.Flpid,
  9124. Fbarid: downloadplandtl2.Fbarid,
  9125. FName: downloadplandtl2.FName,
  9126. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9127. LWeightHis: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9128. RemainLeftW: downloadplandtl2.RemainLeftW,
  9129. AllowRW: downloadplandtl2.AllowRW,
  9130. Sort: downloadplandtl2.Sort,
  9131. HaveButton: downloadplandtl2.HaveButton,
  9132. BeginTag: downloadplandtl2.BeginTag,
  9133. EndTag: downloadplandtl2.EndTag,
  9134. ButtonType: downloadplandtl2.ButtonType,
  9135. OptDevice: downloadplandtl2.OptDevice,
  9136. CowCount: downloadplandtl2.CowCount,
  9137. CowClassID: downloadplandtl2.CowClassID,
  9138. CowClassName: downloadplandtl2.CowClassName,
  9139. BigCowName: downloadplandtl2.BigCowName,
  9140. PWeight: downloadplandtl2.PWeight,
  9141. CCountRatio: downloadplandtl2.CCountRatio,
  9142. SumRTime: downloadplandtl2.SumRTime,
  9143. FeedTempletID: downloadplandtl2.FeedTempletID,
  9144. FeedTempletName: downloadplandtl2.FeedTempletName,
  9145. DryWeight: downloadplandtl2.DryWeight,
  9146. SumWeight: downloadplandtl2.SumWeight,
  9147. PriceWeight: downloadplandtl2.PriceWeight,
  9148. // ProcessTime :downloadplandtl2.ProcessTime ,
  9149. Fpid: downloadplandtl2.Fpid,
  9150. UseInBarType: downloadplandtl2.UseInBarType,
  9151. Date: downloadplandtl2.Date,
  9152. AllowRatio: downloadplandtl2.AllowRatio,
  9153. ErrRatio: downloadplandtl2.ErrRatio,
  9154. ButtonSucc: downloadplandtl2.ButtonSucc,
  9155. Type: downloadplandtl2.Type,
  9156. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9157. XxwBarCode: downloadplandtl2.XxwBarCode,
  9158. }
  9159. _, err := tx.Insert(d2)
  9160. fmt.Println(err)
  9161. }
  9162. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9163. d2 := &models.DownloadPlanDtl1Exec{
  9164. PastureID: downloadplandtl2.PastureID,
  9165. Pid: data.ID,
  9166. Flpid: downloadplandtl2.Flpid,
  9167. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9168. HaveButton: downloadplandtl2.HaveButton,
  9169. ButtonType: downloadplandtl2.ButtonType,
  9170. OptDevice: downloadplandtl2.OptDevice,
  9171. Sort: downloadplandtl2.Sort,
  9172. FName: downloadplandtl2.FName,
  9173. FCount: downloadplandtl2.FCount,
  9174. TmrLoadName: downloadplandtl2.TmrLoadName,
  9175. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9176. StirDelay: downloadplandtl2.StirDelay,
  9177. ButtonSucc: downloadplandtl2.ButtonSucc,
  9178. ErrRatio: downloadplandtl2.ErrRatio,
  9179. Date: downloadplandtl2.Date,
  9180. Type: downloadplandtl2.Type,
  9181. Deviation: downloadplandtl2.Deviation,
  9182. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9183. }
  9184. fmt.Println(d2)
  9185. _, err := tx.Insert(d2)
  9186. fmt.Println(err)
  9187. }
  9188. }
  9189. }
  9190. }
  9191. downloadedplanSortList := make([]*models.DownloadedPlan, 0)
  9192. tx.SQL(`SELECT * FROM downloadedplan WHERE mydate = ? ORDER BY projname`, data["startTime"]).Find(&downloadedplanSortList)
  9193. for i, d := range downloadedplanSortList {
  9194. tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, d.ID)
  9195. }
  9196. }
  9197. func EditPlanSort(c *gin.Context) {
  9198. appG := app.Gin{C: c}
  9199. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9200. fsions := gofasion.NewFasion(string(dataByte))
  9201. planIdStr := fsions.Get("planId").ValueStr()
  9202. mydate := fsions.Get("mydate").ValueStr()
  9203. sort := fsions.Get("sort").ValueStr()
  9204. tx := restful.Engine.NewSession()
  9205. defer tx.Close()
  9206. tx.Begin()
  9207. type downloadedplan struct {
  9208. Id int64 `xorm:"id"`
  9209. Sort int `xorm:"sort"`
  9210. Pid int64 `xorm:"pid"`
  9211. }
  9212. planInfo := new(downloadedplan)
  9213. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  9214. if err != nil {
  9215. logs.Error(err)
  9216. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9217. tx.Rollback()
  9218. return
  9219. }
  9220. sort1, _ := strconv.Atoi(sort)
  9221. if sort1 == planInfo.Sort {
  9222. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  9223. tx.Rollback()
  9224. return
  9225. }
  9226. 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()
  9227. if err != nil {
  9228. logs.Error(err)
  9229. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9230. tx.Rollback()
  9231. return
  9232. }
  9233. if count1 == 0 {
  9234. tx.Rollback()
  9235. logs.Error(err)
  9236. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  9237. return
  9238. }
  9239. 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()
  9240. if err != nil {
  9241. logs.Error(err)
  9242. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9243. tx.Rollback()
  9244. return
  9245. }
  9246. if count > 0 {
  9247. tx.Rollback()
  9248. logs.Error(err)
  9249. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  9250. return
  9251. }
  9252. if planInfo.Sort > sort1 {
  9253. 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()
  9254. if err != nil {
  9255. logs.Error(err)
  9256. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9257. tx.Rollback()
  9258. return
  9259. }
  9260. var minSort, pidCount int
  9261. for _, sort := range minSortList {
  9262. minSort, _ = strconv.Atoi(sort["sort"])
  9263. }
  9264. planList := make([]*downloadedplan, 0)
  9265. 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)
  9266. if err != nil {
  9267. logs.Error(err)
  9268. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9269. tx.Rollback()
  9270. return
  9271. }
  9272. planPid := planInfo.Pid
  9273. planList1 := make([]*downloadedplan, 0)
  9274. planList2 := make([]*downloadedplan, 0)
  9275. for _, plan := range planList {
  9276. if plan.Pid == planPid {
  9277. pidCount++
  9278. planList1 = append(planList1, plan)
  9279. } else {
  9280. planList2 = append(planList2, plan)
  9281. }
  9282. }
  9283. planList1 = append(planList1, planList2...)
  9284. for i, plan := range planList1 {
  9285. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  9286. if err != nil {
  9287. logs.Error(err)
  9288. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9289. tx.Rollback()
  9290. return
  9291. }
  9292. }
  9293. } else {
  9294. 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()
  9295. if err != nil {
  9296. logs.Error(err)
  9297. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9298. tx.Rollback()
  9299. return
  9300. }
  9301. var maxSort int
  9302. for _, sort := range maxSortList {
  9303. maxSort, _ = strconv.Atoi(sort["sort"])
  9304. }
  9305. planList := make([]*downloadedplan, 0)
  9306. 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)
  9307. if err != nil {
  9308. logs.Error(err)
  9309. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9310. tx.Rollback()
  9311. return
  9312. }
  9313. planPid := planInfo.Pid
  9314. planList1 := make([]*downloadedplan, 0)
  9315. planList2 := make([]*downloadedplan, 0)
  9316. for _, plan := range planList {
  9317. if plan.Pid == planPid {
  9318. // pidCount++
  9319. planList1 = append(planList1, plan)
  9320. } else {
  9321. planList2 = append(planList2, plan)
  9322. }
  9323. }
  9324. planList2 = append(planList2, planList1...)
  9325. for i, plan := range planList2 {
  9326. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  9327. if err != nil {
  9328. logs.Error(err)
  9329. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9330. tx.Rollback()
  9331. return
  9332. }
  9333. }
  9334. }
  9335. err = tx.Commit()
  9336. if err != nil {
  9337. logs.Error(err)
  9338. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9339. tx.Rollback()
  9340. return
  9341. }
  9342. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9343. }
  9344. func EditDownloadedplanArtificial(c *gin.Context) {
  9345. appG := app.Gin{C: c}
  9346. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9347. fsions := gofasion.NewFasion(string(dataByte))
  9348. planIdStr := fsions.Get("planId").ValueStr()
  9349. tx := restful.Engine.NewSession()
  9350. defer tx.Close()
  9351. tx.Begin()
  9352. planIdList := strings.Split(planIdStr, ",")
  9353. for _, planId := range planIdList {
  9354. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? `, planId)
  9355. if err != nil {
  9356. logs.Error(err)
  9357. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9358. tx.Rollback()
  9359. return
  9360. }
  9361. }
  9362. err := tx.Commit()
  9363. if err != nil {
  9364. logs.Error(err)
  9365. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9366. tx.Rollback()
  9367. return
  9368. }
  9369. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9370. }
  9371. type PlanRFID struct {
  9372. RFID string `json:"RFID"`
  9373. Lweight string `json:"lweight"`
  9374. Gear string `json:"gear"`
  9375. Speed string `json:"speed"`
  9376. }
  9377. func GetPlanRFID(c *gin.Context) {
  9378. appG := app.Gin{C: c}
  9379. RFIDStr := c.Query("RFID")
  9380. planRFIDList := make([]*PlanRFID, 0)
  9381. planRFIDList = append(planRFIDList, &PlanRFID{
  9382. RFID: RFIDStr,
  9383. Lweight: "1411.1",
  9384. Gear: "1",
  9385. Speed: "10",
  9386. })
  9387. planRFIDList = append(planRFIDList, &PlanRFID{
  9388. RFID: RFIDStr,
  9389. Lweight: "1322.1",
  9390. Gear: "1",
  9391. Speed: "10",
  9392. })
  9393. planRFIDList = append(planRFIDList, &PlanRFID{
  9394. RFID: RFIDStr,
  9395. Lweight: "1904.1",
  9396. Gear: "1",
  9397. Speed: "10",
  9398. })
  9399. planRFIDList = append(planRFIDList, &PlanRFID{
  9400. RFID: RFIDStr,
  9401. Lweight: "1870.1",
  9402. Gear: "1",
  9403. Speed: "10",
  9404. })
  9405. planRFIDList = append(planRFIDList, &PlanRFID{
  9406. RFID: RFIDStr,
  9407. Lweight: "2041.1",
  9408. Gear: "1",
  9409. Speed: "10",
  9410. })
  9411. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  9412. }
  9413. type tmrEquipmentMuster struct {
  9414. A string
  9415. N string
  9416. }
  9417. func GetTmrEquipmentMuster(c *gin.Context) {
  9418. appG := app.Gin{C: c}
  9419. id := c.Query("id")
  9420. tx := restful.Engine.NewSession()
  9421. defer tx.Close()
  9422. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  9423. if err != nil {
  9424. logs.Error(err)
  9425. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9426. return
  9427. }
  9428. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  9429. for _, data := range dataList {
  9430. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  9431. for _, g := range tmrEquipmentMusterList {
  9432. a, _ := strconv.ParseFloat(g.A, 64)
  9433. n, _ := strconv.ParseFloat(g.N, 64)
  9434. a1, n1 := ddmmtoddd(a, n)
  9435. g.A = fmt.Sprintf("%f", n1)
  9436. g.N = fmt.Sprintf("%f", a1)
  9437. }
  9438. }
  9439. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  9440. }
  9441. func ddmmtoddd(lng, lat float64) (float64, float64) {
  9442. lngDegree := fmt.Sprintf("%f", lng/100)
  9443. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  9444. lngDegreeInt := int(lngDegreefloat * 1000000)
  9445. dd := lngDegreeInt / 100 * 100 / 60
  9446. fmt.Println(dd)
  9447. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  9448. latDegree := fmt.Sprintf("%f", lat/100)
  9449. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  9450. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  9451. latDegreeInt := int(latDegreefloat * 1000000)
  9452. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  9453. a, _ := strconv.ParseFloat(lngStr, 64)
  9454. b, _ := strconv.ParseFloat(latStr, 64)
  9455. return coordtransform.WGS84toGCJ02(b, a)
  9456. }
  9457. func EditDownloadedplanExecWeight(c *gin.Context) {
  9458. appG := app.Gin{C: c}
  9459. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9460. fsions := gofasion.NewFasion(string(dataByte))
  9461. pid := fsions.Get("pid").ValueStr()
  9462. sort := fsions.Get("sort").ValueStr()
  9463. weight := fsions.Get("weight").ValueStr()
  9464. userId := fsions.Get("userId").ValueStr()
  9465. tx := restful.Engine.NewSession()
  9466. defer tx.Close()
  9467. tx.Begin()
  9468. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  9469. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  9470. pid, sort, pid, sort, weight, userId)
  9471. if err != nil {
  9472. logs.Error(err)
  9473. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9474. tx.Rollback()
  9475. return
  9476. }
  9477. _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9478. if err != nil {
  9479. logs.Error(err)
  9480. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9481. tx.Rollback()
  9482. return
  9483. }
  9484. _, 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)
  9485. if err != nil {
  9486. logs.Error(err)
  9487. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9488. tx.Rollback()
  9489. return
  9490. }
  9491. err = tx.Commit()
  9492. if err != nil {
  9493. logs.Error(err)
  9494. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9495. tx.Rollback()
  9496. return
  9497. }
  9498. appG.Response(http.StatusOK, e.SUCCESS, true)
  9499. }
  9500. func EditDownloadplandtl2Weight(c *gin.Context) {
  9501. appG := app.Gin{C: c}
  9502. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9503. fsions := gofasion.NewFasion(string(dataByte))
  9504. pid := fsions.Get("pid").ValueStr()
  9505. sort := fsions.Get("sort").ValueStr()
  9506. weight := fsions.Get("weight").ValueStr()
  9507. userId := fsions.Get("userId").ValueStr()
  9508. tx := restful.Engine.NewSession()
  9509. defer tx.Close()
  9510. tx.Begin()
  9511. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9512. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9513. pid, sort, pid, sort, weight, userId)
  9514. if err != nil {
  9515. logs.Error(err)
  9516. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9517. tx.Rollback()
  9518. return
  9519. }
  9520. _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9521. if err != nil {
  9522. logs.Error(err)
  9523. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9524. tx.Rollback()
  9525. return
  9526. }
  9527. err = tx.Commit()
  9528. if err != nil {
  9529. logs.Error(err)
  9530. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9531. tx.Rollback()
  9532. return
  9533. }
  9534. appG.Response(http.StatusOK, e.SUCCESS, true)
  9535. }
  9536. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9537. params := fasion.Get("parammaps")
  9538. surplus := params.Get("surplus").ValueStr()
  9539. surplusId := params.Get("surplusId").ValueStr()
  9540. tx := restful.Engine.NewSession()
  9541. defer tx.Close()
  9542. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9543. if surplusId != "0" {
  9544. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9545. if err != nil {
  9546. log.Println("PostDataByName-error-1: ", err)
  9547. return errors.New("配方修改失败!")
  9548. }
  9549. type ftdetail struct {
  9550. Id string
  9551. Fname string
  9552. Sort int64
  9553. }
  9554. ftList := make([]*ftdetail, 0)
  9555. for _, data := range dataList {
  9556. ft := new(ftdetail)
  9557. ft.Fname = data["fname"]
  9558. ft.Id = data["id"]
  9559. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9560. if err != nil {
  9561. log.Println("PostDataByName-error-2: ", err)
  9562. return err
  9563. }
  9564. ft.Sort = sort
  9565. ftList = append(ftList, ft)
  9566. }
  9567. if surplus == "日粮" {
  9568. for _, ft := range ftList {
  9569. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9570. }
  9571. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9572. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9573. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9574. fmt.Println(err)
  9575. } else {
  9576. var sort int64
  9577. for _, ft := range ftList {
  9578. if ft.Fname == surplus {
  9579. sort = ft.Sort
  9580. break
  9581. }
  9582. }
  9583. if sort == 0 {
  9584. for _, ft := range ftList {
  9585. ft.Sort = ft.Sort + 1
  9586. }
  9587. } else {
  9588. for _, ft := range ftList {
  9589. if ft.Sort >= sort {
  9590. ft.Sort = ft.Sort + 1
  9591. }
  9592. }
  9593. }
  9594. for _, ft := range ftList {
  9595. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9596. }
  9597. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9598. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9599. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9600. if err != nil {
  9601. log.Println("PostDataByName-error-1: ", err)
  9602. fmt.Println(err)
  9603. return errors.New("配方修改失败!")
  9604. }
  9605. }
  9606. }
  9607. return nil
  9608. }
  9609. func FeedSurplus(fasion *gofasion.Fasion) {
  9610. tx := restful.Engine.NewSession()
  9611. defer tx.Close()
  9612. params := fasion.Get("parammaps")
  9613. feedId := params.Get("id").ValueStr()
  9614. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9615. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9616. }
  9617. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9618. // params := fasion.Get("parammaps")
  9619. // surplus := params.Get("surplus").ValueStr()
  9620. // surplusId := params.Get("surplusId").ValueStr()
  9621. tx := restful.Engine.NewSession()
  9622. defer tx.Close()
  9623. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9624. if surplusId != "0" {
  9625. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9626. if err != nil {
  9627. log.Println("PostDataByName-error-1: ", err)
  9628. return errors.New("配方修改失败!")
  9629. }
  9630. type ftdetail struct {
  9631. Id string
  9632. Fname string
  9633. Sort int64
  9634. }
  9635. ftList := make([]*ftdetail, 0)
  9636. for _, data := range dataList {
  9637. ft := new(ftdetail)
  9638. ft.Fname = data["fname"]
  9639. ft.Id = data["id"]
  9640. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9641. if err != nil {
  9642. log.Println("PostDataByName-error-2: ", err)
  9643. return err
  9644. }
  9645. ft.Sort = sort
  9646. ftList = append(ftList, ft)
  9647. }
  9648. if surplus == "日粮" {
  9649. for _, ft := range ftList {
  9650. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9651. }
  9652. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9653. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9654. pastureId, id, surplusId, surplusId, surplusId)
  9655. fmt.Println(err)
  9656. } else {
  9657. var sort int64
  9658. for _, ft := range ftList {
  9659. if ft.Fname == surplus {
  9660. sort = ft.Sort
  9661. break
  9662. }
  9663. }
  9664. if sort == 0 {
  9665. for _, ft := range ftList {
  9666. ft.Sort = ft.Sort + 1
  9667. }
  9668. } else {
  9669. for _, ft := range ftList {
  9670. if ft.Sort >= sort {
  9671. ft.Sort = ft.Sort + 1
  9672. }
  9673. }
  9674. }
  9675. for _, ft := range ftList {
  9676. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9677. }
  9678. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9679. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9680. id, surplusId, surplusId, sort, surplusId, pastureId)
  9681. if err != nil {
  9682. log.Println("PostDataByName-error-1: ", err)
  9683. fmt.Println(err)
  9684. return errors.New("配方修改失败!")
  9685. }
  9686. }
  9687. }
  9688. return nil
  9689. }
  9690. func GetLanguageStatus() string {
  9691. tx := restful.Engine.NewSession()
  9692. defer tx.Close()
  9693. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9694. if err != nil {
  9695. log.Println(err)
  9696. return "0"
  9697. }
  9698. return dataList[0]["inforvalue"]
  9699. }
  9700. func EditLanguage(c *gin.Context) {
  9701. appG := app.Gin{C: c}
  9702. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9703. fsions := gofasion.NewFasion(string(dataByte))
  9704. language := fsions.Get("language").ValueStr()
  9705. tx := restful.Engine.NewSession()
  9706. defer tx.Close()
  9707. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9708. if err != nil {
  9709. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9710. return
  9711. }
  9712. if language == "0" {
  9713. _, err := tx.Exec(`delete from dictlist `)
  9714. if err != nil {
  9715. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9716. return
  9717. }
  9718. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9719. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9720. if err != nil {
  9721. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9722. return
  9723. }
  9724. } else {
  9725. _, err := tx.Exec(`delete from dictlist `)
  9726. if err != nil {
  9727. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9728. return
  9729. }
  9730. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9731. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9732. if err != nil {
  9733. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9734. return
  9735. }
  9736. }
  9737. appG.Response(http.StatusOK, e.SUCCESS, true)
  9738. }
  9739. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9740. tx := restful.Engine.NewSession()
  9741. defer tx.Close()
  9742. 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
  9743. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9744. if err != nil {
  9745. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9746. return
  9747. }
  9748. for _, dataexcel := range barList {
  9749. // dataexcel := make(map[string]interface{}, 0)
  9750. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9751. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9752. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9753. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9754. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9755. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9756. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9757. // if err != nil {
  9758. // logs.Error(err)
  9759. // return
  9760. // }
  9761. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9762. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9763. // if err != nil {
  9764. // logs.Error(err)
  9765. // return
  9766. // }
  9767. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9768. continue
  9769. }
  9770. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9771. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9772. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9773. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9774. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9775. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9776. // /*
  9777. tx.SQL(` update lpplandtl1 set lweight = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9778. if err != nil {
  9779. logs.Error(err)
  9780. return
  9781. }
  9782. tx.SQL(` update fpdetail set ptuse = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9783. if err != nil {
  9784. logs.Error(err)
  9785. return
  9786. }
  9787. // */
  9788. exist, err := tx.SQL(` select id from feedp 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. if !exist {
  9794. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9795. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9796. if err != nil {
  9797. logs.Error(err)
  9798. return
  9799. }
  9800. }
  9801. var feedpargs []interface{}
  9802. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9803. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9804. if _, ok := dataexcel["ftname"]; ok {
  9805. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9806. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9807. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9808. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9809. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9810. } else {
  9811. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9812. }
  9813. if _, ok := dataexcel["ptsfname"]; ok {
  9814. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9815. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9816. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9817. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9818. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9819. } else {
  9820. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9821. }
  9822. upFeedpSql += " where barname = ? and pastureid = ? "
  9823. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9824. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9825. if err != nil {
  9826. logs.Error(err)
  9827. return
  9828. }
  9829. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9830. if err != nil {
  9831. logs.Error(err)
  9832. return
  9833. }
  9834. if !exist1 {
  9835. _, 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) `,
  9836. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9837. if err != nil {
  9838. logs.Error(err)
  9839. return
  9840. }
  9841. }
  9842. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9843. if err != nil {
  9844. logs.Error(err)
  9845. return
  9846. }
  9847. if !exist2 {
  9848. _, 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) `,
  9849. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9850. if err != nil {
  9851. logs.Error(err)
  9852. return
  9853. }
  9854. }
  9855. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9856. if err != nil {
  9857. logs.Error(err)
  9858. return
  9859. }
  9860. if !exist3 {
  9861. _, 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) `,
  9862. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9863. if err != nil {
  9864. logs.Error(err)
  9865. return
  9866. }
  9867. }
  9868. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9869. if err != nil {
  9870. logs.Error(err)
  9871. return
  9872. }
  9873. if !exist4 {
  9874. _, 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) `,
  9875. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9876. if err != nil {
  9877. logs.Error(err)
  9878. return
  9879. }
  9880. }
  9881. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9882. if err != nil {
  9883. logs.Error(err)
  9884. return
  9885. }
  9886. if !exist5 {
  9887. _, 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) `,
  9888. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9889. if err != nil {
  9890. logs.Error(err)
  9891. return
  9892. }
  9893. }
  9894. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9895. if err != nil {
  9896. logs.Error(err)
  9897. return
  9898. }
  9899. if !exist6 {
  9900. _, 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) `,
  9901. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9902. if err != nil {
  9903. logs.Error(err)
  9904. return
  9905. }
  9906. }
  9907. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9908. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9909. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9910. and pastureid = ? and times = ?`
  9911. var fpdargs1 []interface{}
  9912. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9913. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9914. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9915. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9916. if err != nil {
  9917. fmt.Println(err)
  9918. return
  9919. }
  9920. var fpdargs2 []interface{}
  9921. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9922. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9923. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9924. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9925. if err != nil {
  9926. fmt.Println(err)
  9927. return
  9928. }
  9929. var fpdargs3 []interface{}
  9930. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9931. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9932. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9933. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9934. if err != nil {
  9935. fmt.Println(err)
  9936. return
  9937. }
  9938. var fpdargs4 []interface{}
  9939. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9940. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9941. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9942. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9943. if err != nil {
  9944. fmt.Println(err)
  9945. return
  9946. }
  9947. var fpdargs5 []interface{}
  9948. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9949. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9950. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9951. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9952. if err != nil {
  9953. fmt.Println(err)
  9954. return
  9955. }
  9956. var fpdargs6 []interface{}
  9957. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  9958. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9959. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  9960. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  9961. if err != nil {
  9962. fmt.Println(err)
  9963. return
  9964. }
  9965. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  9966. 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()
  9967. if err != nil {
  9968. return
  9969. }
  9970. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9971. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9972. upFpdetailList := make([]*upFpdetail, 0)
  9973. for _, newfpd := range newList {
  9974. for _, oldfpd := range oldFpdList {
  9975. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  9976. var oldweight, newweight float64
  9977. if oldfpd["weight"] != nil {
  9978. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  9979. }
  9980. if newfpd["weight"] != nil {
  9981. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  9982. }
  9983. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  9984. upFpdetailList = append(upFpdetailList, &upFpdetail{
  9985. Old: oldweight,
  9986. New: newweight,
  9987. Times: newfpd["times"].(int64),
  9988. Ptid: newfpd["ptid"].(int64),
  9989. Fweight: fweight,
  9990. Id: oldfpd["id"].(int64),
  9991. })
  9992. break
  9993. }
  9994. }
  9995. }
  9996. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  9997. }
  9998. }
  9999. func AddXxwFtdetail(c *gin.Context) {
  10000. appG := app.Gin{C: c}
  10001. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  10002. c.Bind(&xxwFtdetailList)
  10003. tx := restful.Engine.NewSession()
  10004. defer tx.Close()
  10005. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  10006. if err != nil {
  10007. logs.Error(err)
  10008. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10009. }
  10010. _, err = tx.Insert(xxwFtdetailList)
  10011. if err != nil {
  10012. logs.Error(err)
  10013. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10014. }
  10015. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  10016. appG.Response(http.StatusOK, e.SUCCESS, true)
  10017. }
  10018. func AddXxwFeedtemplet(c *gin.Context) {
  10019. appG := app.Gin{C: c}
  10020. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  10021. c.Bind(&xxwFeedtempletList)
  10022. tx := restful.Engine.NewSession()
  10023. defer tx.Close()
  10024. pastureinfo := new(udPastureInfo)
  10025. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  10026. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  10027. if err != nil {
  10028. logs.Error(err)
  10029. return
  10030. }
  10031. for _, ft := range xxwFeedtempletList {
  10032. ids, err := setting.SnowIds.NextId()
  10033. if err != nil {
  10034. ids = time.Now().UnixNano()
  10035. logging.Info("create SnowIds err", err)
  10036. }
  10037. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  10038. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  10039. ft.RecipeobjName, ft.RecipeobjName)
  10040. if err != nil {
  10041. logs.Error(err)
  10042. return
  10043. }
  10044. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  10045. _, 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')),
  10046. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  10047. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  10048. if err != nil {
  10049. logs.Error(err)
  10050. return
  10051. }
  10052. }
  10053. appG.Response(http.StatusOK, e.SUCCESS, true)
  10054. }
  10055. func ProcessExcel(c *gin.Context) {
  10056. appG := app.Gin{C: c}
  10057. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10058. fasion := gofasion.NewFasion(string(dataByte))
  10059. params := fasion.Get("parammaps")
  10060. pastureid := params.Get("pastureid").ValueStr()
  10061. startTime := params.Get("startTime").ValueStr()
  10062. stopTime := params.Get("stopTime").ValueStr()
  10063. iscompleted := params.Get("iscompleted").ValueStr()
  10064. lpplantype := params.Get("lpplantype").ValueStr()
  10065. error := params.Get("error").ValueStr()
  10066. hlwc1 := params.Get("hlwc1").ValueStr()
  10067. hlwc2 := params.Get("hlwc2").ValueStr()
  10068. slwc1 := params.Get("slwc1").ValueStr()
  10069. slwc2 := params.Get("slwc2").ValueStr()
  10070. hlzq1 := params.Get("hlzq1").ValueStr()
  10071. hlzq2 := params.Get("hlzq2").ValueStr()
  10072. slzq1 := params.Get("slzq1").ValueStr()
  10073. slzq2 := params.Get("slzq2").ValueStr()
  10074. fclassid := params.Get("fclassid").ValueStr()
  10075. minproesstime := params.Get("minproesstime").ValueStr()
  10076. maxproesstime := params.Get("maxproesstime").ValueStr()
  10077. tx := restful.Engine.NewSession()
  10078. defer tx.Close()
  10079. planList, err := tx.SQL(`SELECT
  10080. 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
  10081. FROM downloadedplan d
  10082. join pasture p on p.pastureid = d.pastureid
  10083. WHERE d.pastureid= ? and d.intime IS NOT NULL
  10084. AND mydate >= ? AND mydate <= ?
  10085. AND (iscompleted=? or ?='')
  10086. AND (lpplantype = ? or ? = '')
  10087. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  10088. 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
  10089. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  10090. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10091. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  10092. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10093. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  10094. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10095. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  10096. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10097. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  10098. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  10099. 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,
  10100. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  10101. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  10102. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  10103. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10104. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  10105. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  10106. or (?= '' and ? = '' ))
  10107. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  10108. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  10109. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  10110. maxproesstime, minproesstime, maxproesstime).QueryString()
  10111. if err != nil {
  10112. logs.Error(err)
  10113. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10114. return
  10115. }
  10116. planExecList, err := tx.SQL(`SELECT
  10117. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10118. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10119. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  10120. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10121. ) proesstime,
  10122. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10123. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  10124. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10125. sumproesstime, d1.pid,
  10126. d1.sort,
  10127. d1.fname,
  10128. d1.lweight,
  10129. d1.actualweightminus,
  10130. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  10131. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  10132. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  10133. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  10134. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  10135. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  10136. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  10137. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10138. d1.begintime stoptime,
  10139. d1.lastactualweight,
  10140. d1.actualweight,
  10141. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  10142. case d1.buttontype
  10143. when 1 then '自动'
  10144. when 2 then '手动'
  10145. when 3 then '手动'
  10146. end,
  10147. case d1.buttontype
  10148. when 1 then 'Automatic'
  10149. when 2 then 'Manual'
  10150. when 3 then 'Manual'
  10151. end
  10152. ) buttontype
  10153. FROM
  10154. downloadplandtl1_exec d1
  10155. WHERE d1.date between ? and ?
  10156. ORDER BY sort
  10157. `, startTime, stopTime).QueryString()
  10158. if err != nil {
  10159. logs.Error(err)
  10160. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10161. return
  10162. }
  10163. planExec2, err := tx.SQL(`SELECT
  10164. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  10165. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10166. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10167. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  10168. ) proesstime,
  10169. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  10170. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10171. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  10172. d1.sort,
  10173. d1.fname,
  10174. d1.lweight,
  10175. d1.actualweightminus,
  10176. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  10177. ABS(d1.lweight- d1.actualweightminus) diff,
  10178. 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,
  10179. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10180. d1.begintime stoptime,
  10181. d1.lastactualweight,
  10182. d1.actualweight,d1.pid
  10183. FROM
  10184. downloadplandtl2 d1
  10185. WHERE d1.date between ? and ?
  10186. ORDER BY sort`, startTime, stopTime).QueryString()
  10187. if err != nil {
  10188. logs.Error(err)
  10189. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10190. return
  10191. }
  10192. // 创建一个新的 Excel 文件
  10193. f := excelizexuri.NewFile()
  10194. // 创建工作表名称
  10195. sheetName := "Sheet1"
  10196. // border := []excelizexuri.Border{
  10197. // {Type: "left", Color: "000000", Style: 1},
  10198. // {Type: "right", Color: "000000", Style: 1},
  10199. // {Type: "top", Color: "000000", Style: 1},
  10200. // {Type: "bottom", Color: "000000", Style: 1},
  10201. // }
  10202. // 创建新的样式
  10203. style := &excelizexuri.Style{
  10204. // Border: border,
  10205. Alignment: &excelizexuri.Alignment{
  10206. Vertical: "center",
  10207. Horizontal: "center",
  10208. ShrinkToFit: true,
  10209. WrapText: true,
  10210. },
  10211. }
  10212. styleTitle := &excelizexuri.Style{
  10213. Fill: excelizexuri.Fill{
  10214. Color: []string{"FFFF0000"}, // 尝试使用完整的ARGB格式
  10215. },
  10216. // Border: border,
  10217. Font: &excelizexuri.Font{
  10218. Bold: true, // 加粗
  10219. Size: 24, // 字体大小
  10220. // Name: "宋体", // 字体名称
  10221. // WrapText :true,
  10222. Color: "000000", // 字体颜色(黑色)
  10223. },
  10224. Alignment: &excelizexuri.Alignment{
  10225. Vertical: "center", // 垂直居中
  10226. Horizontal: "center", // 水平居中
  10227. ShrinkToFit: true,
  10228. WrapText: true,
  10229. },
  10230. }
  10231. // 创建样式 ID
  10232. styleTitleId, err := f.NewStyle(styleTitle)
  10233. if err != nil {
  10234. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10235. return
  10236. }
  10237. // 创建样式 ID
  10238. styleID, err := f.NewStyle(style)
  10239. if err != nil {
  10240. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10241. return
  10242. }
  10243. // 合并单元格并设置内容
  10244. f.MergeCell(sheetName, "A1", "K1")
  10245. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  10246. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  10247. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  10248. planExecMap := make(map[string][]map[string]string, 0)
  10249. for _, planExec := range planExecList {
  10250. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  10251. }
  10252. plan2Map := make(map[string][]map[string]string, 0)
  10253. for _, plan2 := range planExec2 {
  10254. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  10255. }
  10256. num := 2
  10257. var notBorder []int
  10258. for _, plan := range planList {
  10259. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  10260. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10261. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10262. for i, header := range headers {
  10263. // 从 A2 开始
  10264. if header == "开始日期" {
  10265. cell := "%" + fmt.Sprintf("c%d", num)
  10266. cell = fmt.Sprintf(cell, 'A'+i+1)
  10267. f.SetCellValue(sheetName, cell, header)
  10268. f.SetCellStyle(sheetName, cell, cell, styleID)
  10269. continue
  10270. }
  10271. cell := "%" + fmt.Sprintf("c%d", num)
  10272. cell = fmt.Sprintf(cell, 'A'+i)
  10273. f.SetCellValue(sheetName, cell, header)
  10274. f.SetCellStyle(sheetName, cell, cell, styleID)
  10275. }
  10276. num += 1
  10277. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  10278. cell := "%" + fmt.Sprintf("c%d", num)
  10279. cell = fmt.Sprintf(cell, 'A'+0)
  10280. f.SetCellValue(sheetName, cell, plan["pastureName"])
  10281. f.SetCellStyle(sheetName, cell, cell, styleID)
  10282. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  10283. cell = "%" + fmt.Sprintf("c%d", num)
  10284. cell = fmt.Sprintf(cell, 'A'+1)
  10285. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  10286. f.SetCellStyle(sheetName, cell, cell, styleID)
  10287. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  10288. cell = "%" + fmt.Sprintf("c%d", num)
  10289. cell = fmt.Sprintf(cell, 'A'+2)
  10290. f.SetCellValue(sheetName, cell, plan["projname"])
  10291. f.SetCellStyle(sheetName, cell, cell, styleID)
  10292. cell = "%" + fmt.Sprintf("c%d", num)
  10293. cell = fmt.Sprintf(cell, 'A'+3)
  10294. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10295. f.SetCellValue(sheetName, cell, plan["mydate"])
  10296. f.SetCellStyle(sheetName, cell, cell, styleID)
  10297. cell = "%" + fmt.Sprintf("c%d", num)
  10298. cell = fmt.Sprintf(cell, 'A'+6)
  10299. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10300. f.SetCellValue(sheetName, cell, plan["intime"])
  10301. f.SetCellStyle(sheetName, cell, cell, styleID)
  10302. num += 1
  10303. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10304. for i, header := range headers1 {
  10305. cell = "%" + fmt.Sprintf("c%d", num)
  10306. cell = fmt.Sprintf(cell, 'C'+i)
  10307. f.SetCellValue(sheetName, cell, header)
  10308. f.SetCellStyle(sheetName, cell, cell, styleID)
  10309. // maxWidth := len(header)
  10310. // colName := string('C' + i)
  10311. // f.SetColWidth(sheetName, colName, colName, 20)
  10312. f.SetColWidth(sheetName, header, header, 40)
  10313. }
  10314. num += 1
  10315. // 在循环外部创建红色样式(只创建一次)
  10316. redStyle := &excelizexuri.Style{
  10317. Fill: excelizexuri.Fill{
  10318. Type: "pattern",
  10319. Color: []string{"FF0000"},
  10320. Pattern: 1,
  10321. },
  10322. // Font: &excelizexuri.Font{
  10323. // Bold: true, // 加粗
  10324. // Size: 24, // 字体大小
  10325. // // Name: "宋体", // 字体名称
  10326. // // WrapText :true,
  10327. // Color: "FFFF0000", // 字体颜色(黑色)
  10328. // },
  10329. Alignment: &excelizexuri.Alignment{
  10330. Vertical: "center",
  10331. Horizontal: "center",
  10332. ShrinkToFit: true,
  10333. WrapText: true,
  10334. },
  10335. }
  10336. redStyleID, err := f.NewStyle(redStyle)
  10337. if err != nil {
  10338. c.String(http.StatusInternalServerError, "Failed to create red style: "+err.Error())
  10339. return
  10340. }
  10341. // 在循环内部正确使用条件判断
  10342. for _, planExec := range planExecMap[plan["id"]] {
  10343. var currentStyleID int
  10344. if planExec["abnormal"] == "1" {
  10345. currentStyleID = redStyleID
  10346. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, planExec["abnormal"]) // 调试
  10347. } else {
  10348. currentStyleID = styleID
  10349. }
  10350. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10351. sort, _ := strconv.Atoi(planExec["sort"])
  10352. f.SetCellValue(sheetName, cell, sort)
  10353. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10354. cell = fmt.Sprintf("D%d", num)
  10355. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  10356. f.SetCellValue(sheetName, cell, lweight)
  10357. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10358. cell = fmt.Sprintf("E%d", num)
  10359. if _, ok := planExec["actualweightminus"]; ok {
  10360. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  10361. f.SetCellValue(sheetName, cell, actualweightminus)
  10362. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10363. } else {
  10364. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  10365. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10366. }
  10367. cell = fmt.Sprintf("F%d", num)
  10368. f.SetCellValue(sheetName, cell, planExec["fname"])
  10369. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10370. cell = fmt.Sprintf("G%d", num)
  10371. if _, ok := planExec["diff"]; ok {
  10372. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  10373. f.SetCellValue(sheetName, cell, diff)
  10374. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10375. } else {
  10376. f.SetCellValue(sheetName, cell, planExec["diff"])
  10377. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10378. }
  10379. cell = fmt.Sprintf("H%d", num)
  10380. if _, ok := planExec["diffRate"]; ok {
  10381. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  10382. f.SetCellValue(sheetName, cell, diffRate)
  10383. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10384. } else {
  10385. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  10386. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10387. }
  10388. cell = fmt.Sprintf("I%d", num)
  10389. f.SetCellValue(sheetName, cell, planExec["intime"])
  10390. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10391. cell = fmt.Sprintf("J%d", num)
  10392. if _, ok := planExec["lastactualweight"]; ok {
  10393. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  10394. f.SetCellValue(sheetName, cell, lastactualweight)
  10395. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10396. } else {
  10397. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  10398. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10399. }
  10400. cell = fmt.Sprintf("K%d", num)
  10401. if _, ok := planExec["actualweight"]; ok {
  10402. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  10403. f.SetCellValue(sheetName, cell, actualweight)
  10404. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10405. } else {
  10406. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  10407. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10408. }
  10409. num += 1
  10410. }
  10411. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10412. for i, header := range headers2 {
  10413. cell := "%" + fmt.Sprintf("c%d", num)
  10414. cell = fmt.Sprintf(cell, 'C'+i)
  10415. f.SetCellValue(sheetName, cell, header)
  10416. f.SetCellStyle(sheetName, cell, cell, styleID)
  10417. maxWidth := len(header)
  10418. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  10419. }
  10420. num += 1
  10421. for _, plan2 := range plan2Map[plan["id"]] {
  10422. var currentStyleID int
  10423. if plan2["abnormal"] == "1" {
  10424. currentStyleID = redStyleID
  10425. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, plan2["abnormal"]) // 调试
  10426. } else {
  10427. currentStyleID = styleID
  10428. }
  10429. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10430. sort, _ := strconv.Atoi(plan2["sort"])
  10431. f.SetCellValue(sheetName, cell, sort)
  10432. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10433. cell = fmt.Sprintf("D%d", num)
  10434. f.SetCellValue(sheetName, cell, plan2["fname"])
  10435. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10436. cell = fmt.Sprintf("E%d", num)
  10437. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  10438. f.SetCellValue(sheetName, cell, lweight)
  10439. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10440. cell = fmt.Sprintf("F%d", num)
  10441. if _, ok := plan2["actualweightminus"]; ok {
  10442. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  10443. f.SetCellValue(sheetName, cell, actualweightminus)
  10444. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10445. } else {
  10446. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  10447. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10448. }
  10449. cell = fmt.Sprintf("G%d", num)
  10450. if _, ok := plan2["diff"]; ok {
  10451. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  10452. f.SetCellValue(sheetName, cell, diff)
  10453. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10454. } else {
  10455. f.SetCellValue(sheetName, cell, plan2["diff"])
  10456. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10457. }
  10458. cell = fmt.Sprintf("H%d", num)
  10459. if _, ok := plan2["diffRate"]; ok {
  10460. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  10461. f.SetCellValue(sheetName, cell, diffRate)
  10462. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10463. } else {
  10464. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  10465. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10466. }
  10467. cell = fmt.Sprintf("I%d", num)
  10468. f.SetCellValue(sheetName, cell, plan2["intime"])
  10469. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10470. cell = fmt.Sprintf("J%d", num)
  10471. if _, ok := plan2["lastactualweight"]; ok {
  10472. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  10473. f.SetCellValue(sheetName, cell, lastactualweight)
  10474. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10475. } else {
  10476. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  10477. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10478. }
  10479. cell = fmt.Sprintf("K%d", num)
  10480. if _, ok := plan2["lastactualweight"]; ok {
  10481. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  10482. f.SetCellValue(sheetName, cell, actualweight)
  10483. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10484. } else {
  10485. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  10486. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10487. }
  10488. num += 1
  10489. }
  10490. num += 1
  10491. notBorder = append(notBorder, num)
  10492. }
  10493. // for i := 2; i < num; i++ {
  10494. // exist := false
  10495. // for _, n := range notBorder {
  10496. // if i+1 == n {
  10497. // exist = true
  10498. // break
  10499. // }
  10500. // }
  10501. // if !exist {
  10502. // // 为 A-K 列设置边框
  10503. // for col := 'A'; col <= 'K'; col++ {
  10504. // cellName := fmt.Sprintf("%c%d", col, i)
  10505. // style, _ := f.NewStyle(&excelizexuri.Style{
  10506. // // Border: border,
  10507. // Alignment: &excelizexuri.Alignment{
  10508. // Vertical: "center",
  10509. // Horizontal: "center",
  10510. // ShrinkToFit: true,
  10511. // WrapText: true,
  10512. // },
  10513. // })
  10514. // f.SetCellStyle(sheetName, cellName, cellName, style)
  10515. // }
  10516. // }
  10517. // }
  10518. for col := 'A'; col <= 'K'; col++ {
  10519. colName := string(col)
  10520. switch colName {
  10521. case "A", "B": // 牧场名称、TMR列
  10522. f.SetColWidth(sheetName, colName, colName, 10)
  10523. case "C": // 操作编号列
  10524. f.SetColWidth(sheetName, colName, colName, 10)
  10525. case "D", "E": // 计划重量、实际重量列
  10526. f.SetColWidth(sheetName, colName, colName, 12)
  10527. case "F": // 代表成分/投料位置列
  10528. f.SetColWidth(sheetName, colName, colName, 20)
  10529. case "G", "H": // 误差数、准确率列
  10530. f.SetColWidth(sheetName, colName, colName, 12)
  10531. case "I": // 完成时间列
  10532. f.SetColWidth(sheetName, colName, colName, 15)
  10533. case "J", "K": // 起始读数重量、完成读数重量列
  10534. f.SetColWidth(sheetName, colName, colName, 15)
  10535. }
  10536. }
  10537. // 设置响应头
  10538. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10539. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10540. c.Header("Content-Transfer-Encoding", "binary")
  10541. // 写入 Excel 文件到响应
  10542. if err := f.Write(c.Writer); err != nil {
  10543. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10544. return
  10545. }
  10546. }
  10547. func RestartMqtt(c *gin.Context) {
  10548. appG := app.Gin{C: c}
  10549. // 发送 GET 请求到 MQTT 重启接口
  10550. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10551. if err != nil {
  10552. logging.Error("RestartMqtt request failed:", err)
  10553. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10554. return
  10555. }
  10556. defer resp.Body.Close()
  10557. // 读取响应内容f
  10558. body, err := ioutil.ReadAll(resp.Body)
  10559. if err != nil {
  10560. logging.Error("RestartMqtt read response failed:", err)
  10561. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10562. return
  10563. }
  10564. // 检查响应状态码
  10565. if resp.StatusCode != http.StatusOK {
  10566. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10567. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10568. return
  10569. }
  10570. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10571. }
  10572. func FpdBatchEditByWeight(c *gin.Context) {
  10573. appG := app.Gin{C: c}
  10574. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10575. fsions := gofasion.NewFasion(string(dataByte))
  10576. barList := fsions.Get("barList").Array()
  10577. pastureid := fsions.Get("pastureId").ValueStr()
  10578. tx := restful.Engine.NewSession()
  10579. defer tx.Close()
  10580. 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
  10581. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10582. if err != nil {
  10583. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10584. return
  10585. }
  10586. for _, barFsions := range barList {
  10587. dataexcel := make(map[string]interface{}, 0)
  10588. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10589. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10590. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10591. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10592. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10593. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10594. continue
  10595. }
  10596. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10597. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10598. // if err != nil {
  10599. // logs.Error(err)
  10600. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10601. // return
  10602. // }
  10603. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10604. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10605. // if err != nil {
  10606. // logs.Error(err)
  10607. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10608. // return
  10609. // }
  10610. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10611. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10612. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10613. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10614. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10615. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10616. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10617. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10618. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10619. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10620. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10621. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10622. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10623. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10624. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10625. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10626. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10627. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10628. if err != nil {
  10629. logs.Error(err)
  10630. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10631. return
  10632. }
  10633. if !ftexist {
  10634. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10635. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10636. if err != nil {
  10637. logs.Error(err)
  10638. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10639. return
  10640. }
  10641. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10642. if err != nil {
  10643. logs.Error(err)
  10644. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10645. return
  10646. }
  10647. }
  10648. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10649. if err != nil {
  10650. logs.Error(err)
  10651. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10652. return
  10653. }
  10654. if !exist {
  10655. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10656. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10657. if err != nil {
  10658. logs.Error(err)
  10659. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10660. return
  10661. }
  10662. }
  10663. var feedpargs []interface{}
  10664. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10665. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10666. if _, ok := dataexcel["ftname"]; ok {
  10667. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10668. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10669. // upFeedpSql += `,ftweight = ? `
  10670. // feedpargs = append(feedpargs, weight)
  10671. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10672. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10673. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10674. } else {
  10675. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10676. }
  10677. // if _, ok := dataexcel["ptsfname"]; ok {
  10678. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10679. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10680. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10681. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10682. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10683. // } else {
  10684. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10685. // }
  10686. upFeedpSql += " where barname = ? and pastureid = ? "
  10687. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10688. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10689. if err != nil {
  10690. logs.Error(err)
  10691. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10692. return
  10693. }
  10694. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10695. if err != nil {
  10696. logs.Error(err)
  10697. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10698. return
  10699. }
  10700. if !exist1 {
  10701. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10702. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10703. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10704. if err != nil {
  10705. logs.Error(err)
  10706. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10707. return
  10708. }
  10709. }
  10710. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10711. if err != nil {
  10712. logs.Error(err)
  10713. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10714. return
  10715. }
  10716. if !exist2 {
  10717. _, 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) `,
  10718. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10719. if err != nil {
  10720. logs.Error(err)
  10721. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10722. return
  10723. }
  10724. }
  10725. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10726. if err != nil {
  10727. logs.Error(err)
  10728. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10729. return
  10730. }
  10731. if !exist3 {
  10732. _, 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) `,
  10733. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10734. if err != nil {
  10735. logs.Error(err)
  10736. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10737. return
  10738. }
  10739. }
  10740. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10741. if err != nil {
  10742. logs.Error(err)
  10743. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10744. return
  10745. }
  10746. if !exist4 {
  10747. _, 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) `,
  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. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, 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 !exist5 {
  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 = ? ),?,5,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. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, 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 !exist6 {
  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 = ? ),?,6,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. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10786. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10787. and pastureid = ? and times = ?`
  10788. var fpdargs1 []interface{}
  10789. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10790. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10791. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10792. if err != nil {
  10793. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10794. return
  10795. }
  10796. var fpdargs2 []interface{}
  10797. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10798. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10799. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10800. if err != nil {
  10801. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10802. return
  10803. }
  10804. var fpdargs3 []interface{}
  10805. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10806. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10807. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10808. if err != nil {
  10809. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10810. return
  10811. }
  10812. var fpdargs4 []interface{}
  10813. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10814. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10815. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10816. if err != nil {
  10817. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10818. return
  10819. }
  10820. var fpdargs5 []interface{}
  10821. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10822. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10823. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10824. if err != nil {
  10825. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10826. return
  10827. }
  10828. var fpdargs6 []interface{}
  10829. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10830. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10831. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10832. if err != nil {
  10833. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10834. return
  10835. }
  10836. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10837. 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()
  10838. if err != nil {
  10839. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10840. return
  10841. }
  10842. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10843. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10844. upFpdetailList := make([]*upFpdetail, 0)
  10845. for _, newfpd := range newList {
  10846. for _, oldfpd := range oldFpdList {
  10847. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10848. var oldweight, newweight float64
  10849. if oldfpd["weight"] != nil {
  10850. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10851. }
  10852. if newfpd["weight"] != nil {
  10853. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10854. }
  10855. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10856. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10857. Old: oldweight,
  10858. New: newweight,
  10859. Times: newfpd["times"].(int64),
  10860. Ptid: newfpd["ptid"].(int64),
  10861. Fweight: fweight,
  10862. Id: oldfpd["id"].(int64),
  10863. })
  10864. break
  10865. }
  10866. }
  10867. }
  10868. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10869. }
  10870. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10871. }
  10872. func FtImportExcel(c *gin.Context) {
  10873. appG := app.Gin{C: c}
  10874. inputdata := ""
  10875. c.Request.ParseForm()
  10876. params := c.Request.Form
  10877. file, _, err := c.Request.FormFile("file")
  10878. if err != nil {
  10879. appG.Response(http.StatusOK, e.ERROR, err)
  10880. return
  10881. }
  10882. sqlnamestrs := params.Get("name")
  10883. sheetname := params.Get("sheetname")
  10884. pastureid := params.Get("pastureid")
  10885. //importParams := params.Get("importParams")
  10886. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10887. // 必输项参数 (字符串格式 "field1,field2,field3")
  10888. requiredParams := params.Get("requiredParams")
  10889. // 日期参数
  10890. dateParams := params.Get("dateParams")
  10891. // 数字参数
  10892. numParams := params.Get("numParams")
  10893. //将字符串分割开
  10894. dateParamslist := strings.Split(dateParams, ",")
  10895. requiredParamslist := strings.Split(requiredParams, ",")
  10896. numParamslist := strings.Split(numParams, ",")
  10897. queryData := make([]interface{}, 0)
  10898. sqlslist := strings.Split(sqlnamestrs, ",")
  10899. xlsx1, err := excelize.OpenReader(file)
  10900. if err != nil {
  10901. fmt.Println(err)
  10902. return
  10903. }
  10904. ok := 0
  10905. error := 0
  10906. isdone := true
  10907. rows := xlsx1.GetRows(sheetname)
  10908. // 限制10000条,多余的截取掉
  10909. if len(rows) > 10000 {
  10910. rows = rows[:10000]
  10911. }
  10912. tx := restful.Engine.NewSession()
  10913. ftNameList := make(map[string]interface{})
  10914. var ftNames []interface{}
  10915. for i, row := range rows {
  10916. if i > 0 {
  10917. entry := make(map[string]interface{})
  10918. outentry := make(map[string]interface{})
  10919. for j, colCell := range rows[0] {
  10920. for k, colCell1 := range row {
  10921. if j == k {
  10922. outentry[colCell] = colCell1
  10923. entry[colCell] = colCell1
  10924. }
  10925. }
  10926. }
  10927. inputdata = ""
  10928. a := ""
  10929. fmt.Println(outentry, entry)
  10930. //校验日期格式
  10931. for _, v := range dateParamslist {
  10932. if v == "" {
  10933. continue
  10934. }
  10935. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10936. dtime, err := TransfTime(d.(string))
  10937. if err != nil {
  10938. a = strings.Trim(v, " ")
  10939. break
  10940. }
  10941. outentry[strings.Trim(v, " ")] = dtime
  10942. }
  10943. }
  10944. if a != "" {
  10945. outentry["error_msg"] = a + " 格式错误"
  10946. error++
  10947. queryData = append(queryData, outentry)
  10948. continue
  10949. }
  10950. a = ""
  10951. //校验必填格式
  10952. for _, v := range requiredParamslist {
  10953. if v == "" {
  10954. continue
  10955. }
  10956. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  10957. a = strings.Trim(v, " ")
  10958. break
  10959. }
  10960. }
  10961. if a != "" {
  10962. outentry["error_msg"] = a + " 未填或格式错误"
  10963. error++
  10964. queryData = append(queryData, outentry)
  10965. continue
  10966. }
  10967. a = ""
  10968. //校验数字格式
  10969. for _, v := range numParamslist {
  10970. if v == "" {
  10971. continue
  10972. }
  10973. d, ok := outentry[strings.Trim(v, " ")]
  10974. if !ok || d == "" {
  10975. outentry[strings.Trim(v, " ")] = 0
  10976. } else {
  10977. var fl float64
  10978. switch d.(type) {
  10979. case string:
  10980. fl, err = strconv.ParseFloat(d.(string), 64)
  10981. }
  10982. if err != nil || fl < 0 {
  10983. a = strings.Trim(v, " ")
  10984. break
  10985. }
  10986. }
  10987. }
  10988. if a != "" {
  10989. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  10990. error++
  10991. queryData = append(queryData, outentry)
  10992. continue
  10993. }
  10994. err := tx.Begin()
  10995. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  10996. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  10997. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  10998. }
  10999. for _, sqlnamestr := range sqlslist {
  11000. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  11001. paramslist := strings.Split(paramslists, ",")
  11002. if len(paramslist) > 0 {
  11003. s_params := make([]interface{}, 0)
  11004. for _, value := range paramslist {
  11005. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  11006. if tempv, exists := c.Get("jwt_username"); exists {
  11007. s_params = append(s_params, tempv.(string))
  11008. } else {
  11009. s_params = append(s_params, "")
  11010. }
  11011. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  11012. s_params = append(s_params, pastureid)
  11013. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  11014. ids, err := setting.SnowIds.NextId()
  11015. if err != nil {
  11016. ids = time.Now().UnixNano()
  11017. logging.Info("create SnowIds err", err)
  11018. }
  11019. s_params = append(s_params, ids)
  11020. } else {
  11021. if outentry[strings.Trim(value, " ")] == nil {
  11022. s_params = append(s_params, "")
  11023. } else {
  11024. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  11025. }
  11026. }
  11027. }
  11028. outentry["input"] = inputdata
  11029. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  11030. if err != nil {
  11031. if tx != nil {
  11032. tx.Rollback()
  11033. }
  11034. if tx != nil {
  11035. tx.Close()
  11036. }
  11037. msg := geterrmsg(err.Error())
  11038. outentry["error_msg"] = msg
  11039. error++
  11040. queryData = append(queryData, outentry)
  11041. isdone = true
  11042. break
  11043. } else {
  11044. if len(returnmsgmap1) > 0 {
  11045. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  11046. if tx != nil {
  11047. tx.Rollback()
  11048. }
  11049. if tx != nil {
  11050. tx.Close()
  11051. }
  11052. msg := geterrmsg(va.(string))
  11053. outentry["error_msg"] = msg
  11054. error++
  11055. queryData = append(queryData, outentry)
  11056. isdone = true
  11057. break
  11058. }
  11059. }
  11060. isdone = false
  11061. }
  11062. }
  11063. }
  11064. ftNames = append(ftNames, outentry["配方名称"])
  11065. switch {
  11066. case err != nil:
  11067. if tx != nil {
  11068. tx.Rollback()
  11069. }
  11070. default:
  11071. if tx != nil {
  11072. err = tx.Commit()
  11073. }
  11074. }
  11075. if tx != nil {
  11076. tx.Close()
  11077. }
  11078. }
  11079. if !isdone {
  11080. ok++
  11081. isdone = true
  11082. }
  11083. }
  11084. go ftSync(ftNames, pastureid)
  11085. data := make(map[string]interface{})
  11086. data["result"] = queryData
  11087. data["success"] = ok
  11088. data["err_count"] = error
  11089. appG.Response(http.StatusOK, e.SUCCESS, data)
  11090. }
  11091. func ftSync(ftNameList []interface{}, pastureId string) {
  11092. tx := restful.Engine.NewSession()
  11093. defer tx.Close()
  11094. for _, ftName := range ftNameList {
  11095. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  11096. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  11097. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  11098. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  11099. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  11100. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  11101. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  11102. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  11103. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, ftName).QueryString()
  11104. FpdBatchEditGrfd(pastureId, values1)
  11105. }
  11106. }
  11107. func CopyFeedtemplet(c *gin.Context) {
  11108. appG := app.Gin{C: c}
  11109. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11110. fsion := gofasion.NewFasion(string(dataByte))
  11111. pastureid := fsion.Get("pastureid").ValueStr()
  11112. newName := fsion.Get("newName").ValueStr()
  11113. id := fsion.Get("id").ValueStr()
  11114. tx := restful.Engine.NewSession()
  11115. defer tx.Close()
  11116. count, err := tx.SQL(` select count(1) from feedtemplet where tname = ? `, newName).Count()
  11117. if err != nil {
  11118. appG.Response(http.StatusOK, e.ERROR, err)
  11119. return
  11120. }
  11121. if count > 0 {
  11122. appG.Response(http.StatusOK, e.ERROR, "配方名称重复!")
  11123. return
  11124. }
  11125. type ftCode struct {
  11126. Tcode string `xorm:"tcode"`
  11127. }
  11128. code := new(ftCode)
  11129. err = tx.SQL(`select if(left((select max(tcode) from feedtemplet where pastureid = ?),8) =
  11130. (select DATE_FORMAT(now(),"%Y%m%d")),(select max(tcode)+1 from feedtemplet where pastureid = ?),
  11131. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))) tcode`, pastureid, pastureid).GetFirst(code).Error
  11132. if err != nil {
  11133. appG.Response(http.StatusOK, e.ERROR, err)
  11134. return
  11135. }
  11136. if code.Tcode == "" {
  11137. appG.Response(http.StatusOK, e.ERROR, "配方编码生产失败!")
  11138. return
  11139. }
  11140. _, err = tx.Exec(`INSERT INTO feedtemplet(pastureid,tname,tcode,tcolor,ccid,ccname,fttype,fttypeid,source,
  11141. remark,enable,sort,volume,autozone)
  11142. select pastureid,?,?,tcolor,ccid,ccname,fttype,fttypeid,source,
  11143. remark,enable,sort,volume,autozone from feedtemplet where id = ? `, newName, code.Tcode, id)
  11144. if err != nil {
  11145. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11146. return
  11147. }
  11148. _, err = tx.Exec(`insert into ftdetail(pastureid,ftid,fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11149. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry)
  11150. select pastureid,(select id from feedtemplet where tcode = ? ),fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11151. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry
  11152. from ftdetail where ftid = ? `, code.Tcode, id)
  11153. if err != nil {
  11154. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11155. return
  11156. }
  11157. appG.Response(http.StatusOK, e.SUCCESS, true)
  11158. }
  11159. func Test(c *gin.Context) {
  11160. appG := app.Gin{C: c}
  11161. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11162. appG.Response(http.StatusOK, e.SUCCESS, string(dataByte))
  11163. }
  11164. func GetPlanDry(c *gin.Context) {
  11165. appG := app.Gin{C: c}
  11166. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11167. fsion := gofasion.NewFasion(string(dataByte))
  11168. date := fsion.Get("date").ValueStr()
  11169. tx := restful.Engine.NewSession()
  11170. defer tx.Close()
  11171. dataList, err := tx.SQL(`SELECT
  11172. t.feedtempletName,
  11173. ifnull(t.feedtempletPrice,0)feedtempletPrice,
  11174. ifnull(t.feedtempletWeight,0)feedtempletWeight,
  11175. ifnull(t.feedtempletDryWeight,0)feedtempletDryWeight,
  11176. t.tmrno,
  11177. t.bname,
  11178. t.barid,
  11179. t.dry,
  11180. t.actualweightminus,
  11181. t.mydate,
  11182. t.pasturename,
  11183. t.endDate,
  11184. t.startDate,
  11185. t.times,
  11186. -- 计算startDate和endDate的中间时间
  11187. ifnull(DATE_FORMAT(
  11188. DATE_ADD(
  11189. t.startDate,
  11190. INTERVAL TIMESTAMPDIFF(SECOND, t.startDate, t.endDate)/2 SECOND
  11191. ),
  11192. '%Y-%m-%d %H:%i:%s'
  11193. ),'') AS midTime
  11194. FROM (
  11195. SELECT
  11196. (SELECT sort FROM downloadedplan WHERE pid = d.pid AND mydate = d.mydate AND lpplantype IN (0,1)) tmrno,
  11197. b.bname,
  11198. b.id barid,
  11199. 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
  11200. JOIN downloadplandtl1 dd1 ON dd.id = dd1.pid
  11201. JOIN feednur fn ON fn.fid = dd1.fid
  11202. WHERE dd.pid = d.pid AND dd.mydate = d.mydate AND lpplantype IN (0,1,4))/100),2) dry,
  11203. 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,
  11204. DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate,
  11205. p.pasture_name pastureName,
  11206. DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endDate,
  11207. DATE_FORMAT(IFNULL(
  11208. (SELECT MAX(intime) FROM downloadplandtl2 d1
  11209. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d1.intime<d2.intime),
  11210. (SELECT MAX(intime) FROM downloadplandtl1_exec de
  11211. WHERE de.date=d2.date AND de.pastureid = d2.pastureid AND de.pid=d2.pid)
  11212. ), '%Y-%m-%d %H:%i:%s') startDate,
  11213. d.times ,
  11214. ( SELECT
  11215. round(SUM(
  11216. IF(ftd.preftid<>0,
  11217. ftd.fweight*IFNULL((SELECT SUM(ftd1.fweight*f1.dry/100)/SUM(ftd1.fweight) FROM ftdetaildate ftd1
  11218. JOIN feednur f1 ON f1.fid= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11219. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11220. ftd.fweight*f.dry/100)) ,2)
  11221. dryweight
  11222. FROM ftdetaildate ftd
  11223. LEFT JOIN feednur f ON f.fid= ftd.fid AND f.pastureid = ftd.pastureid
  11224. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletDryWeight,(
  11225. select
  11226. sum(ftd.fweight)
  11227. FROM ftdetaildate ftd
  11228. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletWeight,
  11229. ( SELECT
  11230. round(SUM(
  11231. IF(ftd.preftid<>0,
  11232. IFNULL((SELECT SUM(ftd1.fweight*f1.uprice) FROM ftdetaildate ftd1
  11233. JOIN feed f1 ON f1.id= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11234. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11235. ftd.fweight*f.uprice)) ,2)
  11236. dryweight
  11237. FROM ftdetaildate ftd
  11238. LEFT JOIN feed f ON f.id= ftd.fid AND f.pastureid = ftd.pastureid
  11239. WHERE ftd.ftid = d.tempid and ftd.date = d2.date )
  11240. feedtempletPrice,d.templetname feedtempletName
  11241. FROM downloadedplan d
  11242. JOIN downloadplandtl2 d2 ON d.id=d2.PID
  11243. JOIN bar b ON b.id = d2.fbarid
  11244. JOIN pasture p ON p.pastureid = d.pastureid
  11245. WHERE d.mydate = DATE_FORMAT(?,'%Y-%m-%d')
  11246. AND d2.type = 0
  11247. AND d.havebutton = 1
  11248. ) t
  11249. WHERE 1=1 `, date).QueryString()
  11250. if err != nil {
  11251. logs.Error(err)
  11252. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11253. return
  11254. }
  11255. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11256. }
  11257. func GetBar(c *gin.Context) {
  11258. appG := app.Gin{C: c}
  11259. tx := restful.Engine.NewSession()
  11260. defer tx.Close()
  11261. pastureinfo := new(udPastureInfo)
  11262. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  11263. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  11264. if err != nil {
  11265. logs.Error(err)
  11266. return
  11267. }
  11268. dataList, err := tx.SQL(` select id,bname from bar where pastureid = ?`, pastureinfo.Pastureid).QueryString()
  11269. if err != nil {
  11270. logs.Error(err)
  11271. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11272. return
  11273. }
  11274. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11275. }
  11276. func GetHomepage(c *gin.Context) {
  11277. appG := app.Gin{C: c}
  11278. tx := restful.Engine.NewSession()
  11279. defer tx.Close()
  11280. dataList, err := tx.SQL(` SELECT
  11281. ifnull((SELECT CONCAT(ROUND(if(SUM(lweight) <= SUM(iweight),SUM(lweight)/SUM(iweight),SUM(iweight)/SUM(lweight))*100,2),'%') yesRateHL
  11282. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11283. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) ),'0.00%')yesRateHL, -- 昨日混料准确率
  11284. (SELECT CONCAT(ROUND(SUM(iweight)/SUM(lweight)*100,2),'%') yesRateHL
  11285. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11286. 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日混料准确率
  11287. ifnull((SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11288. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11289. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) ),'0.00%')yesRateSL, -- 昨日撒料准确率
  11290. (SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11291. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11292. 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日撒料准确率
  11293. 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),'%') -- 正确率
  11294. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11295. WHERE dt.pastureid = d.pastureid AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')),'0.00%') yesRateSLR, -- 昨日正确率
  11296. (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),'%') -- 正确率
  11297. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11298. WHERE dt.pastureid = d.pastureid
  11299. 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日正确率
  11300. (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,
  11301. (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,
  11302. 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,
  11303. 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,
  11304. ifnull(round(getSLtimeDiffSINGEL(d.pastureid,d.mydate),2),0.00) temtime,
  11305. ifnull(round(getSLtimeDiffMonth(d.pastureid) ,2),0.00) montime
  11306. FROM
  11307. (SELECT (select column_default as pastureid from information_schema.COLUMNS
  11308. 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()
  11309. if err != nil {
  11310. logs.Error(err)
  11311. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11312. return
  11313. }
  11314. dataList1, err := tx.SQL(`select
  11315. 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
  11316. LEFT JOIN ftdetail ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1'
  11317. join feed f on f.id = ifnull(ftd.fid,d1.fid) where d1.date = date_format(now(),'%Y-%m-%d') `).QueryString()
  11318. if err != nil {
  11319. logs.Error(err)
  11320. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11321. return
  11322. }
  11323. for _, data := range dataList {
  11324. for _, data1 := range dataList1 {
  11325. data["totalCost"] = data1["totalCost"]
  11326. data["cost"] = data1["cost"]
  11327. }
  11328. }
  11329. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11330. }
  11331. func GetFeedingManagement(c *gin.Context) {
  11332. appG := app.Gin{C: c}
  11333. typea := c.Query("typea") // 0 栏舍 1 日期
  11334. startDate := c.Query("startdate")
  11335. endDate := c.Query("enddate")
  11336. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11337. // fsion := gofasion.NewFasion(string(dataByte))
  11338. tx := restful.Engine.NewSession()
  11339. defer tx.Close()
  11340. if typea == "0" {
  11341. 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
  11342. SUM(
  11343. 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 ,
  11344. 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)*
  11345. 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 )),
  11346. 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)*
  11347. 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 ))
  11348. )
  11349. )actualweightminus ,
  11350. SUM(
  11351. 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 ,
  11352. 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)*
  11353. 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 )),
  11354. 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)*
  11355. 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 ))
  11356. ) * ifnull(fn.dry,0)
  11357. ) dryweight , SUM(
  11358. 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 ,
  11359. 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)*
  11360. 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 )),
  11361. 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)*
  11362. 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 ))
  11363. ) * ifnull(f.uprice,0)
  11364. ) priceweight
  11365. ,(select ccount from feedpdate where date = d1.date and barid = d2.fbarid) ccount,b.bname
  11366. FROM
  11367. downloadedplan d
  11368. JOIN downloadplandtl2 d2
  11369. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11370. JOIN downloadplandtl1 d1
  11371. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11372. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11373. 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
  11374. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11375. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11376. left join feednur fn on fn.fid = f.id
  11377. WHERE d.mydate BETWEEN ? AND ? GROUP BY d2.fbarid ) t `, startDate, endDate).QueryString()
  11378. if err != nil {
  11379. logs.Error(err)
  11380. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11381. return
  11382. }
  11383. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11384. } else {
  11385. 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
  11386. SUM(
  11387. 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 ,
  11388. 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)*
  11389. 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 )),
  11390. 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)*
  11391. 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 ))
  11392. )
  11393. )actualweightminus ,
  11394. SUM(
  11395. 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 ,
  11396. 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)*
  11397. 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 )),
  11398. 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)*
  11399. 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 ))
  11400. ) * ifnull(fn.dry,0)
  11401. ) dryweight , SUM(
  11402. 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 ,
  11403. 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)*
  11404. 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 )),
  11405. 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)*
  11406. 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 ))
  11407. ) * ifnull(f.uprice,0)
  11408. ) priceweight
  11409. ,(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
  11410. FROM
  11411. downloadedplan d
  11412. JOIN downloadplandtl2 d2
  11413. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11414. JOIN downloadplandtl1 d1
  11415. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11416. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11417. 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
  11418. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11419. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11420. left join feednur fn on fn.fid = f.id
  11421. WHERE d.mydate BETWEEN ? AND ?
  11422. GROUP BY d.mydate) 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. }
  11430. }
  11431. func GetFpdetailFname(c *gin.Context) {
  11432. appG := app.Gin{C: c}
  11433. // id := c.Query("id")
  11434. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11435. fsion := gofasion.NewFasion(string(dataByte))
  11436. id := fsion.Get("id").ValueDefaultStr("")
  11437. tx := restful.Engine.NewSession()
  11438. defer tx.Close()
  11439. fpdetailFnameList := make([]*models.FpdetailFname, 0)
  11440. err := tx.SQL(` SELECT
  11441. TRIM(ftid)ftid,TRIM(fid)fid,
  11442. IFNULL((SELECT fname FROM feed WHERE pastureid =ftdetail.pastureid AND id = ftdetail.fid),ftdetail. fname) fname,
  11443. fweight,sort,
  11444. TRIM(ftdetail.id) id, fweight /(select sum(fweight) from ftdetail where ftid = (select ftid from feedp where barid = ? ) ) sumFweight
  11445. FROM
  11446. ftdetail
  11447. WHERE ( ftid=(select ftid from feedp where barid = ? )) AND is_show = 1
  11448. ORDER BY ftdetail.sort,ftdetail.id `, id, id).Find(&fpdetailFnameList)
  11449. if err != nil {
  11450. logs.Error(err)
  11451. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11452. return
  11453. }
  11454. fpdetailList := make([]*models.Fpdetail, 0)
  11455. err = tx.SQL(`select id,barid,barname,times,weight from fpdetail where barid = ?`, id).Find(&fpdetailList)
  11456. if err != nil {
  11457. logs.Error(err)
  11458. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11459. return
  11460. }
  11461. for _, f := range fpdetailFnameList {
  11462. f.FWeight = 0
  11463. for _, fpd := range fpdetailList {
  11464. value := f.SumFWeight * fpd.Weight
  11465. // 将其四舍五入到小数点后两位
  11466. roundedValue := math.Round(value*100) / 100
  11467. if fpd.Times == 1 {
  11468. f.TimesOne = roundedValue
  11469. } else if fpd.Times == 2 {
  11470. f.TimesTwo = roundedValue
  11471. } else if fpd.Times == 3 {
  11472. f.TimesThree = roundedValue
  11473. } else if fpd.Times == 4 {
  11474. f.TimesFour = roundedValue
  11475. } else if fpd.Times == 5 {
  11476. f.TimesFive = roundedValue
  11477. } else if fpd.Times == 6 {
  11478. f.TimesSix = roundedValue
  11479. }
  11480. f.FWeight += value
  11481. }
  11482. }
  11483. fpdetailFname := new(models.FpdetailFname)
  11484. fpdetailFname.FName = "合计"
  11485. for _, f := range fpdetailFnameList {
  11486. fpdetailFname.TimesOne += f.TimesOne
  11487. fpdetailFname.TimesTwo += f.TimesTwo
  11488. fpdetailFname.TimesThree += f.TimesThree
  11489. fpdetailFname.TimesFour += f.TimesFour
  11490. fpdetailFname.TimesFive += f.TimesFive
  11491. fpdetailFname.TimesSix += f.TimesSix
  11492. fpdetailFname.FWeight += f.FWeight
  11493. f.FWeight = RoundFloat(f.FWeight, 2)
  11494. }
  11495. // 在处理代码中
  11496. fpdetailFname.TimesOne = RoundFloat(fpdetailFname.TimesOne, 2)
  11497. fpdetailFname.TimesTwo = RoundFloat(fpdetailFname.TimesTwo, 2)
  11498. fpdetailFname.TimesThree = RoundFloat(fpdetailFname.TimesThree, 2)
  11499. fpdetailFname.TimesFour = RoundFloat(fpdetailFname.TimesFour, 2)
  11500. fpdetailFname.TimesFive = RoundFloat(fpdetailFname.TimesFive, 2)
  11501. fpdetailFname.TimesSix = RoundFloat(fpdetailFname.TimesSix, 2)
  11502. fpdetailFname.FWeight = RoundFloat(fpdetailFname.FWeight, 2)
  11503. fpdetailFnameList = append(fpdetailFnameList, fpdetailFname)
  11504. appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11505. }
  11506. func RoundFloat(x float64, prec int) float64 {
  11507. output := math.Pow(10, float64(prec))
  11508. return math.Round(x*output) / output
  11509. }
  11510. func GetLyUdData(c *gin.Context) {
  11511. appG := app.Gin{C: c}
  11512. // id := c.Query("id")
  11513. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11514. fsion := gofasion.NewFasion(string(dataByte))
  11515. myDate := fsion.Get("myDate").ValueDefaultStr("")
  11516. times := fsion.Get("Times").ValueDefaultStr("")
  11517. name := fsion.Get("name").ValueDefaultStr("")
  11518. tx := restful.Engine.NewSession()
  11519. defer tx.Close()
  11520. if name == "dateplanlist" {
  11521. 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
  11522. join pasture p on dl.pastureId=p.pastureid JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId
  11523. where dl.Mydate = ? AND dl.lpplanType =0 and dl.Times= ? GROUP BY dl.id union all
  11524. 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
  11525. from downloadedplan dl join pasture p on dl.pastureId=p.pastureid
  11526. 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
  11527. where dl.Mydate = ? AND dl.lpplanType =2 and dl.Times= ?
  11528. GROUP BY dl.id order by ProjName `, myDate, times, myDate, times).Query().List()
  11529. fmt.Println(err)
  11530. appG.Response(http.StatusOK, e.SUCCESS, data)
  11531. return
  11532. } else if name == "getAddFeed" {
  11533. 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,
  11534. 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,
  11535. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM downloadedplan dd
  11536. JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11537. 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
  11538. join feedtemplet ftd on ftd.id = d.tempid and ftd.pastureId = d.pastureId
  11539. JOIN feed f ON f.id = d1.fid AND f.pastureId = d.pastureId
  11540. WHERE DATE_FORMAT(dd.Mydate ,'%Y-%m-%d' ) = ? and dd.Times =? and d1.type = 0
  11541. 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,
  11542. round(d1.LWEIGHT *(ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and ftid = ftdd.ftid and pastureId = d.pastureId )),2) expWeight,
  11543. 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,
  11544. '' 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,
  11545. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM
  11546. downloadedplan dd JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11547. 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
  11548. join feedtemplet ftd on ftd.id = d1.fid and ftd.pastureId = d.pastureId
  11549. join ftdetaildate ftdd on ftdd.ftid = ftd.id and ftdd.date = d.Mydate and ftdd.pastureId = d.pastureId
  11550. join feed f on f.id = ftdd.fid and f.pastureId = d.pastureId
  11551. 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()
  11552. appG.Response(http.StatusOK, e.SUCCESS, data)
  11553. return
  11554. } else if name == "getDeleteFeed" {
  11555. 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,
  11556. 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 ,
  11557. (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
  11558. ,d2.xxwBarCode as penId,if(d.lpplanType=2,(select id from downloadedplan p where p.pid=d.pid and p.mydate=? and p.Times=?
  11559. and p.lpplanType=1 limit 1),d2.pid) Id from downloadedplan d LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID
  11560. and d.pastureId=d2.pastureId where d.mydate=? AND d.lpplanType in (0,2) and d.Times=?`, myDate, times, myDate, times).Query().List()
  11561. appG.Response(http.StatusOK, e.SUCCESS, data)
  11562. return
  11563. }
  11564. // appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11565. }