ops.go 459 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663
  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. // fmt.Println(fsion.Get("userId").ValueStr(),"fsion.Get.ValueStr()")
  2982. FpdBatchEditGrfd(fmt.Sprintf("%v", parammaps["pastureid"]), values1)
  2983. // 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 ,
  2984. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2985. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2986. // UNION
  2987. // 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 ,
  2988. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2989. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2990. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2991. // lpplanList := make([]*lpplanStruct, 0)
  2992. // err = tx.SQL(`select id,times,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpplan.pastureid ) = 0 ,
  2993. // ifnull((select maxstirfeed from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),100000),(select ifnull(volume,0) from tmr where id = lpplan.tmrid ) *
  2994. // (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)
  2995. // if err != nil {
  2996. // logs.Error(err, 1)
  2997. // return
  2998. // }
  2999. // lppidlist := []string{}
  3000. // for _, lpp := range lpplanList {
  3001. // lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  3002. // }
  3003. // if len(lppidlist) <= 0 {
  3004. // appG.Response(http.StatusOK, e.SUCCESS, true)
  3005. // return
  3006. // }
  3007. // lpplandtl1AllList := make([]*lpplandtl1, 0)
  3008. // err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  3009. // order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  3010. // if err != nil {
  3011. // // tx.Rollback()
  3012. // logs.Error(err, 2, parammaps["pastureid"])
  3013. // return
  3014. // }
  3015. // for _, lpp := range lpplandtl1AllList {
  3016. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  3017. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  3018. // if err != nil {
  3019. // logs.Error(err)
  3020. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3021. // return
  3022. // }
  3023. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3024. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  3025. // if err != nil {
  3026. // logs.Error(err)
  3027. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3028. // return
  3029. // }
  3030. // }
  3031. // var wg sync.WaitGroup
  3032. // for _, old := range fpdOldDataList {
  3033. // for _, fpd := range fpdDataList {
  3034. // wg.Add(1)
  3035. // go func(old, fpd map[string]interface{}) {
  3036. // updateLppandList := make([]*lpplandtl1, 0)
  3037. // defer wg.Done()
  3038. // if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3039. // fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3040. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3041. // oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3042. // // if weight > oldweight {
  3043. // // return
  3044. // // }
  3045. // var w float64
  3046. // var status int
  3047. // if weight < oldweight {
  3048. // if weight >= 0 {
  3049. // return
  3050. // }
  3051. // w = weight
  3052. // status = 0
  3053. // } else {
  3054. // if oldweight > 0 {
  3055. // return
  3056. // }
  3057. // w = weight
  3058. // status = 1
  3059. // }
  3060. // // fweight = w
  3061. // for _, lpp := range lpplanList {
  3062. // var fweight float64
  3063. // var lweight float64
  3064. // lpplandtl1List := make([]*lpplandtl1, 0)
  3065. // fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3066. // for _, lppland := range lpplandtl1AllList {
  3067. // if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3068. // lpplandtl1List = append(lpplandtl1List, lppland)
  3069. // }
  3070. // }
  3071. // if len(lpplandtl1List) == 0 {
  3072. // continue
  3073. // }
  3074. // for _, lppland := range lpplandtl1List {
  3075. // lweight += lppland.Lweight
  3076. // }
  3077. // if status == 0 {
  3078. // if lweight <= 0 {
  3079. // continue
  3080. // }
  3081. // } else {
  3082. // if lpp.Maxweight <= lweight {
  3083. // continue
  3084. // }
  3085. // }
  3086. // for _, lppland := range lpplandtl1List {
  3087. // if fpdid == lppland.Fpdid {
  3088. // if status == 1 {
  3089. // // if w <= lppland.Lweight {
  3090. // if lpp.Maxweight <= lweight {
  3091. // continue
  3092. // }
  3093. // if w+lweight <= lpp.Maxweight {
  3094. // lppland.Lweight += w
  3095. // lweight += w
  3096. // fweight += w
  3097. // w = 0
  3098. // } else {
  3099. // w = w - (lpp.Maxweight - lweight)
  3100. // n := (lpp.Maxweight - lweight)
  3101. // lppland.Lweight = lppland.Lweight + n
  3102. // lweight += n
  3103. // fweight += n
  3104. // }
  3105. // } else {
  3106. // if lppland.Lweight == 0 {
  3107. // continue
  3108. // }
  3109. // if w+lppland.Lweight >= 0 {
  3110. // lppland.Lweight = lppland.Lweight + w
  3111. // lweight = lweight + w
  3112. // fweight = fweight + w
  3113. // w = 0
  3114. // } else {
  3115. // w = w + lppland.Lweight
  3116. // lweight = lweight - lppland.Lweight
  3117. // fweight = fweight - lppland.Lweight
  3118. // lppland.Lweight = 0
  3119. // }
  3120. // }
  3121. // updateLppandList = append(updateLppandList, lppland)
  3122. // break
  3123. // }
  3124. // }
  3125. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3126. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3127. // WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3128. // if err != nil {
  3129. // // tx.Rollback()
  3130. // logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3131. // return
  3132. // }
  3133. // for _, lppland := range updateLppandList {
  3134. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3135. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3136. // if err != nil {
  3137. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3138. // // tx.Rollback()
  3139. // logs.Error(err, 3)
  3140. // return
  3141. // }
  3142. // // defer wg.Done()
  3143. // }
  3144. // updateLppandList = []*lpplandtl1{}
  3145. // if w == 0 {
  3146. // break
  3147. // }
  3148. // }
  3149. // }
  3150. // }(old, fpd)
  3151. // }
  3152. // }
  3153. // wg.Wait()
  3154. }
  3155. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3156. if err != nil {
  3157. logs.Error(err)
  3158. appG.Response(http.StatusOK, e.ERROR, false)
  3159. return
  3160. }
  3161. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3162. if err != nil {
  3163. logs.Error(err)
  3164. appG.Response(http.StatusOK, e.ERROR, false)
  3165. return
  3166. }
  3167. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3168. if err != nil {
  3169. logs.Error(err)
  3170. appG.Response(http.StatusOK, e.ERROR, false)
  3171. return
  3172. }
  3173. now := createdate
  3174. userId:= fsion.Get("userId").ValueStr()
  3175. // for _, oldFpd := range oldFpdDataList {
  3176. for _, newFpd := range newFpdDataList {
  3177. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3178. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3179. // go func() {
  3180. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3181. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3182. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3183. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  3184. if err != nil {
  3185. logs.Error(err)
  3186. appG.Response(http.StatusOK, e.ERROR, false)
  3187. return
  3188. }
  3189. // }()
  3190. }
  3191. // break
  3192. // }
  3193. // }
  3194. // }
  3195. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3196. for _, newLpplandtl1 := range newLpplandtl1List {
  3197. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3198. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3199. // go func() {
  3200. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3201. background,cowcount,ccountradio,lweighthis,userId,createdate)
  3202. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3203. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3204. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3205. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3206. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3207. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], userId,now ).Execute()
  3208. if err != nil {
  3209. logs.Error(err)
  3210. appG.Response(http.StatusOK, e.ERROR, false)
  3211. return
  3212. }
  3213. // }()
  3214. // }
  3215. // break
  3216. // }
  3217. // }
  3218. }
  3219. // for _, oldFeedp := range oldFeedpList {
  3220. for _, newFeedp := range newFeedpList {
  3221. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3222. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3223. // go func() {
  3224. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3225. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3226. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3227. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3228. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3229. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3230. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3231. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  3232. // fmt.Println(userId,"33333333333333333333333333333333333")
  3233. if err != nil {
  3234. logs.Error(err)
  3235. appG.Response(http.StatusOK, e.ERROR, false)
  3236. return
  3237. }
  3238. }
  3239. // ,,parammaps["ftid"])
  3240. // surplus, surplusId, id, pastureId string
  3241. // FtdetailSurplusFt(parammaps["ftid"].)
  3242. ftList1, err := tx.SQL(` SELECT
  3243. f.id,
  3244. f.surplus surplusId,
  3245. f.pastureid,
  3246. s.surplus
  3247. FROM
  3248. feedtemplet f
  3249. JOIN surplus s ON s.id = f.surplus
  3250. WHERE
  3251. f.id = ?`, parammaps["ftid"]).QueryString()
  3252. for _, ft := range ftList1 {
  3253. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3254. }
  3255. appG.Response(http.StatusOK, e.SUCCESS, true)
  3256. }
  3257. type lpplandtlInfo struct {
  3258. Id int64 `xorm:"id"`
  3259. Pastureid int64 `xorm:"pastureid"`
  3260. Lppid int64 `xorm:"lppid"`
  3261. Barid int64 `xorm:"barid"`
  3262. Barname string `xorm:"barname"`
  3263. Fpdid int64 `xorm:"fpdid"`
  3264. Fttype int64 `xorm:"fttype"`
  3265. Lweight float64 `xorm:"lweight"`
  3266. Sort int64 `xorm:"sort"`
  3267. Tmrid int64 `xorm:"tmrid"`
  3268. Tmrname string `xorm:"tmrname"`
  3269. Cowcount int64 `xorm:"cowcount"`
  3270. Ccountradio float64 `xorm:"ccountradio"`
  3271. Background string `xorm:"background"`
  3272. Lweighthis float64 `xorm:"lweighthis"`
  3273. Maxweight float64 `xorm:"maxweight"`
  3274. }
  3275. func UpdateFpdetailBar(c *gin.Context) {
  3276. appG := app.Gin{C: c}
  3277. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3278. fsion := gofasion.NewFasion(string(dataByte))
  3279. pastureid := fsion.Get("pastureid").ValueStr()
  3280. id := fsion.Get("id").ValueStr()
  3281. tx := restful.Engine.NewSession()
  3282. tx.Begin()
  3283. 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 `,
  3284. pastureid, id).Query().List()
  3285. if err != nil {
  3286. logs.Error(err)
  3287. }
  3288. for _, fpd := range fpdList {
  3289. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3290. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3291. pastureid, fpd["id"]).Query().List()
  3292. if err != nil {
  3293. tx.Rollback()
  3294. logs.Error(err)
  3295. appG.Response(http.StatusOK, e.ERROR, false)
  3296. return
  3297. }
  3298. var lweight float64
  3299. for _, lppland := range lpplandList {
  3300. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3301. lweight += lweight1
  3302. }
  3303. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3304. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3305. if fpdweight >= ptuse && lweight == ptuse {
  3306. continue
  3307. } else {
  3308. if lweight <= fpdweight {
  3309. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3310. if err != nil {
  3311. tx.Rollback()
  3312. logs.Error(err)
  3313. appG.Response(http.StatusOK, e.ERROR, false)
  3314. return
  3315. }
  3316. } else {
  3317. weight := fpdweight - lweight
  3318. for _, lppland := range lpplandList {
  3319. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3320. if weight >= lpplandlweight {
  3321. weight = weight - lpplandlweight
  3322. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3323. if err != nil {
  3324. tx.Rollback()
  3325. logs.Error(err)
  3326. appG.Response(http.StatusOK, e.ERROR, false)
  3327. return
  3328. }
  3329. } else {
  3330. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3331. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3332. // if err != nil {
  3333. // tx.Rollback()
  3334. // logs.Error(err)
  3335. // appG.Response(http.StatusOK, e.ERROR, false)
  3336. // return
  3337. // }
  3338. weight = 0
  3339. break
  3340. }
  3341. }
  3342. }
  3343. }
  3344. }
  3345. fsionData := fsion.Get("data").Array()
  3346. for _, list := range fsionData {
  3347. ftmap := make(map[string]interface{})
  3348. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3349. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3350. ftmap["times"] = list.Get("times").ValueInt64()
  3351. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3352. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3353. // fmt.Println(ftmap)
  3354. /*
  3355. count, err := tx.SQL(` select count(1) from lpplandtl1 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 = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3357. if count == 1 {
  3358. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3359. and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3360. if err != nil {
  3361. tx.Rollback()
  3362. logs.Error(err)
  3363. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3364. return
  3365. }
  3366. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3367. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3368. if err != nil {
  3369. tx.Rollback()
  3370. logs.Error(err)
  3371. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3372. return
  3373. }
  3374. }
  3375. */
  3376. fpdDataList, err := tx.SQL(`
  3377. 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 ,
  3378. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3379. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3380. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3381. if err != nil {
  3382. tx.Rollback()
  3383. logs.Error(err)
  3384. }
  3385. for _, fpd := range fpdDataList {
  3386. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3387. fttype := -1
  3388. if fpd["fttype"].(string) == "1" {
  3389. fttype = 1
  3390. }
  3391. var fweight float64
  3392. var lweight float64
  3393. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3394. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  3395. t.maxstirfeed,(select ifnull(volume,0) from tmr where id = lpp.tmrid ) *
  3396. (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  3397. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3398. join tmr t on t.id = lpp.tmrid
  3399. where lppland.fpdid =?
  3400. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3401. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3402. if err != nil {
  3403. tx.Rollback()
  3404. logs.Error(err)
  3405. }
  3406. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3407. var w float64
  3408. var status int
  3409. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3410. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3411. if weight >= 0 {
  3412. continue
  3413. }
  3414. w = weight
  3415. status = 0
  3416. } else {
  3417. // continue
  3418. if weight <= 0 {
  3419. continue
  3420. }
  3421. w = weight
  3422. status = 1
  3423. }
  3424. // for _, lppland := range lpplandtl1List {
  3425. // lweight += lppland.Lweight
  3426. // }
  3427. for _, lppland := range lpplandtl1List {
  3428. lpplandInfo := new(lpplandtlInfo)
  3429. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3430. lweight = lpplandInfo.Lweight
  3431. if status == 1 {
  3432. // if w <= lppland.Lweight {
  3433. if lppland.Maxweight <= lweight {
  3434. continue
  3435. }
  3436. if w+lweight <= lppland.Maxweight {
  3437. lppland.Lweight += w
  3438. lweight += w
  3439. fweight += w
  3440. w = 0
  3441. } else {
  3442. w = w - (lppland.Maxweight - lweight)
  3443. n := (lppland.Maxweight - lweight)
  3444. lppland.Lweight = lppland.Lweight + n
  3445. lweight += n
  3446. fweight += n
  3447. }
  3448. } else {
  3449. if lppland.Lweight == 0 {
  3450. continue
  3451. }
  3452. if w+lppland.Lweight >= 0 {
  3453. lppland.Lweight = lppland.Lweight + w
  3454. lweight = lweight + w
  3455. fweight = fweight + w
  3456. w = 0
  3457. } else {
  3458. w = w + lppland.Lweight
  3459. lweight = lweight - lppland.Lweight
  3460. fweight = fweight - lppland.Lweight
  3461. lppland.Lweight = 0
  3462. }
  3463. }
  3464. if lppland.Lweight > 0 {
  3465. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3466. if err != nil {
  3467. tx.Rollback()
  3468. logs.Error(err)
  3469. return
  3470. }
  3471. } else {
  3472. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3473. if err != nil {
  3474. tx.Rollback()
  3475. logs.Error(err)
  3476. return
  3477. }
  3478. }
  3479. if w == 0 {
  3480. break
  3481. }
  3482. // break
  3483. }
  3484. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3485. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3486. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3487. if err != nil {
  3488. tx.Rollback()
  3489. logs.Error(err)
  3490. }
  3491. if w == 0 {
  3492. break
  3493. }
  3494. }
  3495. }
  3496. }
  3497. tx.Commit()
  3498. now := time.Now()
  3499. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3500. if err != nil {
  3501. logs.Error(err)
  3502. appG.Response(http.StatusOK, e.ERROR, false)
  3503. return
  3504. }
  3505. for _, newLpplandtl1 := range newLpplandtl1List {
  3506. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3507. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3508. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3509. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3510. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3511. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3512. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3513. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3514. if err != nil {
  3515. logs.Error(err)
  3516. appG.Response(http.StatusOK, e.ERROR, false)
  3517. return
  3518. }
  3519. }
  3520. appG.Response(http.StatusOK, e.SUCCESS, true)
  3521. }
  3522. func GetProcessAnalysis(c *gin.Context) {
  3523. appG := app.Gin{C: c}
  3524. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3525. fsion := gofasion.NewFasion(string(dataByte))
  3526. sqlnamestr := fsion.Get("name").ValueStr()
  3527. offset := fsion.Get("offset").ValueDefaultInt(0)
  3528. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3529. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3530. parammaps := fsion.Get("parammaps")
  3531. tx := restful.Engine.NewSession()
  3532. err := tx.Begin()
  3533. defer func() {
  3534. switch {
  3535. case err != nil:
  3536. logging.Error("tx.Begin 事务启动失败__error:", err)
  3537. if tx != nil {
  3538. tx.Rollback()
  3539. }
  3540. default:
  3541. if tx != nil {
  3542. err = tx.Commit()
  3543. }
  3544. }
  3545. if tx != nil {
  3546. tx.Close()
  3547. }
  3548. }()
  3549. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3550. s_params := make([]interface{}, 0)
  3551. paramslist := strings.Split(p, ",")
  3552. if len(paramslist) > 0 && p != "" {
  3553. for _, value := range paramslist {
  3554. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3555. if tempv, exists := c.Get("jwt_username"); exists {
  3556. s_params = append(s_params, tempv.(string))
  3557. } else {
  3558. s_params = append(s_params, "")
  3559. }
  3560. } else {
  3561. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3562. }
  3563. }
  3564. }
  3565. tmrtnameStr := ""
  3566. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3567. if len(tmrtnameStr) == 0 {
  3568. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3569. } else {
  3570. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3571. }
  3572. }
  3573. if len(tmrtnameStr) > 0 {
  3574. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3575. }
  3576. sql += " ORDER BY d.intime"
  3577. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3578. if err != nil {
  3579. logging.Error("GetDataByName err: ", err)
  3580. msg := geterrmsg(err.Error())
  3581. appG.Response(http.StatusOK, e.ERROR, msg)
  3582. } else {
  3583. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3584. }
  3585. }
  3586. func UpdateFeedtempletStatus(c *gin.Context) {
  3587. appG := app.Gin{C: c}
  3588. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3589. fsion := gofasion.NewFasion(string(dataByte))
  3590. parammaps := fsion.Get("parammaps")
  3591. tx := restful.Engine.NewSession()
  3592. tx.Begin()
  3593. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3594. if err != nil {
  3595. tx.Rollback()
  3596. logs.Error(err)
  3597. appG.Response(http.StatusOK, e.ERROR, err)
  3598. return
  3599. }
  3600. tx.Commit()
  3601. appG.Response(http.StatusOK, e.SUCCESS, true)
  3602. }
  3603. func AddFtdry(c *gin.Context) {
  3604. appG := app.Gin{C: c}
  3605. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3606. fsion := gofasion.NewFasion(string(dataByte))
  3607. sqlnamestr := fsion.Get("name").ValueStr()
  3608. s_params := make([]interface{}, 0)
  3609. tx := restful.Engine.NewSession()
  3610. err := tx.Begin()
  3611. defer func() {
  3612. switch {
  3613. case err != nil:
  3614. if tx != nil {
  3615. tx.Rollback()
  3616. }
  3617. default:
  3618. if tx != nil {
  3619. err = tx.Commit()
  3620. }
  3621. }
  3622. if tx != nil {
  3623. tx.Close()
  3624. }
  3625. }()
  3626. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3627. if sql != "" {
  3628. parammaps := fsion.Get("parammaps")
  3629. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3630. paramslist := strings.Split(p, ",")
  3631. if len(paramslist) > 0 && p != "" {
  3632. for _, value := range paramslist {
  3633. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3634. if tempv, exists := c.Get("jwt_username"); exists {
  3635. s_params = append(s_params, tempv.(string))
  3636. } else {
  3637. s_params = append(s_params, "")
  3638. }
  3639. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3640. ids, err := setting.SnowIds.NextId()
  3641. if err != nil {
  3642. ids = time.Now().UnixNano()
  3643. logging.Info("create SnowIds err", err)
  3644. }
  3645. s_params = append(s_params, ids)
  3646. } else {
  3647. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3648. }
  3649. }
  3650. }
  3651. var actweight float64
  3652. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3653. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3654. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3655. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3656. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3657. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3658. 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()
  3659. if err != nil {
  3660. logging.Error("AddFtdry err: ", err)
  3661. msg := geterrmsg(err.Error())
  3662. appG.Response(http.StatusOK, e.ERROR, msg)
  3663. }
  3664. if len(actweightList) > 0 {
  3665. for _, item := range actweightList {
  3666. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3667. if err != nil {
  3668. logging.Error("AddFtdry err: ", err)
  3669. msg := geterrmsg(err.Error())
  3670. appG.Response(http.StatusOK, e.ERROR, msg)
  3671. }
  3672. actweight = fl
  3673. }
  3674. } else {
  3675. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3676. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3677. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3678. if err != nil {
  3679. logging.Error("AddFtdry err: ", err)
  3680. msg := geterrmsg(err.Error())
  3681. appG.Response(http.StatusOK, e.ERROR, msg)
  3682. }
  3683. for _, item := range dryList {
  3684. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3685. if err != nil {
  3686. logging.Error("AddFtdry err: ", err)
  3687. msg := geterrmsg(err.Error())
  3688. appG.Response(http.StatusOK, e.ERROR, msg)
  3689. }
  3690. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3691. }
  3692. }
  3693. if sqlnamestr == "insertFtdry" {
  3694. s_params = append(s_params, actweight)
  3695. } else if sqlnamestr == "updateFtdry" {
  3696. sql = fmt.Sprintf(sql, actweight)
  3697. }
  3698. queryData, err := execDataBySqlT(sql, s_params, tx)
  3699. if err != nil {
  3700. logging.Error("AddFtdry err: ", err)
  3701. msg := geterrmsg(err.Error())
  3702. appG.Response(http.StatusOK, e.ERROR, msg)
  3703. } else {
  3704. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3705. }
  3706. } else {
  3707. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3708. }
  3709. }
  3710. func CheckDates(c *gin.Context) {
  3711. tx := restful.Engine.NewSession()
  3712. defer tx.Close()
  3713. appG := app.Gin{C: c}
  3714. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3715. tempval_ := make(map[string]interface{})
  3716. tempCommon := make(map[string]interface{})
  3717. tempval := make([]map[string]interface{}, 0)
  3718. err := json.Unmarshal(dataByte, &tempval_)
  3719. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3720. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3721. if err != nil {
  3722. } else {
  3723. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3724. tempCommon = v
  3725. }
  3726. if v, ok := tempval_["data"].([]interface{}); ok {
  3727. for _, Tvalue := range v {
  3728. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3729. tempval = append(tempval, v1)
  3730. }
  3731. }
  3732. }
  3733. if err == nil {
  3734. if tempv, exists := c.Get("jwt_username"); exists {
  3735. tempCommon["jwt_username"] = tempv.(string)
  3736. }
  3737. for _, paramvalue := range tempval {
  3738. if _, ok := paramvalue["resultname"]; !ok {
  3739. paramvalue["resultname"] = paramvalue["name"]
  3740. }
  3741. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3742. if err != nil {
  3743. logging.Error("ExecDataParam error:", err)
  3744. }
  3745. }
  3746. if err == nil {
  3747. vmsg := ""
  3748. for _, item := range tempval {
  3749. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3750. for _, childrenList := range list.([]interface{}) {
  3751. for k, children := range childrenList.(map[string]interface{}) {
  3752. if k != "children" {
  3753. continue
  3754. }
  3755. for _, v := range children.([]map[string]interface{}) {
  3756. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3757. if k1 == "list" {
  3758. for _, v2 := range v1.([]map[string]interface{}) {
  3759. if v2["vmsg"].(string) != "1" {
  3760. if len(vmsg) == 0 {
  3761. vmsg = v2["vmsg"].(string)
  3762. } else {
  3763. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3764. }
  3765. }
  3766. }
  3767. }
  3768. }
  3769. }
  3770. }
  3771. }
  3772. }
  3773. }
  3774. if len(vmsg) > 0 {
  3775. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3776. } else {
  3777. appG.Response(http.StatusOK, e.SUCCESS, true)
  3778. }
  3779. } else {
  3780. msg := geterrmsg(err.Error())
  3781. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3782. }
  3783. }
  3784. }
  3785. if err != nil {
  3786. msg := geterrmsg(err.Error())
  3787. appG.Response(http.StatusOK, e.ERROR, msg)
  3788. }
  3789. }
  3790. 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) {
  3791. sqlname := fasion["name"].(string)
  3792. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3793. if v, ok := fasion["type"]; ok {
  3794. sqltype = v.(string)
  3795. }
  3796. sql := ""
  3797. p := ""
  3798. s_params := make([]interface{}, 0)
  3799. if sqltype != "" {
  3800. sql, p = restful.GetSqlByName(sqlname, tx)
  3801. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3802. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3803. paramslist := strings.Split(p, ",")
  3804. if len(paramslist) > 0 && p != "" {
  3805. for _, value := range paramslist {
  3806. ss := ""
  3807. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3808. ids, err := setting.SnowIds.NextId()
  3809. if err != nil {
  3810. ids = time.Now().UnixNano()
  3811. logging.Info("create SnowIds err", err)
  3812. }
  3813. s_params = append(s_params, ids)
  3814. } else {
  3815. if ss == "" && CommonParamMap != nil {
  3816. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3817. ss = valuestring
  3818. tempstrb := strings.IndexAny(valuestring, "@")
  3819. tempstre := strings.IndexAny(valuestring, ".")
  3820. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3821. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3822. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3823. }
  3824. } else {
  3825. ss = ""
  3826. }
  3827. }
  3828. }
  3829. if ss == "" && ParentParamMap != nil {
  3830. ss = getParamValue_(v, value, ParentParamMap)
  3831. }
  3832. if ss == "" && sameParamMap != nil {
  3833. ss = getParamValue(v, value, sameParamMap)
  3834. }
  3835. if ss == "" && ParamMap != nil {
  3836. ss = getParamValue(v, value, ParamMap)
  3837. }
  3838. s_params = append(s_params, ss)
  3839. }
  3840. }
  3841. }
  3842. }
  3843. }
  3844. if sql == "" {
  3845. sqltype = ""
  3846. }
  3847. if sql != "" {
  3848. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3849. if err != nil {
  3850. return nil, err
  3851. }
  3852. // fmt.Println(tempValParam)
  3853. return tempValParam.(map[string]interface{}), nil
  3854. } else {
  3855. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3856. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3857. if err != nil {
  3858. return nil, err
  3859. }
  3860. return nil, err
  3861. }
  3862. }
  3863. return nil, nil
  3864. }
  3865. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3866. var err error
  3867. subarray, ok := fasion["children"]
  3868. if ok {
  3869. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3870. tempVal_arrary := make([]map[string]interface{}, 0)
  3871. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3872. tempVal_ := make(map[string]interface{})
  3873. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3874. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3875. } else {
  3876. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3877. }
  3878. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3879. if err != nil {
  3880. return err
  3881. }
  3882. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3883. }
  3884. v.(map[string]interface{})["children"] = tempVal_arrary
  3885. }
  3886. }
  3887. return nil
  3888. }
  3889. func FpdImportExcel(c *gin.Context) {
  3890. appG := app.Gin{C: c}
  3891. inputdata := ""
  3892. c.Request.ParseForm()
  3893. params := c.Request.Form
  3894. file, _, err := c.Request.FormFile("file")
  3895. if err != nil {
  3896. appG.Response(http.StatusOK, e.ERROR, err)
  3897. return
  3898. }
  3899. sqlnamestrs := params.Get("name")
  3900. sheetname := params.Get("sheetname")
  3901. pastureid := params.Get("pastureid")
  3902. // importParams := params.Get("importParams")
  3903. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3904. // 必输项参数 (字符串格式 "field1,field2,field3")
  3905. requiredParams := params.Get("requiredParams")
  3906. // 日期参数
  3907. dateParams := params.Get("dateParams")
  3908. // 数字参数
  3909. numParams := params.Get("numParams")
  3910. //将字符串分割开
  3911. dateParamslist := strings.Split(dateParams, ",")
  3912. requiredParamslist := strings.Split(requiredParams, ",")
  3913. numParamslist := strings.Split(numParams, ",")
  3914. queryData := make([]interface{}, 0)
  3915. sqlslist := strings.Split(sqlnamestrs, ",")
  3916. xlsx1, err := excelize.OpenReader(file)
  3917. if err != nil {
  3918. fmt.Println(err)
  3919. return
  3920. }
  3921. ok := 0
  3922. error := 0
  3923. isdone := true
  3924. tx := restful.Engine.NewSession()
  3925. defer tx.Close()
  3926. languageStatus := GetLanguageStatus()
  3927. if languageStatus == "0" {
  3928. 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
  3929. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3930. if err != nil {
  3931. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3932. return
  3933. }
  3934. rows := xlsx1.GetRows(sheetname)
  3935. // 限制10000条,多余的截取掉
  3936. if len(rows) > 10000 {
  3937. rows = rows[:10000]
  3938. }
  3939. dataList := make(map[string][]*upFpdetail, 0)
  3940. for i, row := range rows {
  3941. if i > 0 {
  3942. entry := make(map[string]interface{})
  3943. outentry := make(map[string]interface{})
  3944. for j, colCell := range rows[0] {
  3945. for k, colCell1 := range row {
  3946. if j == k {
  3947. outentry[colCell] = colCell1
  3948. entry[colCell] = colCell1
  3949. }
  3950. }
  3951. }
  3952. inputdata = ""
  3953. a := ""
  3954. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3955. //校验日期格式
  3956. for _, v := range dateParamslist {
  3957. if v == "" {
  3958. continue
  3959. }
  3960. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3961. dtime, err := TransfTime(d.(string))
  3962. if err != nil {
  3963. a = strings.Trim(v, " ")
  3964. break
  3965. }
  3966. outentry[strings.Trim(v, " ")] = dtime
  3967. }
  3968. }
  3969. if a != "" {
  3970. outentry["error_msg"] = a + " 格式错误"
  3971. error++
  3972. queryData = append(queryData, outentry)
  3973. continue
  3974. }
  3975. a = ""
  3976. //校验必填格式
  3977. for _, v := range requiredParamslist {
  3978. if v == "" {
  3979. continue
  3980. }
  3981. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3982. a = strings.Trim(v, " ")
  3983. break
  3984. }
  3985. }
  3986. if a != "" {
  3987. outentry["error_msg"] = a + " 未填或格式错误"
  3988. error++
  3989. queryData = append(queryData, outentry)
  3990. continue
  3991. }
  3992. a = ""
  3993. //校验数字格式
  3994. for _, v := range numParamslist {
  3995. if v == "" {
  3996. continue
  3997. }
  3998. d, ok := outentry[strings.Trim(v, " ")]
  3999. if !ok || d == "" {
  4000. outentry[strings.Trim(v, " ")] = 0
  4001. } else {
  4002. var fl float64
  4003. switch d.(type) {
  4004. case string:
  4005. fl, err = strconv.ParseFloat(d.(string), 64)
  4006. }
  4007. if err != nil || fl < 0 {
  4008. a = strings.Trim(v, " ")
  4009. break
  4010. }
  4011. }
  4012. }
  4013. if a != "" {
  4014. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  4015. error++
  4016. queryData = append(queryData, outentry)
  4017. continue
  4018. }
  4019. errExist := false
  4020. for _, sqlnamestr := range sqlslist {
  4021. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4022. paramslist := strings.Split(paramslists, ",")
  4023. if len(paramslist) > 0 {
  4024. s_params := make([]interface{}, 0)
  4025. for _, value := range paramslist {
  4026. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4027. if tempv, exists := c.Get("jwt_username"); exists {
  4028. s_params = append(s_params, tempv.(string))
  4029. } else {
  4030. s_params = append(s_params, "")
  4031. }
  4032. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4033. s_params = append(s_params, pastureid)
  4034. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4035. ids, err := setting.SnowIds.NextId()
  4036. if err != nil {
  4037. ids = time.Now().UnixNano()
  4038. logging.Info("create SnowIds err", err)
  4039. }
  4040. s_params = append(s_params, ids)
  4041. } else {
  4042. if outentry[strings.Trim(value, " ")] == nil {
  4043. s_params = append(s_params, "")
  4044. } else {
  4045. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4046. }
  4047. }
  4048. }
  4049. outentry["input"] = inputdata
  4050. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4051. if err != nil {
  4052. errExist = true
  4053. // if tx != nil {
  4054. // tx.Rollback()
  4055. // }
  4056. // if tx != nil {
  4057. // tx.Close()
  4058. // }
  4059. msg := geterrmsg(err.Error())
  4060. outentry["error_msg"] = msg
  4061. error++
  4062. queryData = append(queryData, outentry)
  4063. isdone = true
  4064. break
  4065. } else {
  4066. if len(returnmsgmap1) > 0 {
  4067. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4068. // if tx != nil {
  4069. // tx.Rollback()
  4070. // }
  4071. // if tx != nil {
  4072. // tx.Close()
  4073. // }
  4074. msg := geterrmsg(va.(string))
  4075. outentry["error_msg"] = msg
  4076. error++
  4077. queryData = append(queryData, outentry)
  4078. isdone = true
  4079. break
  4080. }
  4081. }
  4082. isdone = false
  4083. }
  4084. }
  4085. }
  4086. fmt.Println(outentry["栏舍名称"])
  4087. if !errExist {
  4088. dataexcel := make(map[string]interface{}, 0)
  4089. if _, ok := outentry["栏舍名称"]; ok {
  4090. dataexcel["barname"] = outentry["栏舍名称"]
  4091. }
  4092. if _, ok := outentry["实际牛头数"]; ok {
  4093. dataexcel["ccount"] = outentry["实际牛头数"]
  4094. }
  4095. // if _, ok := outentry["实际羊只数"]; ok {
  4096. // dataexcel["ccount"] = outentry["实际羊只数"]
  4097. // }
  4098. if _, ok := outentry["系数(%)"]; ok {
  4099. dataexcel["ratio"] = outentry["系数(%)"]
  4100. }
  4101. if _, ok := outentry["配方模板"]; ok {
  4102. dataexcel["ftname"] = outentry["配方模板"]
  4103. }
  4104. if _, ok := outentry["补料配方"]; ok {
  4105. dataexcel["ptsfname"] = outentry["补料配方"]
  4106. }
  4107. if _, ok := outentry["第一班比例(%)"]; ok {
  4108. dataexcel["1"] = outentry["第一班比例(%)"]
  4109. if fmt.Sprintf("%v", dataexcel["1"]) == "" {
  4110. dataexcel["1"] = 0
  4111. }
  4112. } else {
  4113. dataexcel["1"] = 0
  4114. }
  4115. if _, ok := outentry["第二班比例(%)"]; ok {
  4116. dataexcel["2"] = outentry["第二班比例(%)"]
  4117. if fmt.Sprintf("%v", dataexcel["2"]) == "" {
  4118. dataexcel["2"] = 0
  4119. }
  4120. } else {
  4121. dataexcel["2"] = 0
  4122. }
  4123. if _, ok := outentry["第三班比例(%)"]; ok {
  4124. dataexcel["3"] = outentry["第三班比例(%)"]
  4125. if fmt.Sprintf("%v", dataexcel["3"]) == "" {
  4126. dataexcel["3"] = 0
  4127. }
  4128. } else {
  4129. dataexcel["3"] = 0
  4130. }
  4131. if _, ok := outentry["第四班比例(%)"]; ok {
  4132. dataexcel["4"] = outentry["第四班比例(%)"]
  4133. if fmt.Sprintf("%v", dataexcel["4"]) == "" {
  4134. dataexcel["4"] = 0
  4135. }
  4136. } else {
  4137. dataexcel["4"] = 0
  4138. }
  4139. if _, ok := outentry["第五班比例(%)"]; ok {
  4140. dataexcel["5"] = outentry["第五班比例(%)"]
  4141. if fmt.Sprintf("%v", dataexcel["5"]) == "" {
  4142. dataexcel["5"] = 0
  4143. }
  4144. } else {
  4145. dataexcel["5"] = 0
  4146. }
  4147. if _, ok := outentry["第六班比例(%)"]; ok {
  4148. dataexcel["6"] = outentry["第六班比例(%)"]
  4149. if fmt.Sprintf("%v", dataexcel["6"]) == "" {
  4150. dataexcel["6"] = 0
  4151. }
  4152. } else {
  4153. dataexcel["6"] = 0
  4154. }
  4155. dataWeight := new(models.FpdetailEdit)
  4156. // dataWeightMap := make(map[string]interface{}, 0)
  4157. if _, ok := outentry["第一班重量"]; ok {
  4158. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4159. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4160. }
  4161. if _, ok := outentry["第二班重量"]; ok {
  4162. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4163. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4164. }
  4165. if _, ok := outentry["第三班重量"]; ok {
  4166. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4167. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4168. }
  4169. if _, ok := outentry["第四班重量"]; ok {
  4170. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4171. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4172. }
  4173. if _, ok := outentry["第五班重量"]; ok {
  4174. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4175. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4176. }
  4177. if _, ok := outentry["第六班重量"]; ok {
  4178. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4179. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4180. }
  4181. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4182. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4183. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4184. // fmt.Println(err)
  4185. if fmt.Sprintf("%v", dataexcel["ccount"]) == "0" {
  4186. dataWeight.Weight1 = 0
  4187. dataWeight.Weight2 = 0
  4188. dataWeight.Weight3 = 0
  4189. dataWeight.Weight4 = 0
  4190. dataWeight.Weight5 = 0
  4191. dataWeight.Weight6 = 0
  4192. }
  4193. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4194. if weight > 0 {
  4195. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4196. if err != nil {
  4197. logs.Error(err)
  4198. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4199. return
  4200. }
  4201. if !existbar {
  4202. continue
  4203. }
  4204. _, 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()
  4205. if err != nil {
  4206. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4207. return
  4208. }
  4209. _, 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()
  4210. if err != nil {
  4211. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4212. return
  4213. }
  4214. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4215. if err != nil {
  4216. logs.Error(err)
  4217. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4218. return
  4219. }
  4220. if !existft {
  4221. continue
  4222. }
  4223. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4224. if err != nil {
  4225. logs.Error(err)
  4226. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4227. return
  4228. }
  4229. if !ftexist {
  4230. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4231. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4232. if err != nil {
  4233. logs.Error(err)
  4234. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4235. return
  4236. }
  4237. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4238. if err != nil {
  4239. logs.Error(err)
  4240. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4241. return
  4242. }
  4243. }
  4244. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4245. if err != nil {
  4246. logs.Error(err)
  4247. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4248. return
  4249. }
  4250. if !exist {
  4251. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4252. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4253. if err != nil {
  4254. logs.Error(err)
  4255. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4256. return
  4257. }
  4258. }
  4259. var feedpargs []interface{}
  4260. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4261. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4262. if _, ok := dataexcel["ftname"]; ok {
  4263. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4264. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4265. // upFeedpSql += `,ftweight = ? `
  4266. // feedpargs = append(feedpargs, weight)
  4267. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4268. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4269. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4270. } else {
  4271. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4272. }
  4273. if _, ok := dataexcel["ptsfname"]; ok {
  4274. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4275. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4276. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4277. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4278. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4279. } else {
  4280. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4281. }
  4282. upFeedpSql += " where barname = ? and pastureid = ? "
  4283. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4284. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4285. if err != nil {
  4286. logs.Error(err)
  4287. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4288. return
  4289. }
  4290. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4291. if err != nil {
  4292. logs.Error(err)
  4293. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4294. return
  4295. }
  4296. if !exist1 {
  4297. _, 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) `,
  4298. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4299. if err != nil {
  4300. logs.Error(err)
  4301. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4302. return
  4303. }
  4304. }
  4305. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4306. if err != nil {
  4307. logs.Error(err)
  4308. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4309. return
  4310. }
  4311. if !exist2 {
  4312. _, 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) `,
  4313. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4314. if err != nil {
  4315. logs.Error(err)
  4316. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4317. return
  4318. }
  4319. }
  4320. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4321. if err != nil {
  4322. logs.Error(err)
  4323. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4324. return
  4325. }
  4326. if !exist3 {
  4327. _, 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) `,
  4328. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4329. if err != nil {
  4330. logs.Error(err)
  4331. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4332. return
  4333. }
  4334. }
  4335. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4336. if err != nil {
  4337. logs.Error(err)
  4338. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4339. return
  4340. }
  4341. if !exist4 {
  4342. _, 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) `,
  4343. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4344. if err != nil {
  4345. logs.Error(err)
  4346. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4347. return
  4348. }
  4349. }
  4350. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4351. if err != nil {
  4352. logs.Error(err)
  4353. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4354. return
  4355. }
  4356. if !exist5 {
  4357. _, 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) `,
  4358. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4359. if err != nil {
  4360. logs.Error(err)
  4361. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4362. return
  4363. }
  4364. }
  4365. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4366. if err != nil {
  4367. logs.Error(err)
  4368. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4369. return
  4370. }
  4371. if !exist6 {
  4372. _, 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) `,
  4373. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4374. if err != nil {
  4375. logs.Error(err)
  4376. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4377. return
  4378. }
  4379. }
  4380. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4381. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4382. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4383. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4384. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4385. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4386. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4387. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4388. and pastureid = ? and times = ?`
  4389. var fpdargs1 []interface{}
  4390. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4391. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4392. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4393. if err != nil {
  4394. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4395. return
  4396. }
  4397. var fpdargs2 []interface{}
  4398. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4399. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4400. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4401. if err != nil {
  4402. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4403. return
  4404. }
  4405. var fpdargs3 []interface{}
  4406. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4407. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4408. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4409. if err != nil {
  4410. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4411. return
  4412. }
  4413. var fpdargs4 []interface{}
  4414. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4415. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4416. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4417. if err != nil {
  4418. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4419. return
  4420. }
  4421. var fpdargs5 []interface{}
  4422. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4423. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4424. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4425. if err != nil {
  4426. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4427. return
  4428. }
  4429. var fpdargs6 []interface{}
  4430. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4431. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4432. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4433. if err != nil {
  4434. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4435. return
  4436. }
  4437. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4438. 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()
  4439. if err != nil {
  4440. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4441. return
  4442. }
  4443. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4444. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4445. upFpdetailList := make([]*upFpdetail, 0)
  4446. for _, newfpd := range newList {
  4447. for _, oldfpd := range oldFpdList {
  4448. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4449. var oldweight, newweight float64
  4450. if oldfpd["weight"] != nil {
  4451. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4452. }
  4453. if newfpd["weight"] != nil {
  4454. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4455. }
  4456. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4457. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4458. Old: oldweight,
  4459. New: newweight,
  4460. Times: newfpd["times"].(int64),
  4461. Ptid: newfpd["ptid"].(int64),
  4462. Fweight: fweight,
  4463. Id: oldfpd["id"].(int64),
  4464. })
  4465. break
  4466. }
  4467. }
  4468. }
  4469. // fmt.Println(dataexcel["barname"])
  4470. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4471. } else {
  4472. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4473. if err != nil {
  4474. logs.Error(err)
  4475. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4476. return
  4477. }
  4478. if !existbar {
  4479. continue
  4480. }
  4481. _, 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()
  4482. if err != nil {
  4483. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4484. return
  4485. }
  4486. _, 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()
  4487. if err != nil {
  4488. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4489. return
  4490. }
  4491. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4492. if err != nil {
  4493. logs.Error(err)
  4494. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4495. return
  4496. }
  4497. if !existft {
  4498. continue
  4499. }
  4500. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4501. if err != nil {
  4502. logs.Error(err)
  4503. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4504. return
  4505. }
  4506. if !ftexist {
  4507. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4508. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4509. if err != nil {
  4510. logs.Error(err)
  4511. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4512. return
  4513. }
  4514. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4515. if err != nil {
  4516. logs.Error(err)
  4517. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4518. return
  4519. }
  4520. }
  4521. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4522. if err != nil {
  4523. logs.Error(err)
  4524. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4525. return
  4526. }
  4527. if !exist {
  4528. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4529. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4530. if err != nil {
  4531. logs.Error(err)
  4532. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4533. return
  4534. }
  4535. }
  4536. var feedpargs []interface{}
  4537. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4538. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4539. if _, ok := dataexcel["ftname"]; ok {
  4540. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4541. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4542. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4543. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4544. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4545. } else {
  4546. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4547. }
  4548. if _, ok := dataexcel["ptsfname"]; ok {
  4549. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4550. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4551. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4552. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4553. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4554. } else {
  4555. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4556. }
  4557. upFeedpSql += " where barname = ? and pastureid = ? "
  4558. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4559. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4560. if err != nil {
  4561. logs.Error(err)
  4562. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4563. return
  4564. }
  4565. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4566. if err != nil {
  4567. logs.Error(err)
  4568. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4569. return
  4570. }
  4571. if !exist1 {
  4572. _, 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) `,
  4573. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4574. if err != nil {
  4575. logs.Error(err)
  4576. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4577. return
  4578. }
  4579. }
  4580. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4581. if err != nil {
  4582. logs.Error(err)
  4583. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4584. return
  4585. }
  4586. if !exist2 {
  4587. _, 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) `,
  4588. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4589. if err != nil {
  4590. logs.Error(err)
  4591. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4592. return
  4593. }
  4594. }
  4595. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4596. if err != nil {
  4597. logs.Error(err)
  4598. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4599. return
  4600. }
  4601. if !exist3 {
  4602. _, 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) `,
  4603. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4604. if err != nil {
  4605. logs.Error(err)
  4606. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4607. return
  4608. }
  4609. }
  4610. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4611. if err != nil {
  4612. logs.Error(err)
  4613. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4614. return
  4615. }
  4616. if !exist4 {
  4617. _, 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) `,
  4618. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4619. if err != nil {
  4620. logs.Error(err)
  4621. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4622. return
  4623. }
  4624. }
  4625. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4626. if err != nil {
  4627. logs.Error(err)
  4628. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4629. return
  4630. }
  4631. if !exist5 {
  4632. _, 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) `,
  4633. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4634. if err != nil {
  4635. logs.Error(err)
  4636. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4637. return
  4638. }
  4639. }
  4640. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4641. if err != nil {
  4642. logs.Error(err)
  4643. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4644. return
  4645. }
  4646. if !exist6 {
  4647. _, 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) `,
  4648. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4649. if err != nil {
  4650. logs.Error(err)
  4651. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4652. return
  4653. }
  4654. }
  4655. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4656. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4657. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4658. and pastureid = ? and times = ?`
  4659. var fpdargs1 []interface{}
  4660. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4661. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4662. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4663. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4664. if err != nil {
  4665. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4666. return
  4667. }
  4668. var fpdargs2 []interface{}
  4669. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4670. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4671. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4672. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4673. if err != nil {
  4674. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4675. return
  4676. }
  4677. var fpdargs3 []interface{}
  4678. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4679. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4680. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4681. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4682. if err != nil {
  4683. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4684. return
  4685. }
  4686. var fpdargs4 []interface{}
  4687. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4688. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4689. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4690. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4691. if err != nil {
  4692. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4693. return
  4694. }
  4695. var fpdargs5 []interface{}
  4696. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4697. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4698. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4699. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4700. if err != nil {
  4701. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4702. return
  4703. }
  4704. var fpdargs6 []interface{}
  4705. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4706. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4707. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4708. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4709. if err != nil {
  4710. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4711. return
  4712. }
  4713. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4714. 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()
  4715. if err != nil {
  4716. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4717. return
  4718. }
  4719. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4720. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4721. upFpdetailList := make([]*upFpdetail, 0)
  4722. for _, newfpd := range newList {
  4723. for _, oldfpd := range oldFpdList {
  4724. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4725. var oldweight, newweight float64
  4726. if oldfpd["weight"] != nil {
  4727. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4728. }
  4729. if newfpd["weight"] != nil {
  4730. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4731. }
  4732. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4733. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4734. Old: oldweight,
  4735. New: newweight,
  4736. Times: newfpd["times"].(int64),
  4737. Ptid: newfpd["ptid"].(int64),
  4738. Fweight: fweight,
  4739. Id: oldfpd["id"].(int64),
  4740. })
  4741. break
  4742. }
  4743. }
  4744. }
  4745. // fmt.Println(dataexcel["barname"])
  4746. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4747. }
  4748. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4749. }
  4750. }
  4751. if !isdone {
  4752. ok++
  4753. isdone = true
  4754. }
  4755. }
  4756. for barname, v := range dataList {
  4757. // for _, v1 := range v {
  4758. // count, err := tx.SQL(` select count(1) from lpplandtl1 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 = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4760. // if count == 1 {
  4761. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4762. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4763. // if err != nil {
  4764. // logs.Error(err)
  4765. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4766. // return
  4767. // }
  4768. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4769. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4770. // if err != nil {
  4771. // logs.Error(err)
  4772. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4773. // return
  4774. // }
  4775. // }
  4776. // }
  4777. // /*
  4778. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  4779. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  4780. if err != nil {
  4781. logs.Error(err)
  4782. return
  4783. }
  4784. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4785. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  4786. if err != nil {
  4787. logs.Error(err)
  4788. return
  4789. }
  4790. // */
  4791. updateFpdetailByBar(pastureid, barname, v)
  4792. }
  4793. } else {
  4794. 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
  4795. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4796. if err != nil {
  4797. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4798. return
  4799. }
  4800. rows := xlsx1.GetRows(sheetname)
  4801. // 限制10000条,多余的截取掉
  4802. if len(rows) > 10000 {
  4803. rows = rows[:10000]
  4804. }
  4805. dataList := make(map[string][]*upFpdetail, 0)
  4806. for i, row := range rows {
  4807. if i > 0 {
  4808. entry := make(map[string]interface{})
  4809. outentry := make(map[string]interface{})
  4810. for j, colCell := range rows[0] {
  4811. for k, colCell1 := range row {
  4812. if j == k {
  4813. outentry[colCell] = colCell1
  4814. entry[colCell] = colCell1
  4815. }
  4816. }
  4817. }
  4818. inputdata = ""
  4819. a := ""
  4820. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4821. //校验日期格式
  4822. for _, v := range dateParamslist {
  4823. if v == "" {
  4824. continue
  4825. }
  4826. if d, ok := outentry[v]; ok {
  4827. dtime, err := TransfTime(d.(string))
  4828. if err != nil {
  4829. a = v
  4830. break
  4831. }
  4832. outentry[v] = dtime
  4833. }
  4834. }
  4835. if a != "" {
  4836. outentry["error_msg"] = a + " format error"
  4837. error++
  4838. queryData = append(queryData, outentry)
  4839. continue
  4840. }
  4841. a = ""
  4842. //校验必填格式
  4843. for _, v := range requiredParamslist {
  4844. if v == "" {
  4845. continue
  4846. }
  4847. if d, ok := outentry[v]; !ok || d == "" {
  4848. a = v
  4849. break
  4850. }
  4851. }
  4852. if a != "" {
  4853. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4854. error++
  4855. queryData = append(queryData, outentry)
  4856. continue
  4857. }
  4858. a = ""
  4859. //校验数字格式
  4860. for _, v := range numParamslist {
  4861. if v == "" {
  4862. continue
  4863. }
  4864. d, ok := outentry[v]
  4865. if !ok || d == "" {
  4866. outentry[v] = 0
  4867. } else {
  4868. var fl float64
  4869. switch d.(type) {
  4870. case string:
  4871. fl, err = strconv.ParseFloat(d.(string), 64)
  4872. }
  4873. if err != nil || fl < 0 {
  4874. a = v
  4875. break
  4876. }
  4877. }
  4878. }
  4879. if a != "" {
  4880. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4881. error++
  4882. queryData = append(queryData, outentry)
  4883. continue
  4884. }
  4885. errExist := false
  4886. for _, sqlnamestr := range sqlslist {
  4887. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4888. paramslist := strings.Split(paramslists, ",")
  4889. if len(paramslist) > 0 {
  4890. s_params := make([]interface{}, 0)
  4891. for _, value := range paramslist {
  4892. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4893. if tempv, exists := c.Get("jwt_username"); exists {
  4894. s_params = append(s_params, tempv.(string))
  4895. } else {
  4896. s_params = append(s_params, "")
  4897. }
  4898. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4899. s_params = append(s_params, pastureid)
  4900. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4901. ids, err := setting.SnowIds.NextId()
  4902. if err != nil {
  4903. ids = time.Now().UnixNano()
  4904. logging.Info("create SnowIds err", err)
  4905. }
  4906. s_params = append(s_params, ids)
  4907. } else {
  4908. if outentry[strings.Trim(value, " ")] == nil {
  4909. s_params = append(s_params, "")
  4910. } else {
  4911. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4912. }
  4913. }
  4914. }
  4915. outentry["input"] = inputdata
  4916. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4917. if err != nil {
  4918. errExist = true
  4919. // if tx != nil {
  4920. // tx.Rollback()
  4921. // }
  4922. // if tx != nil {
  4923. // tx.Close()
  4924. // }
  4925. msg := geterrmsg(err.Error())
  4926. outentry["error_msg"] = msg
  4927. error++
  4928. queryData = append(queryData, outentry)
  4929. isdone = true
  4930. break
  4931. } else {
  4932. if len(returnmsgmap1) > 0 {
  4933. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4934. // if tx != nil {
  4935. // tx.Rollback()
  4936. // }
  4937. // if tx != nil {
  4938. // tx.Close()
  4939. // }
  4940. msg := geterrmsg(va.(string))
  4941. outentry["error_msg"] = msg
  4942. error++
  4943. queryData = append(queryData, outentry)
  4944. isdone = true
  4945. break
  4946. }
  4947. }
  4948. isdone = false
  4949. }
  4950. }
  4951. }
  4952. if !errExist {
  4953. dataexcel := make(map[string]interface{}, 0)
  4954. if _, ok := outentry["Pen Name"]; ok {
  4955. dataexcel["barname"] = outentry["Pen Name"]
  4956. }
  4957. if _, ok := outentry["Actual Cattle Number"]; ok {
  4958. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4959. }
  4960. if _, ok := outentry["Coefficient(%)"]; ok {
  4961. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4962. }
  4963. if _, ok := outentry["Formula Template"]; ok {
  4964. dataexcel["ftname"] = outentry["Formula Template"]
  4965. }
  4966. if _, ok := outentry["Supplement Formula"]; ok {
  4967. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4968. }
  4969. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4970. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4971. }
  4972. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4973. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4974. }
  4975. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4976. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4977. }
  4978. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4979. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4980. }
  4981. if _, ok := outentry["Fifth Shift Ratio(%)"]; ok {
  4982. dataexcel["5"] = outentry["Fifth Shift Ratio(%)"]
  4983. }
  4984. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4985. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4986. }
  4987. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4988. if err != nil {
  4989. logs.Error(err)
  4990. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4991. return
  4992. }
  4993. if !existbar {
  4994. continue
  4995. }
  4996. _, 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()
  4997. if err != nil {
  4998. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4999. return
  5000. }
  5001. _, 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()
  5002. if err != nil {
  5003. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5004. return
  5005. }
  5006. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  5007. if err != nil {
  5008. logs.Error(err)
  5009. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  5010. return
  5011. }
  5012. if !existft {
  5013. continue
  5014. }
  5015. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  5016. if err != nil {
  5017. logs.Error(err)
  5018. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5019. return
  5020. }
  5021. if !ftexist {
  5022. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  5023. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5024. if err != nil {
  5025. logs.Error(err)
  5026. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5027. return
  5028. }
  5029. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5030. if err != nil {
  5031. logs.Error(err)
  5032. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5033. return
  5034. }
  5035. }
  5036. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5037. if err != nil {
  5038. logs.Error(err)
  5039. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5040. return
  5041. }
  5042. if !exist {
  5043. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  5044. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  5045. if err != nil {
  5046. logs.Error(err)
  5047. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5048. return
  5049. }
  5050. }
  5051. var feedpargs []interface{}
  5052. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  5053. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  5054. if _, ok := dataexcel["ftname"]; ok {
  5055. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  5056. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  5057. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  5058. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  5059. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5060. } else {
  5061. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  5062. }
  5063. if _, ok := dataexcel["ptsfname"]; ok {
  5064. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  5065. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  5066. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  5067. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  5068. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5069. } else {
  5070. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  5071. }
  5072. upFeedpSql += " where barname = ? and pastureid = ? "
  5073. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  5074. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  5075. if err != nil {
  5076. logs.Error(err)
  5077. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5078. return
  5079. }
  5080. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  5081. if err != nil {
  5082. logs.Error(err)
  5083. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5084. return
  5085. }
  5086. if !exist1 {
  5087. _, 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) `,
  5088. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5089. if err != nil {
  5090. logs.Error(err)
  5091. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5092. return
  5093. }
  5094. }
  5095. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5096. if err != nil {
  5097. logs.Error(err)
  5098. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5099. return
  5100. }
  5101. if !exist2 {
  5102. _, 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) `,
  5103. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5104. if err != nil {
  5105. logs.Error(err)
  5106. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5107. return
  5108. }
  5109. }
  5110. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5111. if err != nil {
  5112. logs.Error(err)
  5113. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5114. return
  5115. }
  5116. if !exist3 {
  5117. _, 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) `,
  5118. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5119. if err != nil {
  5120. logs.Error(err)
  5121. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5122. return
  5123. }
  5124. }
  5125. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5126. if err != nil {
  5127. logs.Error(err)
  5128. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5129. return
  5130. }
  5131. if !exist4 {
  5132. _, 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) `,
  5133. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5134. if err != nil {
  5135. logs.Error(err)
  5136. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5137. return
  5138. }
  5139. }
  5140. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5141. if err != nil {
  5142. logs.Error(err)
  5143. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5144. return
  5145. }
  5146. if !exist5 {
  5147. _, 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) `,
  5148. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5149. if err != nil {
  5150. logs.Error(err)
  5151. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5152. return
  5153. }
  5154. }
  5155. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5156. if err != nil {
  5157. logs.Error(err)
  5158. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5159. return
  5160. }
  5161. if !exist6 {
  5162. _, 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) `,
  5163. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5164. if err != nil {
  5165. logs.Error(err)
  5166. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5167. return
  5168. }
  5169. }
  5170. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5171. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5172. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5173. and pastureid = ? and times = ?`
  5174. var fpdargs1 []interface{}
  5175. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5176. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5177. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5178. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5179. if err != nil {
  5180. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5181. return
  5182. }
  5183. var fpdargs2 []interface{}
  5184. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5185. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5186. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5187. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5188. if err != nil {
  5189. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5190. return
  5191. }
  5192. var fpdargs3 []interface{}
  5193. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5194. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5195. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5196. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5197. if err != nil {
  5198. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5199. return
  5200. }
  5201. var fpdargs4 []interface{}
  5202. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5203. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5204. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5205. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5206. if err != nil {
  5207. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5208. return
  5209. }
  5210. var fpdargs5 []interface{}
  5211. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5212. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5213. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5214. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5215. if err != nil {
  5216. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5217. return
  5218. }
  5219. var fpdargs6 []interface{}
  5220. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5221. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5222. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5223. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5224. if err != nil {
  5225. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5226. return
  5227. }
  5228. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5229. 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()
  5230. if err != nil {
  5231. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5232. return
  5233. }
  5234. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5235. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5236. upFpdetailList := make([]*upFpdetail, 0)
  5237. for _, newfpd := range newList {
  5238. for _, oldfpd := range oldFpdList {
  5239. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5240. var oldweight, newweight float64
  5241. if oldfpd["weight"] != nil {
  5242. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5243. }
  5244. if newfpd["weight"] != nil {
  5245. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5246. }
  5247. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5248. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5249. Old: oldweight,
  5250. New: newweight,
  5251. Times: newfpd["times"].(int64),
  5252. Ptid: newfpd["ptid"].(int64),
  5253. Fweight: fweight,
  5254. Id: oldfpd["id"].(int64),
  5255. })
  5256. break
  5257. }
  5258. }
  5259. }
  5260. // fmt.Println(dataexcel["barname"])
  5261. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5262. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5263. }
  5264. }
  5265. if !isdone {
  5266. ok++
  5267. isdone = true
  5268. }
  5269. }
  5270. for barname, v := range dataList {
  5271. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5272. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5273. if err != nil {
  5274. logs.Error(err)
  5275. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5276. return
  5277. }
  5278. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5279. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5280. if err != nil {
  5281. logs.Error(err)
  5282. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5283. return
  5284. }
  5285. updateFpdetailByBar(pastureid, barname, v)
  5286. }
  5287. }
  5288. data := make(map[string]interface{})
  5289. data["result"] = queryData
  5290. data["success"] = ok
  5291. data["err_count"] = error
  5292. appG.Response(http.StatusOK, e.SUCCESS, data)
  5293. }
  5294. type upFpdetail struct {
  5295. Old float64
  5296. New float64
  5297. Times int64
  5298. Ptid int64
  5299. Fweight float64
  5300. Id int64
  5301. // Ptsid string
  5302. }
  5303. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5304. tx := restful.Engine.NewSession()
  5305. defer tx.Close()
  5306. tx.Begin()
  5307. 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 `,
  5308. pastureid, barname).Query().List()
  5309. if err != nil {
  5310. logs.Error(err)
  5311. }
  5312. for _, fpd := range fpdList {
  5313. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5314. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5315. pastureid, fpd["id"], fpd["times"]).Query().List()
  5316. if err != nil {
  5317. tx.Rollback()
  5318. logs.Error(err)
  5319. return err
  5320. }
  5321. var lweight float64
  5322. for _, lppland := range lpplandList {
  5323. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5324. lweight += lweight1
  5325. }
  5326. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5327. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5328. if fpdweight >= ptuse && lweight == ptuse {
  5329. continue
  5330. } else {
  5331. if lweight <= fpdweight {
  5332. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5333. if err != nil {
  5334. tx.Rollback()
  5335. logs.Error(err)
  5336. return err
  5337. }
  5338. } else {
  5339. weight := lweight - fpdweight
  5340. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5341. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5342. if err != nil {
  5343. tx.Rollback()
  5344. logs.Error(err)
  5345. return err
  5346. }
  5347. for _, lppland := range lpplandList {
  5348. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5349. if weight >= lpplandlweight {
  5350. weight = weight - lpplandlweight
  5351. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5352. if err != nil {
  5353. tx.Rollback()
  5354. logs.Error(err)
  5355. return err
  5356. }
  5357. } else {
  5358. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5359. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5360. if err != nil {
  5361. tx.Rollback()
  5362. logs.Error(err)
  5363. return err
  5364. }
  5365. weight = 0
  5366. break
  5367. }
  5368. }
  5369. }
  5370. }
  5371. }
  5372. for _, list := range dataList {
  5373. ftmap := make(map[string]interface{})
  5374. ftmap["old"] = list.Old
  5375. ftmap["new"] = list.New
  5376. ftmap["times"] = list.Times
  5377. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5378. ftmap["ptsid"] = ""
  5379. // fmt.Println(ftmap)
  5380. // 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 ,
  5381. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5382. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5383. // UNION
  5384. fpdDataList, err := tx.SQL(`
  5385. 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 ,
  5386. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5387. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5388. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5389. if err != nil {
  5390. tx.Rollback()
  5391. logs.Error(err)
  5392. }
  5393. for _, fpd := range fpdDataList {
  5394. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5395. // fttype := -1
  5396. // if fpd["fttype"].(string) == "1" {
  5397. fttype := 1
  5398. // }
  5399. var fweight float64
  5400. var lweight float64
  5401. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5402. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  5403. t.maxstirfeed,t.volume * (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  5404. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5405. join tmr t on t.id = lpp.tmrid
  5406. where lppland.fpdid =?
  5407. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5408. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5409. if err != nil {
  5410. tx.Rollback()
  5411. logs.Error(err)
  5412. }
  5413. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5414. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5415. // 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
  5416. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5417. var w float64
  5418. var status int
  5419. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5420. if weight >= 0 {
  5421. continue
  5422. }
  5423. w = weight
  5424. status = 0
  5425. } else {
  5426. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5427. // continue
  5428. // }
  5429. w = weight
  5430. status = 1
  5431. }
  5432. // for _, lppland := range lpplandtl1List {
  5433. // lweight += lppland.Lweight
  5434. // }
  5435. for _, lppland := range lpplandtl1List {
  5436. lpplandInfo := new(lpplandtlInfo)
  5437. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5438. lweight = lpplandInfo.Lweight
  5439. if status == 1 {
  5440. // if w <= lppland.Lweight {
  5441. if lppland.Maxweight <= lweight {
  5442. continue
  5443. }
  5444. if w+lweight <= lppland.Maxweight {
  5445. lppland.Lweight += w
  5446. lweight += w
  5447. fweight += w
  5448. w = 0
  5449. } else {
  5450. w = w - (lppland.Maxweight - lweight)
  5451. n := (lppland.Maxweight - lweight)
  5452. lppland.Lweight = lppland.Lweight + n
  5453. lweight += n
  5454. fweight += n
  5455. }
  5456. } else {
  5457. if lppland.Lweight == 0 {
  5458. continue
  5459. }
  5460. if w+lppland.Lweight >= 0 {
  5461. lppland.Lweight = lppland.Lweight + w
  5462. lweight = lweight + w
  5463. fweight = fweight + w
  5464. w = 0
  5465. } else {
  5466. w = w + lppland.Lweight
  5467. lweight = lweight - lppland.Lweight
  5468. fweight = fweight - lppland.Lweight
  5469. lppland.Lweight = 0
  5470. }
  5471. }
  5472. if lppland.Lweight > 0 {
  5473. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5474. if err != nil {
  5475. tx.Rollback()
  5476. logs.Error(err)
  5477. return err
  5478. }
  5479. } else {
  5480. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5481. if err != nil {
  5482. tx.Rollback()
  5483. logs.Error(err)
  5484. return err
  5485. }
  5486. }
  5487. if w == 0 {
  5488. break
  5489. }
  5490. }
  5491. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5492. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5493. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5494. if err != nil {
  5495. tx.Rollback()
  5496. logs.Error(err)
  5497. }
  5498. if w == 0 {
  5499. break
  5500. }
  5501. }
  5502. }
  5503. }
  5504. err = tx.Commit()
  5505. if err != nil {
  5506. logs.Error(err)
  5507. tx.Rollback()
  5508. return err
  5509. }
  5510. now := time.Now()
  5511. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5512. if err != nil {
  5513. logs.Error(err)
  5514. return nil
  5515. }
  5516. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5517. if err != nil {
  5518. logs.Error(err)
  5519. return nil
  5520. }
  5521. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5522. if err != nil {
  5523. logs.Error(err)
  5524. return nil
  5525. }
  5526. for _, newLpplandtl1 := range newLpplandtl1List {
  5527. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5528. background,cowcount,ccountradio,lweighthis,createdate)
  5529. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5530. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5531. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5532. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5533. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5534. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5535. if err != nil {
  5536. logs.Error(err)
  5537. // appG.Response(http.StatusOK, e.ERROR, false)
  5538. return err
  5539. }
  5540. }
  5541. for _, newFpd := range newFpdDataList {
  5542. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5543. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5544. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5545. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5546. if err != nil {
  5547. logs.Error(err)
  5548. // appG.Response(http.StatusOK, e.ERROR, false)
  5549. return err
  5550. }
  5551. }
  5552. for _, newFeedp := range newFeedpList {
  5553. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5554. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5555. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5556. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5557. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5558. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5559. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5560. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5561. if err != nil {
  5562. logs.Error(err)
  5563. // appG.Response(http.StatusOK, e.ERROR, false)
  5564. return err
  5565. }
  5566. }
  5567. return nil
  5568. }
  5569. func DeleteFTdetail(c *gin.Context) {
  5570. appG := app.Gin{C: c}
  5571. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5572. fsion := gofasion.NewFasion(string(dataByte))
  5573. parammaps := fsion.Get("parammaps")
  5574. pastureid := parammaps.Get("pastureid").ValueStr()
  5575. ftid := parammaps.Get("ftid").ValueStr()
  5576. tx := restful.Engine.NewSession()
  5577. defer tx.Close()
  5578. tx.Begin()
  5579. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5580. if err != nil {
  5581. tx.Rollback()
  5582. logs.Error(err)
  5583. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5584. return
  5585. }
  5586. if parammaps.Get("type").ValueStr() == "1" {
  5587. _, err := tx.SQL(`UPDATE feedp fp
  5588. set
  5589. fp.ftweight= IFNULL(IF(
  5590. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5591. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5592. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5593. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5594. ),0),fp.feedweight = IFNULL(IF(
  5595. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5596. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5597. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5598. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5599. ),0) +ifnull(fp.supplyweight,0)
  5600. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5601. if err != nil {
  5602. tx.Rollback()
  5603. logs.Error(err)
  5604. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5605. return
  5606. }
  5607. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5608. _, err = tx.SQL(`
  5609. UPDATE fpdetail fpd
  5610. INNER JOIN feedp fp
  5611. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5612. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5613. ptuse= 0
  5614. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5615. if err != nil {
  5616. tx.Rollback()
  5617. logs.Error(err)
  5618. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5619. return
  5620. }
  5621. } else {
  5622. _, err := tx.SQL(`UPDATE feedp fp
  5623. SET
  5624. fp.supplyweight= IFNULL(IF(
  5625. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5626. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5627. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5628. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5629. ),0),fp.feedweight = IFNULL(IF(
  5630. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5631. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5632. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5633. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5634. ),0) + ifnull(fp.supplyweight,0)
  5635. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5636. if err != nil {
  5637. tx.Rollback()
  5638. logs.Error(err)
  5639. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5640. return
  5641. }
  5642. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5643. _, err = tx.SQL(`
  5644. UPDATE fpdetail fpd
  5645. INNER JOIN feedp fp
  5646. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5647. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5648. ptsrate = 0
  5649. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5650. if err != nil {
  5651. tx.Rollback()
  5652. logs.Error(err)
  5653. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5654. return
  5655. }
  5656. }
  5657. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5658. if err != nil {
  5659. tx.Rollback()
  5660. logs.Error(err)
  5661. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5662. return
  5663. }
  5664. err = tx.Commit()
  5665. if err != nil {
  5666. tx.Rollback()
  5667. logs.Error(err)
  5668. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5669. return
  5670. }
  5671. appG.Response(http.StatusOK, e.SUCCESS, true)
  5672. }
  5673. func DeleteSpillageAll(c *gin.Context) {
  5674. appG := app.Gin{C: c}
  5675. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5676. fsion := gofasion.NewFasion(string(dataByte))
  5677. parammaps := fsion.Get("parammaps")
  5678. pastureid := parammaps.Get("pastureid").ValueStr()
  5679. times := parammaps.Get("times").ValueStr()
  5680. barid := parammaps.Get("barid").ValueStr()
  5681. tx := restful.Engine.NewSession()
  5682. defer tx.Close()
  5683. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5684. if err != nil {
  5685. logs.Error(err)
  5686. appG.Response(http.StatusOK, e.ERROR, false)
  5687. return
  5688. }
  5689. now := time.Now()
  5690. for _, item := range lpplandtl1List {
  5691. go func(item map[string]interface{}) {
  5692. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5693. background,cowcount,ccountradio,lweighthis,createdate)
  5694. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5695. item["pastureid"], item["lppid"], item["barid"],
  5696. item["barname"], item["fpdid"], item["fttype"],
  5697. item["lweight"], item["sort"], item["tmrid"],
  5698. item["tmrname"], item["background"], item["cowcount"],
  5699. item["ccountradio"], item["lweighthis"], now).Execute()
  5700. if err != nil {
  5701. logs.Error(err)
  5702. appG.Response(http.StatusOK, e.ERROR, false)
  5703. return
  5704. }
  5705. }(item)
  5706. }
  5707. tx.Begin()
  5708. _, 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()
  5709. if err != nil {
  5710. tx.Rollback()
  5711. logs.Error(err)
  5712. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5713. return
  5714. }
  5715. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5716. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5717. if err != nil {
  5718. tx.Rollback()
  5719. logs.Error(err)
  5720. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5721. return
  5722. }
  5723. err = tx.Commit()
  5724. if err != nil {
  5725. tx.Rollback()
  5726. logs.Error(err)
  5727. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5728. return
  5729. }
  5730. appG.Response(http.StatusOK, e.SUCCESS, true)
  5731. }
  5732. func GetTMRListEnableTypeAll(c *gin.Context) {
  5733. appG := app.Gin{C: c}
  5734. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5735. fsion := gofasion.NewFasion(string(dataByte))
  5736. parammaps := fsion.Get("parammaps")
  5737. pastureid := parammaps.Get("pastureid").ValueStr()
  5738. tx := restful.Engine.NewSession()
  5739. defer tx.Close()
  5740. dataList, err := tx.SQL(`SELECT
  5741. eqcode,
  5742. tname,
  5743. datacaptureno,
  5744. trim(tclassid) tclassid,
  5745. concat(tname,' / ',eqcode) tmrmix,
  5746. d.label tclassname,
  5747. maxstirfeed,
  5748. remark,
  5749. tmr.enable,
  5750. TRIM(tmr.id) id,
  5751. TRIM(tmr.pastureid)pastureid
  5752. FROM
  5753. tmr
  5754. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5755. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5756. ORDER BY id DESC`, pastureid).Query().List()
  5757. if err != nil {
  5758. logs.Error(err)
  5759. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5760. return
  5761. }
  5762. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5763. if err != nil {
  5764. logs.Error(err)
  5765. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5766. return
  5767. }
  5768. var carNum int64
  5769. for _, sysopt := range sysoptData {
  5770. if sysopt["inforvalue"] == nil {
  5771. carNum = 1
  5772. } else {
  5773. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5774. }
  5775. }
  5776. id := 200
  5777. n := 0
  5778. for i := carNum; i > 0; i-- {
  5779. id++
  5780. n++
  5781. data := make(map[string]interface{}, 0)
  5782. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5783. data["tname"] = fmt.Sprintf("任意车%d", n)
  5784. data["datacaptureno"] = -2
  5785. data["tclassid"] = -2
  5786. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5787. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5788. data["maxstirfeed"] = 100000
  5789. data["remark"] = fmt.Sprintf("任意车%d", n)
  5790. data["enable"] = 1
  5791. data["id"] = fmt.Sprintf("%d", id)
  5792. data["pastureid"] = pastureid
  5793. // data := make(map[string]interface{}, 0)
  5794. // data["eqcode"] = fmt.Sprintf("AnyCar%d", n)
  5795. // data["tname"] = fmt.Sprintf("AnyCar%d", n)
  5796. // data["datacaptureno"] = -2
  5797. // data["tclassid"] = -2
  5798. // data["tmrmix"] = fmt.Sprintf("AnyCar%d", n)
  5799. // data["tclassname"] = fmt.Sprintf("AnyCar%d", n)
  5800. // data["maxstirfeed"] = 100000
  5801. // data["remark"] = fmt.Sprintf("AnyCar%d", n)
  5802. // data["enable"] = 1
  5803. // data["id"] = fmt.Sprintf("%d", id)
  5804. // data["pastureid"] = pastureid
  5805. dataList = append(dataList, data)
  5806. }
  5807. // UNION ALL
  5808. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5809. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5810. }
  5811. func GetFeedpHistory(c *gin.Context) {
  5812. appG := app.Gin{C: c}
  5813. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5814. fsion := gofasion.NewFasion(string(dataByte))
  5815. // parammaps := fsion.Get("parammaps")
  5816. bar := fsion.Get("barname").ValueStr()
  5817. startDate := fsion.Get("startDate").ValueStr()
  5818. endDate := fsion.Get("endDate").ValueStr()
  5819. tx := restful.Engine.NewSession()
  5820. defer tx.Close()
  5821. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5822. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5823. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5824. if err != nil {
  5825. logs.Error(err)
  5826. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5827. return
  5828. }
  5829. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5830. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5831. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5832. if err != nil {
  5833. logs.Error(err)
  5834. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5835. return
  5836. }
  5837. for _, feedp := range feedpList {
  5838. // LastftList, err := tx.SQL(` select tname ,id
  5839. // from feedtemplethistory where id = ?
  5840. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5841. // if err != nil {
  5842. // logs.Error(err)
  5843. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5844. // return
  5845. // }
  5846. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5847. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5848. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5849. if err != nil {
  5850. logs.Error(err)
  5851. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5852. return
  5853. }
  5854. var ftname interface{}
  5855. ftnamestatus := 0
  5856. ftname = feedp["ftname"]
  5857. var lastftid int64
  5858. if len(nextfeedpList) > 0 {
  5859. for _, ft := range nextfeedpList {
  5860. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5861. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5862. lastftid = ft["ftid"].(int64)
  5863. ftnamestatus = 1
  5864. break
  5865. }
  5866. }
  5867. }
  5868. for i, fpd := range fpdList {
  5869. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5870. fpd["weightstatus"] = 0
  5871. fpd["tratiostatus"] = 0
  5872. fpd["ftnamestatus"] = ftnamestatus
  5873. for k, fpd2 := range fpdList {
  5874. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5875. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5876. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5877. fpd["weightstatus"] = 1
  5878. }
  5879. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5880. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5881. fpd["tratiostatus"] = 1
  5882. }
  5883. break
  5884. }
  5885. }
  5886. fpd["barid"] = feedp["barid"]
  5887. fpd["barname"] = feedp["barname"]
  5888. fpd["ccount"] = feedp["ccount"]
  5889. fpd["ratio"] = feedp["ratio"]
  5890. fpd["ccountratio"] = feedp["ccountratio"]
  5891. fpd["ftid"] = feedp["ftid"]
  5892. fpd["ftname"] = ftname
  5893. fpd["ccountstatus"] = 0
  5894. fpd["ccountratiostatus"] = 0
  5895. fpd["ratiostatus"] = 0
  5896. fpd["ftnamestatus"] = 0
  5897. fpd["lastftid"] = lastftid
  5898. for _, next := range nextfeedpList {
  5899. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5900. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5901. fpd["ccountstatus"] = 1
  5902. }
  5903. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5904. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5905. fpd["ccountratiostatus"] = 1
  5906. }
  5907. if next["ratio"].(string) != fpd["ratio"].(string) {
  5908. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5909. fpd["ratiostatus"] = 1
  5910. }
  5911. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5912. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5913. // fpd["ftnamestatus"] = 1
  5914. // }
  5915. }
  5916. }
  5917. }
  5918. }
  5919. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5920. }
  5921. // func GetLpplandtl1History(c *gin.Context) {
  5922. // appG := app.Gin{C: c}
  5923. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5924. // fsion := gofasion.NewFasion(string(dataByte))
  5925. // // parammaps := fsion.Get("parammaps")
  5926. // barid := fsion.Get("barid").ValueStr()
  5927. // startDate := fsion.Get("startDate").ValueStr()
  5928. // endDate := fsion.Get("endDate").ValueStr()
  5929. // tx := restful.Engine.NewSession()
  5930. // defer tx.Close()
  5931. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5932. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5933. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5934. // // if err != nil {
  5935. // // logs.Error(err)
  5936. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5937. // // return
  5938. // // }
  5939. // // for _, feedp := range feedpList {
  5940. // // fmt.Println(feedp)
  5941. // // for i, fpd := range fpdList {
  5942. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5943. // // for k, fpd2 := range fpdList {
  5944. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5945. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5946. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5947. // // }
  5948. // // break
  5949. // // }
  5950. // // }
  5951. // // fpd["barid"] = feedp["barid"]
  5952. // // fpd["barname"] = feedp["barname"]
  5953. // // fpd["ccount"] = feedp["ccount"]
  5954. // // fpd["ratio"] = feedp["ratio"]
  5955. // // fpd["ccountratio"] = feedp["ccountratio"]
  5956. // // fpd["ftid"] = feedp["ftid"]
  5957. // // fpd["ftname"] = feedp["ftname"]
  5958. // // }
  5959. // // }
  5960. // // }
  5961. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5962. // }
  5963. func GetRemind(c *gin.Context) {
  5964. appG := app.Gin{C: c}
  5965. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5966. fsion := gofasion.NewFasion(string(dataByte))
  5967. parammaps := fsion.Get("parammaps")
  5968. pastureid := parammaps.Get("pastureid").ValueStr()
  5969. tx := restful.Engine.NewSession()
  5970. defer tx.Close()
  5971. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5972. if err != nil {
  5973. logs.Error(err)
  5974. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5975. return
  5976. }
  5977. // pastureid = "3"
  5978. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5979. if err != nil {
  5980. logs.Error(err)
  5981. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5982. return
  5983. }
  5984. defer resp.Body.Close()
  5985. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5986. buf.ReadFrom(resp.Body)
  5987. fmt.Println(string(buf.Bytes()))
  5988. respMap := make(map[string]interface{}, 0)
  5989. err = json.Unmarshal(buf.Bytes(), &respMap)
  5990. if err != nil {
  5991. logs.Error(err)
  5992. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5993. return
  5994. }
  5995. for _, data := range dataList {
  5996. r := make(map[string]interface{}, 0)
  5997. r["sys_name"] = ""
  5998. r["service_id"] = ""
  5999. r["pasture_id"] = ""
  6000. r["type_name"] = ""
  6001. r["remind_type_id"] = ""
  6002. r["remind_type"] = ""
  6003. r["push_date"] = ""
  6004. r["push_time"] = ""
  6005. r["interval_time"] = ""
  6006. r["push_limit"] = ""
  6007. r["template_id"] = ""
  6008. r["roles_id"] = ""
  6009. r["users_id"] = ""
  6010. r["date_type"] = ""
  6011. r["cycle_type"] = ""
  6012. data["data"] = r
  6013. for _, resp := range respMap["data"].([]interface{}) {
  6014. resp1 := resp.(map[string]interface{})
  6015. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  6016. if resp1["push_time"] == nil {
  6017. resp1["push_time"] = ""
  6018. }
  6019. data["data"] = resp1
  6020. break
  6021. }
  6022. }
  6023. }
  6024. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  6025. }
  6026. type NoticeMsgtype struct {
  6027. SysName string `json:"sys_name"`
  6028. PastureId int64 `json:"pasture_id"`
  6029. ServiceId int64 `json:"service_id"`
  6030. TypeName string `json:"type_name"`
  6031. RemindType int64 `json:"remind_type"`
  6032. PushDate int64 `json:"push_date"`
  6033. PushTime string `json:"push_time"`
  6034. IntervalTime int64 `json:"interval_time"`
  6035. PushLimit int64 `json:"push_limit"`
  6036. TemplateId string `json:"template_id"`
  6037. UsersId string `json:"users_id"`
  6038. DateType int64 `json:"date_type"`
  6039. CycleType int64 `json:"cycle_type"`
  6040. DelayTime int64 `json:"delay_time"`
  6041. Status int64 `json:"status"`
  6042. }
  6043. func UpdateRemind(c *gin.Context) {
  6044. appG := app.Gin{C: c}
  6045. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6046. parammaps := gofasion.NewFasion(string(dataByte))
  6047. // parammaps := fsion.Get("parammaps")
  6048. // user := parammaps.Get("user").ValueStr()
  6049. id := parammaps.Get("id").ValueInt64()
  6050. noticeMsgtype := new(NoticeMsgtype)
  6051. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  6052. noticeMsgtype.ServiceId = id
  6053. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  6054. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  6055. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  6056. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  6057. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  6058. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  6059. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  6060. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  6061. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  6062. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  6063. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  6064. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  6065. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  6066. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  6067. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  6068. //TODO
  6069. noticeMsgtype.SysName = "tmrWatch"
  6070. userList := parammaps.Get("user").Array()
  6071. var userstr []string
  6072. for _, user := range userList {
  6073. userstr = append(userstr, user.ValueStr())
  6074. }
  6075. tx := restful.Engine.NewSession()
  6076. defer tx.Close()
  6077. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  6078. if err != nil {
  6079. logs.Error(err)
  6080. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6081. return
  6082. }
  6083. // var jsonStr = []byte(noticeMsgtype
  6084. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  6085. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  6086. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  6087. req.Header.Set("Content-Type", "application/json")
  6088. client := &http.Client{}
  6089. resp, err := client.Do(req)
  6090. if err != nil {
  6091. logs.Error(err)
  6092. }
  6093. defer resp.Body.Close()
  6094. body, _ := ioutil.ReadAll(resp.Body)
  6095. fmt.Println("response Body:", string(body))
  6096. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  6097. if err != nil {
  6098. logs.Error(err)
  6099. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6100. return
  6101. }
  6102. defer getresp.Body.Close()
  6103. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6104. buf.ReadFrom(getresp.Body)
  6105. // fmt.Println(string(buf.Bytes()))
  6106. respMap := make(map[string]interface{}, 0)
  6107. err = json.Unmarshal(buf.Bytes(), &respMap)
  6108. if err != nil {
  6109. logs.Error(err)
  6110. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6111. return
  6112. }
  6113. for _, resp := range respMap["data"].([]interface{}) {
  6114. resp1 := resp.(map[string]interface{})
  6115. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6116. if err != nil {
  6117. logs.Error(err)
  6118. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6119. return
  6120. }
  6121. }
  6122. appG.Response(http.StatusOK, e.SUCCESS, true)
  6123. }
  6124. func GetSpillageallHistory(c *gin.Context) {
  6125. appG := app.Gin{C: c}
  6126. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6127. parammaps := gofasion.NewFasion(string(dataByte))
  6128. barname := parammaps.Get("barname").ValueStr()
  6129. pastureid := parammaps.Get("pastureid").ValueStr()
  6130. startdate := parammaps.Get("startDate").ValueStr()
  6131. enddate := parammaps.Get("endDate").ValueStr()
  6132. tx := restful.Engine.NewSession()
  6133. defer tx.Close()
  6134. historyList, err := tx.SQL(` select lpp.id,lpp.times,lppland.lweight,lppland.tmrid,lppland.tmrname,lpp.sort,
  6135. DATE_FORMAT(lppland.createdate,'%Y-%m-%d %H:%i:%s') as createdate ,u.username
  6136. from lpplandtl1history lppland
  6137. join lpplan lpp on lpp.id = lppland.lppid
  6138. left join user u on u.id = lppland.userId
  6139. where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6140. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6141. if err != nil {
  6142. logs.Error(err)
  6143. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6144. return
  6145. }
  6146. respMap := make([]map[string]interface{}, 0)
  6147. data := make(map[interface{}]interface{})
  6148. for _, history := range historyList {
  6149. data[history["createdate"]] = history["createdate"]
  6150. }
  6151. createList := []string{}
  6152. for _, v := range data {
  6153. createList = append(createList, v.(string))
  6154. }
  6155. // sort.Sort()
  6156. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6157. sort.Slice(createList, func(i, j int) bool {
  6158. return createList[i] > createList[j]
  6159. })
  6160. for _, v := range createList {
  6161. a := make(map[string]interface{})
  6162. a["createdate"] = data[v]
  6163. // createList = append(createList, v.(string))
  6164. respMap = append(respMap, a)
  6165. }
  6166. number := 0
  6167. dataMap := make([]interface{}, 0)
  6168. for k, resp := range respMap {
  6169. createdate := resp["createdate"].(string)
  6170. var nextcreatedate string
  6171. if len(respMap) > k+1 {
  6172. nextcreatedate = respMap[k+1]["createdate"].(string)
  6173. }
  6174. // dataList := make(map[string][]interface{})
  6175. // list := make(map[string]interface{})
  6176. times := make(map[interface{}]int)
  6177. for _, history := range historyList {
  6178. // List := make(map[interface{}][]interface{})
  6179. i := 0
  6180. if history["createdate"].(string) == createdate {
  6181. times[history["times"]]++
  6182. data := make(map[string]interface{})
  6183. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6184. // exist := false
  6185. if nextcreatedate != "" {
  6186. for _, history1 := range historyList {
  6187. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6188. history1["times"].(int64) == history["times"].(int64) {
  6189. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6190. break
  6191. // exist = true
  6192. }
  6193. }
  6194. }
  6195. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6196. i++
  6197. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6198. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6199. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6200. // resp["times"] = history["times"]
  6201. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6202. data1 := make(map[string]interface{})
  6203. data1["times"] = history["times"]
  6204. data1["empname"] = history["username"]
  6205. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6206. data1["createdate"] = resp["createdate"]
  6207. // fmt.Println(dataList)
  6208. dataMap = append(dataMap, data1)
  6209. }
  6210. if i > number {
  6211. number = i
  6212. }
  6213. // respMap = append(respMap, dataList)
  6214. }
  6215. // for k, data := range dataList {
  6216. // resp[k] = data
  6217. // }
  6218. // resp["data"] = dataList
  6219. }
  6220. // resp := make(map[string]interface{})
  6221. // sort.Strings(createList)
  6222. //
  6223. // for _, create := range createList {
  6224. // for _, r := range respMap {
  6225. // if create == r["createdate"].(string) {
  6226. // resp[create] = r
  6227. // break
  6228. // }
  6229. // }
  6230. // }
  6231. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6232. var trainsList []interface{}
  6233. for i := 0; i < number; i++ {
  6234. trains := make(map[string]interface{})
  6235. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6236. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6237. trainsList = append(trainsList, trains)
  6238. }
  6239. respdata := make(map[string]interface{})
  6240. respdata["data"] = dataMap
  6241. respdata["trains"] = trainsList
  6242. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6243. }
  6244. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6245. appG := app.Gin{C: c}
  6246. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6247. parammaps := gofasion.NewFasion(string(dataByte))
  6248. ftid := parammaps.Get("ftid").ValueInt64()
  6249. lastftid := parammaps.Get("lastftid").ValueInt64()
  6250. pastureid := parammaps.Get("pastureid").ValueInt64()
  6251. // createdate := parammaps.Get("createdate").ValueStr()
  6252. tx := restful.Engine.NewSession()
  6253. defer tx.Close()
  6254. data := make(map[string]interface{})
  6255. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6256. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6257. if err != nil {
  6258. logs.Error(err)
  6259. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6260. return
  6261. }
  6262. feedtemplet := make(map[string]interface{})
  6263. for _, f := range feedtempletList {
  6264. feedtemplet = f
  6265. }
  6266. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  6267. if err != nil {
  6268. logs.Error(err)
  6269. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6270. return
  6271. }
  6272. feedtemplet["fit"] = fitList
  6273. data["current"] = feedtemplet
  6274. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6275. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6276. if err != nil {
  6277. logs.Error(err)
  6278. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6279. return
  6280. }
  6281. lastfeedtemplet := make(map[string]interface{})
  6282. for _, f := range lastfeedtempletList {
  6283. lastfeedtemplet = f
  6284. }
  6285. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  6286. if err != nil {
  6287. logs.Error(err)
  6288. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6289. return
  6290. }
  6291. lastfeedtemplet["fit"] = lastfitList
  6292. data["last"] = lastfeedtemplet
  6293. appG.Response(http.StatusOK, e.SUCCESS, data)
  6294. }
  6295. func GetFeedtempletHistory(c *gin.Context) {
  6296. appG := app.Gin{C: c}
  6297. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6298. parammaps := gofasion.NewFasion(string(dataByte))
  6299. ftid := parammaps.Get("ftid").ValueStr()
  6300. pastureid := parammaps.Get("pastureid").ValueInt64()
  6301. start := parammaps.Get("startdate").ValueStr()
  6302. end := parammaps.Get("enddate").ValueStr()
  6303. tx := restful.Engine.NewSession()
  6304. defer tx.Close()
  6305. 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 ?
  6306. and id = ? and pastureid = ? order by createdate desc `,
  6307. start, end, ftid, pastureid).Query().List()
  6308. if err != nil {
  6309. logs.Error(err)
  6310. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6311. return
  6312. }
  6313. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6314. ftid, pastureid).Query().List()
  6315. if err != nil {
  6316. logs.Error(err)
  6317. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6318. return
  6319. }
  6320. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6321. for i, ft := range ftList {
  6322. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6323. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6324. (select empname from user where id = fit.userId) empname,
  6325. 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
  6326. where fit.fitid = ?
  6327. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6328. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6329. if err != nil {
  6330. logs.Error(err)
  6331. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6332. return
  6333. }
  6334. ft["createdate"] = ft["createdate1"]
  6335. // data["tname"] = ft["tname"]
  6336. // data["tcode"] = ft["tcode"]
  6337. // data["tcolor"] = ft["tcolor"]
  6338. // data["fttype"] = ft["fttype"]
  6339. // data["ccname"] = ft["ccname"]
  6340. // data["source"] = ft["source"]
  6341. // data["version"] = ft["version"]
  6342. // data["remark"] = ft["remark"]
  6343. for n, ft2 := range ftList {
  6344. if i < n {
  6345. if ft["tname"].(string) != ft2["tname"].(string) {
  6346. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6347. }
  6348. if _, ok := ft["tcode"]; ok {
  6349. if _, ok := ft2["tcode"]; ok {
  6350. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6351. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6352. }
  6353. }
  6354. }
  6355. if _, ok := ft["tcolor"]; ok {
  6356. if _, ok := ft2["tcolor"]; ok {
  6357. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6358. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6359. }
  6360. }
  6361. }
  6362. if _, ok := ft["fttype"]; ok {
  6363. if _, ok := ft2["fttype"]; ok {
  6364. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6365. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6366. }
  6367. }
  6368. }
  6369. if _, ok := ft["ccname"]; ok {
  6370. if _, ok := ft2["ccname"]; ok {
  6371. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6372. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6373. }
  6374. }
  6375. }
  6376. if _, ok := ft["source"]; ok {
  6377. if _, ok := ft2["source"]; ok {
  6378. if ft["source"].(string) != ft2["source"].(string) {
  6379. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6380. }
  6381. }
  6382. }
  6383. if _, ok := ft["version"]; ok {
  6384. if _, ok := ft2["version"]; ok {
  6385. if ft["version"].(int64) != ft2["version"].(int64) {
  6386. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6387. }
  6388. }
  6389. }
  6390. if _, ok := ft["remark"]; ok {
  6391. if _, ok := ft2["remark"]; ok {
  6392. if ft["remark"].(string) != ft2["remark"].(string) {
  6393. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6394. }
  6395. }
  6396. }
  6397. break
  6398. }
  6399. }
  6400. dataList := make([]map[string]interface{}, 0)
  6401. if len(fithisList) > 0 {
  6402. for _, fit := range fithisList {
  6403. data := make(map[string]interface{})
  6404. data["feedgroup"] = fit["feedgroup"]
  6405. data["fname"] = fit["fname"]
  6406. data["empname"] = fit["empname"]
  6407. if fit["Eweight"] != nil {
  6408. if fit["Eweight"].(string) != fit["weight"].(string) {
  6409. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6410. } else {
  6411. data["fweight"] = fit["Eweight"]
  6412. }
  6413. data["fweightstatus"] = 1
  6414. } else {
  6415. data["fweight"] = fit["weight"]
  6416. data["fweightstatus"] = 0
  6417. }
  6418. data["autosecond"] = fit["autosecond"]
  6419. // data["tname"] = ft["tname"]
  6420. // data["tcode"] = ft["tcode"]
  6421. // data["tcolor"] = ft["tcolor"]
  6422. // data["fttype"] = ft["fttype"]
  6423. // data["ccname"] = ft["ccname"]
  6424. // data["source"] = ft["source"]
  6425. // data["version"] = ft["version"]
  6426. // data["remark"] = ft["remark"]
  6427. // data["createdate"] = ft["createdate1"]
  6428. // ft["fit"] = data
  6429. dataList = append(dataList, data)
  6430. }
  6431. } else {
  6432. for _, fit := range ftdetailList {
  6433. data := make(map[string]interface{})
  6434. data["feedgroup"] = fit["feedgroup"]
  6435. data["fname"] = fit["fname"]
  6436. // if fit["Eweight"] != nil {
  6437. // data["weight"] = fit["Eweight"]
  6438. // } else {
  6439. data["fweight"] = fit["fweight"]
  6440. // }
  6441. data["autosecond"] = fit["autosecond"]
  6442. // ft["fit"] = data
  6443. dataList = append(dataList, data)
  6444. }
  6445. }
  6446. ft["fit"] = dataList
  6447. }
  6448. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6449. }
  6450. func UpdateMaterialTMR(c *gin.Context) {
  6451. appG := app.Gin{C: c}
  6452. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6453. parammaps := gofasion.NewFasion(string(dataByte))
  6454. tmrid := parammaps.Get("tmrid").ValueStr()
  6455. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6456. lppid := parammaps.Get("lppid").ValueStr()
  6457. times := parammaps.Get("times").ValueStr()
  6458. pastureid := parammaps.Get("pastureid").ValueStr()
  6459. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6460. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6461. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6462. tx := restful.Engine.NewSession()
  6463. defer tx.Close()
  6464. tx.Begin()
  6465. if tmrid != "1000" {
  6466. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6467. if err != nil {
  6468. logs.Error(err)
  6469. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6470. return
  6471. }
  6472. var maxstirfeed float64
  6473. for _, tmr := range tmrList {
  6474. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6475. }
  6476. if status == 0 {
  6477. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6478. if err != nil {
  6479. tx.Rollback()
  6480. logs.Error(err)
  6481. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6482. return
  6483. }
  6484. var lweight float64
  6485. for _, item := range lpplandtl1List {
  6486. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6487. lweight += fl
  6488. }
  6489. if lweight > maxstirfeed {
  6490. lweight = lweight - maxstirfeed
  6491. } else {
  6492. lweight = 0
  6493. }
  6494. if lweight > 0 {
  6495. lweight1 := lweight / float64(len(lpplandtl1List))
  6496. number := 0
  6497. for _, item := range lpplandtl1List {
  6498. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6499. if lweight1 >= fl {
  6500. number++
  6501. }
  6502. }
  6503. lweight := lweight / float64((len(lpplandtl1List) - number))
  6504. for _, item := range lpplandtl1List {
  6505. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6506. if lweight1 >= fl {
  6507. continue
  6508. }
  6509. if tmrtype == "1" {
  6510. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, 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. } else if tmrtype == "2" {
  6518. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6519. if err != nil {
  6520. tx.Rollback()
  6521. logs.Error(err)
  6522. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6523. return
  6524. }
  6525. }
  6526. if item["fttype"].(int64) == 0 {
  6527. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? 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. } else {
  6535. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6536. if err != nil {
  6537. tx.Rollback()
  6538. logs.Error(err)
  6539. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6540. return
  6541. }
  6542. }
  6543. }
  6544. } else {
  6545. for _, item := range lpplandtl1List {
  6546. // 自走式
  6547. if tmrtype == "1" {
  6548. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, 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. } else if tmrtype == "2" {
  6556. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6557. if err != nil {
  6558. logs.Error(err)
  6559. tx.Rollback()
  6560. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6561. return
  6562. }
  6563. }
  6564. }
  6565. }
  6566. } else if status == 1 {
  6567. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6568. if err != nil {
  6569. logs.Error(err)
  6570. tx.Rollback()
  6571. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6572. return
  6573. }
  6574. var lweight float64
  6575. for _, item := range lpplandtl1List {
  6576. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6577. lweight += fl
  6578. }
  6579. if lweight > maxstirfeed {
  6580. lweight = lweight - maxstirfeed
  6581. } else {
  6582. lweight = 0
  6583. }
  6584. for _, item := range lpplandtl1List {
  6585. if lweight > 0 {
  6586. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6587. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6588. if fl >= lweight {
  6589. item["lweight"] = fl - lweight
  6590. lweight = 0
  6591. if tmrtype == "1" {
  6592. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, 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. } else if tmrtype == "2" {
  6600. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6601. if err != nil {
  6602. logs.Error(err)
  6603. tx.Rollback()
  6604. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6605. return
  6606. }
  6607. }
  6608. if item["fttype"].(int64) == 0 {
  6609. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? 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. } else {
  6617. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6618. if err != nil {
  6619. logs.Error(err)
  6620. tx.Rollback()
  6621. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6622. return
  6623. }
  6624. }
  6625. } else {
  6626. lweight = lweight - fl
  6627. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6628. if err != nil {
  6629. logs.Error(err)
  6630. tx.Rollback()
  6631. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6632. return
  6633. }
  6634. if item["fttype"].(int64) == 0 {
  6635. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? 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. } else {
  6643. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6644. if err != nil {
  6645. logs.Error(err)
  6646. tx.Rollback()
  6647. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6648. return
  6649. }
  6650. }
  6651. }
  6652. } else {
  6653. // 自走式
  6654. if tmrtype == "1" {
  6655. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, 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. } else if tmrtype == "2" {
  6663. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6664. if err != nil {
  6665. logs.Error(err)
  6666. tx.Rollback()
  6667. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6668. return
  6669. }
  6670. }
  6671. }
  6672. }
  6673. } else {
  6674. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6675. if err != nil {
  6676. logs.Error(err)
  6677. tx.Rollback()
  6678. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6679. return
  6680. }
  6681. for _, item := range lpplandtl1List {
  6682. if item["fttype"].(int64) == 0 {
  6683. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? 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. } else {
  6691. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).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. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6700. if err != nil {
  6701. logs.Error(err)
  6702. tx.Rollback()
  6703. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6704. return
  6705. }
  6706. }
  6707. }
  6708. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6709. if err != nil {
  6710. logs.Error(err)
  6711. tx.Rollback()
  6712. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6713. return
  6714. }
  6715. } else {
  6716. if status == 2 {
  6717. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6718. if err != nil {
  6719. logs.Error(err)
  6720. tx.Rollback()
  6721. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6722. return
  6723. }
  6724. for _, item := range lpplandtl1List {
  6725. if item["fttype"].(int64) == 0 {
  6726. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? 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. } else {
  6734. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6735. if err != nil {
  6736. logs.Error(err)
  6737. tx.Rollback()
  6738. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6739. return
  6740. }
  6741. }
  6742. }
  6743. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", 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. } else {
  6751. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6752. if err != nil {
  6753. logs.Error(err)
  6754. tx.Rollback()
  6755. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6756. return
  6757. }
  6758. }
  6759. }
  6760. err := tx.Commit()
  6761. if err != nil {
  6762. logs.Error(err)
  6763. tx.Rollback()
  6764. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6765. return
  6766. }
  6767. appG.Response(http.StatusOK, e.SUCCESS, true)
  6768. }
  6769. func UpdateMaterialTMRDate(c *gin.Context) {
  6770. appG := app.Gin{C: c}
  6771. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6772. parammaps := gofasion.NewFasion(string(dataByte))
  6773. tmrid := parammaps.Get("tmrid").ValueStr()
  6774. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6775. lppid := parammaps.Get("lppid").ValueStr()
  6776. times := parammaps.Get("times").ValueStr()
  6777. pastureid := parammaps.Get("pastureid").ValueStr()
  6778. date := parammaps.Get("date").ValueStr()
  6779. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6780. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6781. tx := restful.Engine.NewSession()
  6782. defer tx.Close()
  6783. tx.Begin()
  6784. if tmrid != "1000" {
  6785. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6786. if err != nil {
  6787. logs.Error(err)
  6788. tx.Rollback()
  6789. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6790. return
  6791. }
  6792. var maxstirfeed float64
  6793. for _, tmr := range tmrList {
  6794. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6795. }
  6796. if status == 0 {
  6797. 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()
  6798. if err != nil {
  6799. logs.Error(err)
  6800. tx.Rollback()
  6801. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6802. return
  6803. }
  6804. var lweight float64
  6805. for _, item := range lpplandtl1List {
  6806. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6807. lweight += fl
  6808. }
  6809. if lweight > maxstirfeed {
  6810. lweight = lweight - maxstirfeed
  6811. } else {
  6812. lweight = 0
  6813. }
  6814. if lweight > 0 {
  6815. lweight1 := lweight / float64(len(lpplandtl1List))
  6816. number := 0
  6817. for _, item := range lpplandtl1List {
  6818. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6819. if lweight1 >= fl {
  6820. number++
  6821. }
  6822. }
  6823. lweight := lweight / float64((len(lpplandtl1List) - number))
  6824. for _, item := range lpplandtl1List {
  6825. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6826. if lweight1 >= fl {
  6827. continue
  6828. }
  6829. if tmrtype == "1" {
  6830. _, 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()
  6831. if err != nil {
  6832. logs.Error(err)
  6833. tx.Rollback()
  6834. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6835. return
  6836. }
  6837. } else if tmrtype == "2" {
  6838. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6839. if err != nil {
  6840. logs.Error(err)
  6841. tx.Rollback()
  6842. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6843. return
  6844. }
  6845. }
  6846. if item["fttype"].(int64) == 0 {
  6847. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? 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. } else {
  6855. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6856. if err != nil {
  6857. logs.Error(err)
  6858. tx.Rollback()
  6859. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6860. return
  6861. }
  6862. }
  6863. }
  6864. } else {
  6865. for _, item := range lpplandtl1List {
  6866. // 自走式
  6867. if tmrtype == "1" {
  6868. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, 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. } else if tmrtype == "2" {
  6876. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6877. if err != nil {
  6878. logs.Error(err)
  6879. tx.Rollback()
  6880. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6881. return
  6882. }
  6883. }
  6884. }
  6885. }
  6886. } else if status == 1 {
  6887. 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()
  6888. if err != nil {
  6889. logs.Error(err)
  6890. tx.Rollback()
  6891. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6892. return
  6893. }
  6894. var lweight float64
  6895. for _, item := range lpplandtl1List {
  6896. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6897. lweight += fl
  6898. }
  6899. if lweight > maxstirfeed {
  6900. lweight = lweight - maxstirfeed
  6901. } else {
  6902. lweight = 0
  6903. }
  6904. for _, item := range lpplandtl1List {
  6905. if lweight > 0 {
  6906. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6907. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6908. if fl >= lweight {
  6909. item["lweight"] = fl - lweight
  6910. lweight = 0
  6911. if tmrtype == "1" {
  6912. _, 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()
  6913. if err != nil {
  6914. logs.Error(err)
  6915. tx.Rollback()
  6916. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6917. return
  6918. }
  6919. } else if tmrtype == "2" {
  6920. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6921. if err != nil {
  6922. logs.Error(err)
  6923. tx.Rollback()
  6924. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6925. return
  6926. }
  6927. }
  6928. if item["fttype"].(int64) == 0 {
  6929. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? 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. } else {
  6937. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6938. if err != nil {
  6939. logs.Error(err)
  6940. tx.Rollback()
  6941. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6942. return
  6943. }
  6944. }
  6945. } else {
  6946. lweight = lweight - fl
  6947. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], 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. if item["fttype"].(int64) == 0 {
  6955. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? 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. } else {
  6963. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6964. if err != nil {
  6965. logs.Error(err)
  6966. tx.Rollback()
  6967. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6968. return
  6969. }
  6970. }
  6971. }
  6972. } else {
  6973. // 自走式
  6974. if tmrtype == "1" {
  6975. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, 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. } else if tmrtype == "2" {
  6983. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6984. if err != nil {
  6985. logs.Error(err)
  6986. tx.Rollback()
  6987. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6988. return
  6989. }
  6990. }
  6991. }
  6992. }
  6993. } else {
  6994. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6995. if err != nil {
  6996. logs.Error(err)
  6997. tx.Rollback()
  6998. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6999. return
  7000. }
  7001. for _, item := range lpplandtl1List {
  7002. if item["fttype"].(int64) == 0 {
  7003. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? 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. } else {
  7011. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], 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. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  7020. if err != nil {
  7021. logs.Error(err)
  7022. tx.Rollback()
  7023. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7024. return
  7025. }
  7026. }
  7027. }
  7028. _, 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()
  7029. if err != nil {
  7030. logs.Error(err)
  7031. tx.Rollback()
  7032. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7033. return
  7034. }
  7035. } else {
  7036. if status == 2 {
  7037. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  7038. if err != nil {
  7039. logs.Error(err)
  7040. tx.Rollback()
  7041. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7042. return
  7043. }
  7044. for _, item := range lpplandtl1List {
  7045. if item["fttype"].(int64) == 0 {
  7046. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? 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. } else {
  7054. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7055. if err != nil {
  7056. logs.Error(err)
  7057. tx.Rollback()
  7058. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7059. return
  7060. }
  7061. }
  7062. }
  7063. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", 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. } else {
  7071. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  7072. if err != nil {
  7073. logs.Error(err)
  7074. tx.Rollback()
  7075. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7076. return
  7077. }
  7078. }
  7079. }
  7080. err := tx.Commit()
  7081. if err != nil {
  7082. logs.Error(err)
  7083. tx.Rollback()
  7084. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7085. return
  7086. }
  7087. appG.Response(http.StatusOK, e.SUCCESS, true)
  7088. }
  7089. func Decimal(value float64) float64 {
  7090. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  7091. return value
  7092. }
  7093. func UpdateDailyData(c *gin.Context) {
  7094. appG := app.Gin{C: c}
  7095. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7096. parammaps := gofasion.NewFasion(string(dataByte))
  7097. pid := parammaps.Get("pid").ValueDefaultStr("0")
  7098. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  7099. sort := parammaps.Get("sort").ValueDefaultStr("0")
  7100. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  7101. date := parammaps.Get("date").ValueStr()
  7102. tx := restful.Engine.NewSession()
  7103. defer tx.Close()
  7104. 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()
  7105. if err != nil {
  7106. logs.Error("UpdateDailyData-error-0:", err)
  7107. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7108. return
  7109. }
  7110. if count > 0 {
  7111. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7112. return
  7113. }
  7114. tx.Begin()
  7115. if location == 0 {
  7116. fid := parammaps.Get("fid").ValueStr()
  7117. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  7118. if err != nil {
  7119. logs.Error("UpdateDailyData-error-1:", err)
  7120. tx.Rollback()
  7121. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7122. return
  7123. }
  7124. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7125. if err != nil {
  7126. logs.Error("UpdateDailyData-error-1:", err)
  7127. tx.Rollback()
  7128. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7129. return
  7130. }
  7131. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7132. if err != nil {
  7133. fmt.Println("Error:", err)
  7134. return
  7135. }
  7136. actualWeight := weight - num
  7137. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7138. if err != nil {
  7139. logs.Error("UpdateDailyData-error-2:", err)
  7140. tx.Rollback()
  7141. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7142. return
  7143. }
  7144. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7145. if err != nil {
  7146. logs.Error("UpdateDailyData-error-3:", err)
  7147. tx.Rollback()
  7148. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7149. return
  7150. }
  7151. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7152. if err != nil {
  7153. logs.Error("UpdateDailyData-error-4:", err)
  7154. tx.Rollback()
  7155. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7156. return
  7157. }
  7158. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7159. if err != nil {
  7160. logs.Error("UpdateDailyData-error-5:", err)
  7161. tx.Rollback()
  7162. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7163. return
  7164. }
  7165. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7166. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7167. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7168. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7169. if err != nil {
  7170. fmt.Println("Error:", err)
  7171. return
  7172. }
  7173. // actual := actualWeight / float64(len(downloadedplanList))
  7174. for _, item := range downloadedplanList {
  7175. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7176. if err != nil {
  7177. fmt.Println("Error:", err)
  7178. return
  7179. }
  7180. actual := itemLweight / lweight * actualWeight
  7181. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7182. if err != nil {
  7183. logs.Error("UpdateDailyData-error-6:", err)
  7184. tx.Rollback()
  7185. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7186. return
  7187. }
  7188. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7189. if err != nil {
  7190. logs.Error("UpdateDailyData-error-7:", err)
  7191. tx.Rollback()
  7192. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7193. return
  7194. }
  7195. _, 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()
  7196. if err != nil {
  7197. logs.Error("UpdateDailyData-error-8:", err)
  7198. tx.Rollback()
  7199. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7200. return
  7201. }
  7202. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7203. if err != nil {
  7204. logs.Error("UpdateDailyData-error-9:", err)
  7205. tx.Rollback()
  7206. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7207. return
  7208. }
  7209. }
  7210. } else {
  7211. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7212. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7213. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7214. // if err != nil {
  7215. // fmt.Println("Error:", err)
  7216. // return
  7217. // }
  7218. for _, item := range downloadedplanList {
  7219. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7220. if err != nil {
  7221. logs.Error("UpdateDailyData-error-6:", 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 set lweight =lweight+ lweight /? *? where pid = ?`,
  7227. item["lweight"], actualWeight, item["id"]).Execute()
  7228. if err != nil {
  7229. logs.Error("UpdateDailyData-error-7:", err)
  7230. tx.Rollback()
  7231. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7232. return
  7233. }
  7234. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7235. where pid = ?`, item["id"]).Execute()
  7236. if err != nil {
  7237. logs.Error("UpdateDailyData-error-8:", err)
  7238. tx.Rollback()
  7239. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7240. return
  7241. }
  7242. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7243. if err != nil {
  7244. logs.Error("UpdateDailyData-error-9:", err)
  7245. tx.Rollback()
  7246. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7247. return
  7248. }
  7249. }
  7250. }
  7251. } else {
  7252. fbarid := parammaps.Get("fbarid").ValueStr()
  7253. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7254. if err != nil {
  7255. logs.Error("UpdateDailyData-error-10:", err)
  7256. tx.Rollback()
  7257. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7258. return
  7259. }
  7260. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7261. if err != nil {
  7262. logs.Error("UpdateDailyData-error-1:", err)
  7263. tx.Rollback()
  7264. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7265. return
  7266. }
  7267. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7268. if err != nil {
  7269. fmt.Println("Error:", err)
  7270. return
  7271. }
  7272. actualWeight := weight - num
  7273. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7274. if err != nil {
  7275. logs.Error("UpdateDailyData-error-11:", 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 set lweight = lweight + lweight /? * ? where pid = ? `,
  7281. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7282. if err != nil {
  7283. logs.Error("UpdateDailyData-error-12:", err)
  7284. tx.Rollback()
  7285. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7286. return
  7287. }
  7288. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7289. where pid = ? `, pid).Execute()
  7290. if err != nil {
  7291. logs.Error("UpdateDailyData-error-13:", err)
  7292. tx.Rollback()
  7293. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7294. return
  7295. }
  7296. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7297. if err != nil {
  7298. logs.Error("UpdateDailyData-error-14:", err)
  7299. tx.Rollback()
  7300. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7301. return
  7302. }
  7303. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7304. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7305. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7306. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7307. if err != nil {
  7308. fmt.Println("Error:", err)
  7309. return
  7310. }
  7311. for _, item := range downloadedplanList {
  7312. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7313. if err != nil {
  7314. fmt.Println("Error:", err)
  7315. return
  7316. }
  7317. actual := itemLweight / lweight * actualWeight
  7318. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7319. if err != nil {
  7320. logs.Error("UpdateDailyData-error-6:", err)
  7321. tx.Rollback()
  7322. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7323. return
  7324. }
  7325. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7326. if err != nil {
  7327. logs.Error("UpdateDailyData-error-7:", err)
  7328. tx.Rollback()
  7329. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7330. return
  7331. }
  7332. _, 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()
  7333. if err != nil {
  7334. logs.Error("UpdateDailyData-error-8:", err)
  7335. tx.Rollback()
  7336. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7337. return
  7338. }
  7339. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7340. if err != nil {
  7341. logs.Error("UpdateDailyData-error-9:", err)
  7342. tx.Rollback()
  7343. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7344. return
  7345. }
  7346. }
  7347. } else {
  7348. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7349. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7350. for _, item := range downloadedplanList {
  7351. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7352. // if err != nil {
  7353. // fmt.Println("Error:", err)
  7354. // return
  7355. // }
  7356. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7357. if err != nil {
  7358. logs.Error("UpdateDailyData-error-6:", 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 set lweight =lweight+ lweight /? *? where pid = ?`,
  7364. item["lweight"], actualWeight, item["id"]).Execute()
  7365. if err != nil {
  7366. logs.Error("UpdateDailyData-error-7:", err)
  7367. tx.Rollback()
  7368. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7369. return
  7370. }
  7371. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7372. where pid = ?`, item["id"]).Execute()
  7373. if err != nil {
  7374. logs.Error("UpdateDailyData-error-8:", err)
  7375. tx.Rollback()
  7376. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7377. return
  7378. }
  7379. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7380. if err != nil {
  7381. logs.Error("UpdateDailyData-error-9:", err)
  7382. tx.Rollback()
  7383. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7384. return
  7385. }
  7386. }
  7387. }
  7388. }
  7389. err = tx.Commit()
  7390. if err != nil {
  7391. logs.Error("UpdateDailyData-error-20:", err)
  7392. tx.Rollback()
  7393. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7394. return
  7395. }
  7396. appG.Response(http.StatusOK, e.SUCCESS, true)
  7397. }
  7398. func GetFormulaStatistics(c *gin.Context) {
  7399. appG := app.Gin{C: c}
  7400. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7401. parammaps := gofasion.NewFasion(string(dataByte))
  7402. startTime := parammaps.Get("startTime").ValueStr()
  7403. endTime := parammaps.Get("endTime").ValueStr()
  7404. pastureId := parammaps.Get("pastureId").ValueStr()
  7405. tx := restful.Engine.NewSession()
  7406. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7407. if err != nil {
  7408. logs.Error("GetFormulaStatistics-error-1:", err)
  7409. tx.Rollback()
  7410. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7411. return
  7412. }
  7413. var feedtemplet, dateList []string
  7414. for _, f := range feedtempletList {
  7415. feedtemplet = append(feedtemplet, f["tname"].(string))
  7416. }
  7417. layout := "2006-01-02"
  7418. // s := "2023-05-01"
  7419. // e := "2023-05-23"
  7420. start, err := time.Parse(layout, startTime)
  7421. if err != nil {
  7422. fmt.Println(err)
  7423. return
  7424. }
  7425. end, err := time.Parse(layout, endTime)
  7426. if err != nil {
  7427. fmt.Println(err)
  7428. return
  7429. }
  7430. end = end.AddDate(0, 0, 1)
  7431. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7432. dateList = append(dateList, d.Format("2006-01-02"))
  7433. }
  7434. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7435. 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= ?
  7436. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7437. if err != nil {
  7438. logs.Error("GetFormulaStatistics-error-2:", err)
  7439. tx.Rollback()
  7440. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7441. return
  7442. }
  7443. var data2 [][]interface{}
  7444. for _, f := range feedtemplet {
  7445. var data1 []interface{}
  7446. for _, date := range dateList {
  7447. exist := false
  7448. for _, item := range downloadedplanList {
  7449. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7450. data1 = append(data1, item["total"])
  7451. exist = true
  7452. break
  7453. }
  7454. }
  7455. if !exist {
  7456. data1 = append(data1, 0)
  7457. }
  7458. }
  7459. data2 = append(data2, data1)
  7460. }
  7461. //前端让加的
  7462. feedtemplet = append(feedtemplet, "")
  7463. {
  7464. var data1 []interface{}
  7465. for _, f := range dateList {
  7466. // f = f + "\n"
  7467. fmt.Println(f)
  7468. data1 = append(data1, 0)
  7469. }
  7470. data2 = append(data2, data1)
  7471. }
  7472. resp := make(map[string]interface{}, 0)
  7473. resp["xdata"] = dateList
  7474. resp["data1"] = feedtemplet
  7475. resp["data2"] = data2
  7476. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7477. }
  7478. func GetPlanData(c *gin.Context) {
  7479. appG := app.Gin{C: c}
  7480. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7481. fsion := gofasion.NewFasion(string(dataByte))
  7482. sqlnamestr := fsion.Get("name").ValueStr()
  7483. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7484. offset := fsion.Get("offset").ValueDefaultInt(0)
  7485. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7486. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7487. month := fsion.Get("month").ValueDefaultStr("map")
  7488. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7489. tx := restful.Engine.NewSession()
  7490. err := tx.Begin()
  7491. defer func() {
  7492. switch {
  7493. case err != nil:
  7494. if tx != nil {
  7495. tx.Rollback()
  7496. }
  7497. default:
  7498. if tx != nil {
  7499. err = tx.Commit()
  7500. }
  7501. }
  7502. if tx != nil {
  7503. tx.Close()
  7504. }
  7505. }()
  7506. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7507. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7508. if sql != "" {
  7509. s_params := make([]interface{}, 0)
  7510. if fsion.HasKey("parammaps") {
  7511. parammaps := fsion.Get("parammaps")
  7512. paramslist := strings.Split(p, ",")
  7513. if len(paramslist) > 0 && p != "" {
  7514. for _, value := range paramslist {
  7515. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7516. if tempv, exists := c.Get("jwt_username"); exists {
  7517. s_params = append(s_params, tempv.(string))
  7518. } else {
  7519. s_params = append(s_params, "")
  7520. }
  7521. } else {
  7522. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7523. }
  7524. }
  7525. }
  7526. }
  7527. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7528. if err != nil {
  7529. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7530. } else {
  7531. paramslist1 := strings.Split(p1, ",")
  7532. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7533. s_params1 := make([]interface{}, 0)
  7534. if len(paramslist1) > 0 && p1 != "" {
  7535. for _, v := range paramslist1 {
  7536. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7537. }
  7538. }
  7539. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7540. for _, item := range arr {
  7541. trgaddressList := []string{}
  7542. if _, ok := item["trgaddress"]; ok {
  7543. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7544. for _, str := range trgaddressList1 {
  7545. if str != "" {
  7546. trgaddressList = append(trgaddressList, str)
  7547. }
  7548. }
  7549. }
  7550. item["trgaddressList"] = trgaddressList
  7551. }
  7552. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7553. }
  7554. // var wg sync.WaitGroup
  7555. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7556. // wg.Add(1)
  7557. // go func(value map[string]interface{}) {
  7558. // defer wg.Done()
  7559. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7560. // }(value)
  7561. // }
  7562. // wg.Wait()
  7563. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7564. }
  7565. } else {
  7566. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7567. }
  7568. }
  7569. func PostPlanData(c *gin.Context) {
  7570. appG := app.Gin{C: c}
  7571. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7572. fsion := gofasion.NewFasion(string(dataByte))
  7573. logging.Info("PostRJSBData err: ", string(dataByte))
  7574. s_params := make([]interface{}, 0)
  7575. tx := restful.Engine.NewSession()
  7576. err := tx.Begin()
  7577. defer func() {
  7578. switch {
  7579. case err != nil:
  7580. if tx != nil {
  7581. tx.Rollback()
  7582. }
  7583. default:
  7584. if tx != nil {
  7585. err = tx.Commit()
  7586. }
  7587. }
  7588. if tx != nil {
  7589. tx.Close()
  7590. }
  7591. }()
  7592. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7593. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7594. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7595. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7596. if !fsion.HasKey("parammaps") {
  7597. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7598. return
  7599. }
  7600. parammaps := fsion.Get("parammaps")
  7601. // paramslist := strings.Split(p, ",")
  7602. // if len(paramslist) > 0 && p != "" {
  7603. // for _, value := range paramslist {
  7604. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7605. // }
  7606. // }
  7607. // _, err = tx.SQL(sql, s_params...).Execute()
  7608. // if err != nil {
  7609. // logging.Error("PostRJSBData err: ", err)
  7610. // msg := geterrmsg(err.Error())
  7611. // appG.Response(http.StatusOK, e.ERROR, msg)
  7612. // return
  7613. // }
  7614. s_params = make([]interface{}, 0)
  7615. paramslist := strings.Split(p1, ",")
  7616. if len(paramslist) > 0 && p1 != "" {
  7617. for _, value := range paramslist {
  7618. // if value == "ID" {
  7619. // id := parammaps.Get("ID").ValueStr()
  7620. // pastureid := parammaps.Get("pastureid").ValueStr()
  7621. // 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
  7622. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7623. // if err != nil {
  7624. // logging.Error("PostRJSBData err: ", err)
  7625. // msg := geterrmsg(err.Error())
  7626. // appG.Response(http.StatusOK, e.ERROR, msg)
  7627. // return
  7628. // }
  7629. // for _, item := range datalist {
  7630. // id = item["id"]
  7631. // }
  7632. // s_params = append(s_params, id)
  7633. // } else {
  7634. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7635. // }
  7636. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7637. }
  7638. }
  7639. _, err = tx.SQL(sql1, s_params...).Execute()
  7640. if err != nil {
  7641. logging.Error("PostRJSBData1 err: ", err)
  7642. msg := geterrmsg(err.Error())
  7643. appG.Response(http.StatusOK, e.ERROR, msg)
  7644. return
  7645. }
  7646. s_params = make([]interface{}, 0)
  7647. paramslist = strings.Split(p2, ",")
  7648. if len(paramslist) > 0 && p2 != "" {
  7649. for _, value := range paramslist {
  7650. if value == "ID" {
  7651. id := parammaps.Get("ID").ValueStr()
  7652. pastureid := parammaps.Get("pastureid").ValueStr()
  7653. 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
  7654. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7655. if err != nil {
  7656. logging.Error("PostRJSBData err: ", err)
  7657. msg := geterrmsg(err.Error())
  7658. appG.Response(http.StatusOK, e.ERROR, msg)
  7659. return
  7660. }
  7661. for _, item := range datalist {
  7662. id = item["id"]
  7663. }
  7664. s_params = append(s_params, id)
  7665. } else {
  7666. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7667. }
  7668. }
  7669. }
  7670. _, err = tx.SQL(sql2, s_params...).Execute()
  7671. if err != nil {
  7672. logging.Error("PostRJSBData2 err: ", err)
  7673. msg := geterrmsg(err.Error())
  7674. appG.Response(http.StatusOK, e.ERROR, msg)
  7675. return
  7676. }
  7677. s_params = make([]interface{}, 0)
  7678. paramslist = strings.Split(p3, ",")
  7679. if len(paramslist) > 0 && p3 != "" {
  7680. for _, value := range paramslist {
  7681. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7682. }
  7683. }
  7684. _, err = tx.SQL(sql3, s_params...).Execute()
  7685. if err != nil {
  7686. logging.Error("PostRJSBData3 err: ", err)
  7687. msg := geterrmsg(err.Error())
  7688. appG.Response(http.StatusOK, e.ERROR, msg)
  7689. return
  7690. }
  7691. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7692. }
  7693. func CheckFeedTrgaddress(c *gin.Context) {
  7694. appG := app.Gin{C: c}
  7695. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7696. fsion := gofasion.NewFasion(string(dataByte))
  7697. fclassid := fsion.Get("fclassid").ValueStr()
  7698. feedId := fsion.Get("feedId").ValueStr()
  7699. backup1 := fsion.Get("backup1").ValueStr()
  7700. backup1List := strings.Split(backup1, ",")
  7701. tx := restful.Engine.NewSession()
  7702. defer tx.Close()
  7703. // if backup1 != "" {
  7704. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7705. for _, feed := range feedList {
  7706. if feed["backup1"] == "" {
  7707. continue
  7708. }
  7709. feedbackupList := strings.Split(feed["backup1"], ",")
  7710. for _, feedbackup := range feedbackupList {
  7711. for _, backup := range backup1List {
  7712. if feedbackup == backup {
  7713. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7714. return
  7715. }
  7716. }
  7717. }
  7718. }
  7719. // }
  7720. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7721. }
  7722. func ThiGetDataByName(c *gin.Context) {
  7723. appG := app.Gin{C: c}
  7724. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7725. fsion := gofasion.NewFasion(string(dataByte))
  7726. sqlnamestr := fsion.Get("name").ValueStr()
  7727. offset := fsion.Get("offset").ValueDefaultInt(0)
  7728. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7729. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7730. tx := restful.Engine.NewSession()
  7731. err := tx.Begin()
  7732. defer func() {
  7733. switch {
  7734. case err != nil:
  7735. logging.Error("tx.Begin 事务启动失败__error:", err)
  7736. if tx != nil {
  7737. tx.Rollback()
  7738. }
  7739. default:
  7740. if tx != nil {
  7741. err = tx.Commit()
  7742. }
  7743. }
  7744. if tx != nil {
  7745. tx.Close()
  7746. }
  7747. }()
  7748. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7749. if sql != "" {
  7750. s_params := make([]interface{}, 0)
  7751. if fsion.HasKey("parammaps") {
  7752. parammaps := fsion.Get("parammaps")
  7753. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7754. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7755. }
  7756. paramslist := strings.Split(p, ",")
  7757. if len(paramslist) > 0 && p != "" {
  7758. for _, value := range paramslist {
  7759. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7760. if tempv, exists := c.Get("jwt_username"); exists {
  7761. s_params = append(s_params, tempv.(string))
  7762. } else {
  7763. s_params = append(s_params, "")
  7764. }
  7765. } else {
  7766. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7767. }
  7768. }
  7769. }
  7770. } else if fsion.HasKey("params") {
  7771. params := fsion.Get("params").Array()
  7772. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7773. for _, v_params := range params {
  7774. s_params = append(s_params, v_params.ValueStr())
  7775. }
  7776. }
  7777. if returntype == "xlsx" {
  7778. var xlsxfile *xlsx.File
  7779. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7780. //c.File("c:/dd.xlsx")
  7781. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7782. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7783. c.Header("Content-Transfer-Encoding", "binary")
  7784. _ = xlsxfile.Write(c.Writer)
  7785. } else {
  7786. if sqlnamestr == "getHomepageStr" {
  7787. parammaps := fsion.Get("parammaps")
  7788. pastureid := parammaps.Get("pastureid").ValueStr()
  7789. var montimeList []float64
  7790. var montime float64
  7791. var wg sync.WaitGroup
  7792. now := time.Now()
  7793. for i := 0; i < 30; i++ {
  7794. wg.Add(1)
  7795. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7796. go func(nowstr string) {
  7797. defer wg.Done()
  7798. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7799. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7800. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7801. montimeList = append(montimeList, m)
  7802. }(nowstr)
  7803. }
  7804. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7805. if err != nil {
  7806. logging.Error("GetDataByName err: ", err)
  7807. msg := geterrmsg(err.Error())
  7808. appG.Response(http.StatusOK, e.ERROR, msg)
  7809. }
  7810. wg.Wait()
  7811. for _, m := range montimeList {
  7812. montime += m
  7813. }
  7814. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7815. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7816. return
  7817. }
  7818. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7819. if err != nil {
  7820. logging.Error("GetDataByName err: ", err)
  7821. msg := geterrmsg(err.Error())
  7822. appG.Response(http.StatusOK, e.ERROR, msg)
  7823. } else {
  7824. if sqlnamestr == "getFeedTrgaddressList" {
  7825. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7826. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7827. trgaddressList := []string{}
  7828. for _, str := range trgaddressList1 {
  7829. if str != "" {
  7830. trgaddressList = append(trgaddressList, str)
  7831. }
  7832. }
  7833. item["trgaddressList"] = trgaddressList
  7834. }
  7835. }
  7836. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7837. }
  7838. }
  7839. } else {
  7840. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7841. }
  7842. }
  7843. // func ToggleCcount(c *gin.Context) {
  7844. // appG := app.Gin{C: c}
  7845. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7846. // fsion := gofasion.NewFasion(string(dataByte))
  7847. // // 0 实际 1 软件
  7848. // status := fsion.Get("status").ValueDefaultInt64(0)
  7849. // pastureId := fsion.Get("pastureId").ValueStr()
  7850. // tx := restful.Engine.NewSession()
  7851. // err := tx.Begin()
  7852. // defer func() {
  7853. // switch {
  7854. // case err != nil:
  7855. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7856. // if tx != nil {
  7857. // tx.Rollback()
  7858. // }
  7859. // default:
  7860. // if tx != nil {
  7861. // err = tx.Commit()
  7862. // }
  7863. // }
  7864. // if tx != nil {
  7865. // tx.Close()
  7866. // }
  7867. // }()
  7868. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7869. // if err != nil {
  7870. // logs.Error(err)
  7871. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7872. // return
  7873. // }
  7874. // for _, bar := range barList {
  7875. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7876. // if err != nil {
  7877. // logs.Error(err)
  7878. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7879. // return
  7880. // }
  7881. // if !exist {
  7882. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7883. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7884. // if err != nil {
  7885. // logs.Error(err)
  7886. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7887. // return
  7888. // }
  7889. // }
  7890. // }
  7891. // if status == 0 {
  7892. // tx.Exec(`update feedp set ccount = actualcount `)
  7893. // }else{
  7894. // tx.Exec(`update feedp set ccount = softccount `)
  7895. // }
  7896. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7897. // if err != nil {
  7898. // logs.Error(err)
  7899. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7900. // return
  7901. // }
  7902. // for _, feedpData :=range feedpList{
  7903. // var feedpargs []interface{}
  7904. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7905. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7906. // if _, ok := feedpData["ftname"]; ok {
  7907. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7908. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7909. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7910. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7911. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7912. // } else {
  7913. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7914. // }
  7915. // if _, ok := feedpData["ptsfname"]; ok {
  7916. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7917. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7918. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7919. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7920. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7921. // } else {
  7922. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7923. // }
  7924. // upFeedpSql += " where barname = ? and pastureid = ? "
  7925. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7926. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7927. // if err != nil {
  7928. // logs.Error(err)
  7929. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7930. // return
  7931. // }
  7932. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7933. // if err != nil {
  7934. // logs.Error(err)
  7935. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7936. // return
  7937. // }
  7938. // if !exist1 {
  7939. // _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  7940. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7941. // if err != nil {
  7942. // logs.Error(err)
  7943. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7944. // return
  7945. // }
  7946. // }
  7947. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7948. // if err != nil {
  7949. // logs.Error(err)
  7950. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7951. // return
  7952. // }
  7953. // if !exist2 {
  7954. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,2,0,0,0,-1,-1) `,
  7955. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7956. // if err != nil {
  7957. // logs.Error(err)
  7958. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7959. // return
  7960. // }
  7961. // }
  7962. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7963. // if err != nil {
  7964. // logs.Error(err)
  7965. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7966. // return
  7967. // }
  7968. // if !exist3 {
  7969. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,3,0,0,0,-1,-1) `,
  7970. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7971. // if err != nil {
  7972. // logs.Error(err)
  7973. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7974. // return
  7975. // }
  7976. // }
  7977. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7978. // if err != nil {
  7979. // logs.Error(err)
  7980. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7981. // return
  7982. // }
  7983. // if !exist4 {
  7984. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,4,0,0,0,-1,-1) `,
  7985. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7986. // if err != nil {
  7987. // logs.Error(err)
  7988. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7989. // return
  7990. // }
  7991. // }
  7992. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7993. // if err != nil {
  7994. // logs.Error(err)
  7995. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7996. // return
  7997. // }
  7998. // if !exist5 {
  7999. // _, 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) `,
  8000. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  8001. // if err != nil {
  8002. // logs.Error(err)
  8003. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8004. // return
  8005. // }
  8006. // }
  8007. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  8008. // if err != nil {
  8009. // logs.Error(err)
  8010. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8011. // return
  8012. // }
  8013. // if !exist6 {
  8014. // _, 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) `,
  8015. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  8016. // if err != nil {
  8017. // logs.Error(err)
  8018. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8019. // return
  8020. // }
  8021. // }
  8022. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8023. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8024. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8025. // and pastureid = ? and times = ?`
  8026. // var fpdargs1 []interface{}
  8027. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8028. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8029. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8030. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8031. // if err != nil {
  8032. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8033. // return
  8034. // }
  8035. // var fpdargs2 []interface{}
  8036. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8037. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8038. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8039. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8040. // if err != nil {
  8041. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8042. // return
  8043. // }
  8044. // var fpdargs3 []interface{}
  8045. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8046. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8047. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8048. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8049. // if err != nil {
  8050. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8051. // return
  8052. // }
  8053. // var fpdargs4 []interface{}
  8054. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8055. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8056. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8057. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8058. // if err != nil {
  8059. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8060. // return
  8061. // }
  8062. // var fpdargs5 []interface{}
  8063. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8064. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8065. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8066. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8067. // if err != nil {
  8068. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8069. // return
  8070. // }
  8071. // var fpdargs6 []interface{}
  8072. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8073. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8074. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8075. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8076. // if err != nil {
  8077. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8078. // return
  8079. // }
  8080. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8081. // 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()
  8082. // if err != nil {
  8083. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8084. // return
  8085. // }
  8086. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8087. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8088. // upFpdetailList := make([]*upFpdetail, 0)
  8089. // for _, newfpd := range newList {
  8090. // for _, oldfpd := range oldFpdList {
  8091. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8092. // var oldweight, newweight float64
  8093. // if oldfpd["weight"] != nil {
  8094. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8095. // }
  8096. // if newfpd["weight"] != nil {
  8097. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8098. // }
  8099. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8100. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  8101. // Old: oldweight,
  8102. // New: newweight,
  8103. // Times: newfpd["times"].(int64),
  8104. // Ptid: newfpd["ptid"].(int64),
  8105. // Fweight: fweight,
  8106. // Id: oldfpd["id"].(int64),
  8107. // })
  8108. // break
  8109. // }
  8110. // }
  8111. // }
  8112. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8113. // }
  8114. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8115. // }
  8116. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8117. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8118. if err != nil {
  8119. return err
  8120. }
  8121. for _, item := range feedpList {
  8122. // if item["ftid"].(string) != data["ftid"].(string) {
  8123. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8124. if err != nil {
  8125. return err
  8126. }
  8127. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8128. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8129. if err != nil {
  8130. return err
  8131. }
  8132. // }
  8133. }
  8134. return nil
  8135. }
  8136. func PostPlanDatas(c *gin.Context) {
  8137. appG := app.Gin{C: c}
  8138. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8139. fsions := gofasion.NewFasion(string(dataByte))
  8140. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8141. tx := restful.Engine.NewSession()
  8142. err := tx.Begin()
  8143. defer func() {
  8144. switch {
  8145. case err != nil:
  8146. if tx != nil {
  8147. tx.Rollback()
  8148. }
  8149. default:
  8150. if tx != nil {
  8151. err = tx.Commit()
  8152. }
  8153. }
  8154. if tx != nil {
  8155. tx.Close()
  8156. }
  8157. }()
  8158. pastureId := fsions.Get("pastureid").ValueStr()
  8159. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8160. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8161. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8162. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8163. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8164. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8165. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8166. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8167. for _, parammaps := range fsions.Get("arrList").Array() {
  8168. fmt.Println(parammaps.Json())
  8169. if parammaps.Json() == "null" {
  8170. continue
  8171. }
  8172. // if !fsion.HasKey("arrList") {
  8173. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8174. // return
  8175. // continue
  8176. // }
  8177. // parammaps := fsion.Get("arrList")
  8178. s_params := make([]interface{}, 0)
  8179. // paramslist := strings.Split(p, ",")
  8180. // if len(paramslist) > 0 && p != "" {
  8181. // for _, value := range paramslist {
  8182. // if value == "pastureid" {
  8183. // s_params = append(s_params, pastureId)
  8184. // } else {
  8185. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8186. // }
  8187. // }
  8188. // }
  8189. // _, err = tx.SQL(sql, s_params...).Execute()
  8190. // if err != nil {
  8191. // logging.Error("PostRJSBData err: ", err)
  8192. // msg := geterrmsg(err.Error())
  8193. // appG.Response(http.StatusOK, e.ERROR, msg)
  8194. // return
  8195. // }
  8196. s_params = make([]interface{}, 0)
  8197. paramslist := strings.Split(p1, ",")
  8198. if len(paramslist) > 0 && p1 != "" {
  8199. for _, value := range paramslist {
  8200. // if value == "ID" {
  8201. // id := parammaps.Get("ID").ValueStr()
  8202. // pastureid := parammaps.Get("pastureid").ValueStr()
  8203. // 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
  8204. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8205. // if err != nil {
  8206. // logging.Error("PostRJSBData err: ", err)
  8207. // msg := geterrmsg(err.Error())
  8208. // appG.Response(http.StatusOK, e.ERROR, msg)
  8209. // return
  8210. // }
  8211. // for _, item := range datalist {
  8212. // id = item["id"]
  8213. // }
  8214. // s_params = append(s_params, id)
  8215. // } else {
  8216. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8217. // }
  8218. if value == "pastureid" {
  8219. s_params = append(s_params, pastureId)
  8220. } else {
  8221. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8222. }
  8223. }
  8224. }
  8225. _, err = tx.SQL(sql1, s_params...).Execute()
  8226. if err != nil {
  8227. logging.Error("PostRJSBData1 err: ", err)
  8228. msg := geterrmsg(err.Error())
  8229. appG.Response(http.StatusOK, e.ERROR, msg)
  8230. return
  8231. }
  8232. s_params = make([]interface{}, 0)
  8233. paramslist = strings.Split(p2, ",")
  8234. if len(paramslist) > 0 && p2 != "" {
  8235. for _, value := range paramslist {
  8236. if value == "ID" {
  8237. id := parammaps.Get("ID").ValueStr()
  8238. pastureid := parammaps.Get("pastureid").ValueStr()
  8239. 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
  8240. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8241. if err != nil {
  8242. logging.Error("PostRJSBData err: ", err)
  8243. msg := geterrmsg(err.Error())
  8244. appG.Response(http.StatusOK, e.ERROR, msg)
  8245. return
  8246. }
  8247. for _, item := range datalist {
  8248. id = item["id"]
  8249. }
  8250. s_params = append(s_params, id)
  8251. } else if value == "pastureid" {
  8252. s_params = append(s_params, pastureId)
  8253. } else {
  8254. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8255. }
  8256. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8257. }
  8258. }
  8259. _, err = tx.SQL(sql2, s_params...).Execute()
  8260. if err != nil {
  8261. logging.Error("PostRJSBData2 err: ", err)
  8262. msg := geterrmsg(err.Error())
  8263. appG.Response(http.StatusOK, e.ERROR, msg)
  8264. return
  8265. }
  8266. s_params = make([]interface{}, 0)
  8267. paramslist = strings.Split(p3, ",")
  8268. if len(paramslist) > 0 && p3 != "" {
  8269. for _, value := range paramslist {
  8270. if value == "pastureid" {
  8271. s_params = append(s_params, pastureId)
  8272. } else {
  8273. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8274. }
  8275. }
  8276. }
  8277. _, err = tx.SQL(sql3, s_params...).Execute()
  8278. if err != nil {
  8279. logging.Error("PostRJSBData3 err: ", err)
  8280. msg := geterrmsg(err.Error())
  8281. appG.Response(http.StatusOK, e.ERROR, msg)
  8282. return
  8283. }
  8284. }
  8285. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8286. }
  8287. func FpdBatchEdit(c *gin.Context) {
  8288. appG := app.Gin{C: c}
  8289. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8290. fsions := gofasion.NewFasion(string(dataByte))
  8291. barList := fsions.Get("barList").Array()
  8292. pastureid := fsions.Get("pastureId").ValueStr()
  8293. tx := restful.Engine.NewSession()
  8294. defer tx.Close()
  8295. 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
  8296. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8297. if err != nil {
  8298. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8299. return
  8300. }
  8301. for _, barFsions := range barList {
  8302. dataexcel := make(map[string]interface{}, 0)
  8303. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8304. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8305. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8306. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8307. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8308. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8309. continue
  8310. }
  8311. /*
  8312. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8313. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8314. if err != nil {
  8315. logs.Error(err)
  8316. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8317. return
  8318. }
  8319. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8320. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8321. if err != nil {
  8322. logs.Error(err)
  8323. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8324. return
  8325. }
  8326. */
  8327. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8328. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8329. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8330. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8331. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8332. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8333. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8334. if err != nil {
  8335. logs.Error(err)
  8336. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8337. return
  8338. }
  8339. if !ftexist {
  8340. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8341. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8342. if err != nil {
  8343. logs.Error(err)
  8344. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8345. return
  8346. }
  8347. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8348. if err != nil {
  8349. logs.Error(err)
  8350. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8351. return
  8352. }
  8353. }
  8354. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8355. if err != nil {
  8356. logs.Error(err)
  8357. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8358. return
  8359. }
  8360. if !exist {
  8361. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8362. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8363. if err != nil {
  8364. logs.Error(err)
  8365. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8366. return
  8367. }
  8368. }
  8369. var feedpargs []interface{}
  8370. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8371. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8372. if _, ok := dataexcel["ftname"]; ok {
  8373. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8374. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8375. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8376. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8377. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8378. } else {
  8379. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8380. }
  8381. if _, ok := dataexcel["ptsfname"]; ok {
  8382. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8383. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8384. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8385. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8386. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8387. } else {
  8388. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8389. }
  8390. upFeedpSql += " where barname = ? and pastureid = ? "
  8391. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8392. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8393. if err != nil {
  8394. logs.Error(err)
  8395. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8396. return
  8397. }
  8398. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8399. if err != nil {
  8400. logs.Error(err)
  8401. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8402. return
  8403. }
  8404. if !exist1 {
  8405. _, 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) `,
  8406. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8407. if err != nil {
  8408. logs.Error(err)
  8409. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8410. return
  8411. }
  8412. }
  8413. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8414. if err != nil {
  8415. logs.Error(err)
  8416. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8417. return
  8418. }
  8419. if !exist2 {
  8420. _, 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) `,
  8421. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8422. if err != nil {
  8423. logs.Error(err)
  8424. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8425. return
  8426. }
  8427. }
  8428. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8429. if err != nil {
  8430. logs.Error(err)
  8431. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8432. return
  8433. }
  8434. if !exist3 {
  8435. _, 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) `,
  8436. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8437. if err != nil {
  8438. logs.Error(err)
  8439. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8440. return
  8441. }
  8442. }
  8443. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8444. if err != nil {
  8445. logs.Error(err)
  8446. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8447. return
  8448. }
  8449. if !exist4 {
  8450. _, 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) `,
  8451. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8452. if err != nil {
  8453. logs.Error(err)
  8454. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8455. return
  8456. }
  8457. }
  8458. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8459. if err != nil {
  8460. logs.Error(err)
  8461. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8462. return
  8463. }
  8464. if !exist5 {
  8465. _, 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) `,
  8466. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8467. if err != nil {
  8468. logs.Error(err)
  8469. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8470. return
  8471. }
  8472. }
  8473. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8474. if err != nil {
  8475. logs.Error(err)
  8476. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8477. return
  8478. }
  8479. if !exist6 {
  8480. _, 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) `,
  8481. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8482. if err != nil {
  8483. logs.Error(err)
  8484. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8485. return
  8486. }
  8487. }
  8488. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8489. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8490. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8491. and pastureid = ? and times = ?`
  8492. var fpdargs1 []interface{}
  8493. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8494. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8495. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8496. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8497. if err != nil {
  8498. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8499. return
  8500. }
  8501. var fpdargs2 []interface{}
  8502. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8503. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8504. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8505. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8506. if err != nil {
  8507. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8508. return
  8509. }
  8510. var fpdargs3 []interface{}
  8511. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8512. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8513. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8514. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8515. if err != nil {
  8516. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8517. return
  8518. }
  8519. var fpdargs4 []interface{}
  8520. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8521. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8522. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8523. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8524. if err != nil {
  8525. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8526. return
  8527. }
  8528. var fpdargs5 []interface{}
  8529. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8530. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8531. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8532. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8533. if err != nil {
  8534. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8535. return
  8536. }
  8537. var fpdargs6 []interface{}
  8538. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8539. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8540. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8541. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8542. if err != nil {
  8543. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8544. return
  8545. }
  8546. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8547. 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()
  8548. if err != nil {
  8549. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8550. return
  8551. }
  8552. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8553. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8554. upFpdetailList := make([]*upFpdetail, 0)
  8555. for _, newfpd := range newList {
  8556. for _, oldfpd := range oldFpdList {
  8557. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8558. var oldweight, newweight float64
  8559. if oldfpd["weight"] != nil {
  8560. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8561. }
  8562. if newfpd["weight"] != nil {
  8563. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8564. }
  8565. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8566. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8567. Old: oldweight,
  8568. New: newweight,
  8569. Times: newfpd["times"].(int64),
  8570. Ptid: newfpd["ptid"].(int64),
  8571. Fweight: fweight,
  8572. Id: oldfpd["id"].(int64),
  8573. })
  8574. break
  8575. }
  8576. }
  8577. }
  8578. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8579. }
  8580. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8581. }
  8582. func UdBarSync(c *gin.Context) {
  8583. appG := app.Gin{C: c}
  8584. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8585. fsions := gofasion.NewFasion(string(dataByte))
  8586. pastureid := fsions.Get("pastureId").ValueStr()
  8587. tx := restful.Engine.NewSession()
  8588. defer tx.Close()
  8589. pastureinfo := new(udPastureInfo)
  8590. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8591. if err != nil {
  8592. logs.Error(err)
  8593. return
  8594. }
  8595. // gm.UdBarSync(pastureid, pastureinfo.Werks)
  8596. jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8597. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8598. }
  8599. func UdFeedSync(c *gin.Context) {
  8600. appG := app.Gin{C: c}
  8601. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8602. fsions := gofasion.NewFasion(string(dataByte))
  8603. pastureid := fsions.Get("pastureId").ValueStr()
  8604. tx := restful.Engine.NewSession()
  8605. defer tx.Close()
  8606. pastureinfo := new(udPastureInfo)
  8607. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8608. if err != nil {
  8609. logs.Error(err)
  8610. return
  8611. }
  8612. // gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8613. jpud.UdFeedSync(pastureid, pastureinfo.Werks)
  8614. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8615. }
  8616. func UdFeedtempletPush(c *gin.Context) {
  8617. appG := app.Gin{C: c}
  8618. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8619. fsions := gofasion.NewFasion(string(dataByte))
  8620. pastureid := fsions.Get("pastureId").ValueStr()
  8621. date := fsions.Get("date").ValueStr()
  8622. tx := restful.Engine.NewSession()
  8623. defer tx.Close()
  8624. pastureinfo := new(udPastureInfo)
  8625. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8626. if err != nil {
  8627. logs.Error(err)
  8628. return
  8629. }
  8630. // gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8631. jpud.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8632. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8633. }
  8634. func UdUtirPush(c *gin.Context) {
  8635. appG := app.Gin{C: c}
  8636. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8637. fsions := gofasion.NewFasion(string(dataByte))
  8638. pastureid := fsions.Get("pastureId").ValueStr()
  8639. date := fsions.Get("date").ValueStr()
  8640. tx := restful.Engine.NewSession()
  8641. defer tx.Close()
  8642. pastureinfo := new(udPastureInfo)
  8643. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8644. if err != nil {
  8645. logs.Error(err)
  8646. return
  8647. }
  8648. // gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8649. jpud.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8650. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8651. }
  8652. func UdBarFeedRemainPush(c *gin.Context) {
  8653. appG := app.Gin{C: c}
  8654. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8655. fsions := gofasion.NewFasion(string(dataByte))
  8656. pastureid := fsions.Get("pastureId").ValueStr()
  8657. date := fsions.Get("date").ValueStr()
  8658. tx := restful.Engine.NewSession()
  8659. defer tx.Close()
  8660. pastureinfo := new(udPastureInfo)
  8661. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8662. if err != nil {
  8663. logs.Error(err)
  8664. return
  8665. }
  8666. // gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8667. jpud.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8668. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8669. }
  8670. func UdMaterialIssuePush(c *gin.Context) {
  8671. appG := app.Gin{C: c}
  8672. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8673. fsions := gofasion.NewFasion(string(dataByte))
  8674. pastureid := fsions.Get("pastureId").ValueStr()
  8675. date := fsions.Get("date").ValueStr()
  8676. tx := restful.Engine.NewSession()
  8677. defer tx.Close()
  8678. pastureinfo := new(udPastureInfo)
  8679. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8680. if err != nil {
  8681. logs.Error(err)
  8682. return
  8683. }
  8684. // gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8685. jpud.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8686. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8687. }
  8688. //搅拌
  8689. func YmyUtirPush(c *gin.Context) {
  8690. appG := app.Gin{C: c}
  8691. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8692. fsions := gofasion.NewFasion(string(dataByte))
  8693. pastureid := fsions.Get("pastureId").ValueStr()
  8694. date := fsions.Get("date").ValueStr()
  8695. tx := restful.Engine.NewSession()
  8696. defer tx.Close()
  8697. pastureinfo := new(udPastureInfo)
  8698. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8699. if err != nil {
  8700. logs.Error(err)
  8701. return
  8702. }
  8703. ymy.YmyUtirPush(pastureid, pastureinfo.Werks, date)
  8704. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8705. }
  8706. //撒料
  8707. func YmyMaterialIssuePush(c *gin.Context) {
  8708. appG := app.Gin{C: c}
  8709. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8710. fsions := gofasion.NewFasion(string(dataByte))
  8711. pastureid := fsions.Get("pastureId").ValueStr()
  8712. date := fsions.Get("date").ValueStr()
  8713. tx := restful.Engine.NewSession()
  8714. defer tx.Close()
  8715. pastureinfo := new(udPastureInfo)
  8716. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8717. if err != nil {
  8718. logs.Error(err)
  8719. return
  8720. }
  8721. ymy.YmyMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8722. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8723. }
  8724. func YmyFeedtempletPush(c *gin.Context) {
  8725. appG := app.Gin{C: c}
  8726. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8727. fsions := gofasion.NewFasion(string(dataByte))
  8728. pastureid := fsions.Get("pastureId").ValueStr()
  8729. date := fsions.Get("date").ValueStr()
  8730. tx := restful.Engine.NewSession()
  8731. defer tx.Close()
  8732. pastureinfo := new(udPastureInfo)
  8733. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8734. if err != nil {
  8735. logs.Error(err)
  8736. return
  8737. }
  8738. ymy.YmyFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8739. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8740. }
  8741. //饲料
  8742. func YmySyncFeed(c *gin.Context) {
  8743. appG := app.Gin{C: c}
  8744. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8745. fsions := gofasion.NewFasion(string(dataByte))
  8746. pastureid := fsions.Get("pastureId").ValueStr()
  8747. // date := fsions.Get("date").ValueStr()
  8748. tx := restful.Engine.NewSession()
  8749. defer tx.Close()
  8750. ymy.YmySyncFeed(pastureid)
  8751. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8752. }
  8753. // 栏舍
  8754. func YmySyncBar(c *gin.Context) {
  8755. appG := app.Gin{C: c}
  8756. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8757. fsions := gofasion.NewFasion(string(dataByte))
  8758. pastureid := fsions.Get("pastureId").ValueStr()
  8759. // date := fsions.Get("date").ValueStr()
  8760. tx := restful.Engine.NewSession()
  8761. defer tx.Close()
  8762. pastureinfo := new(udPastureInfo)
  8763. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8764. if err != nil {
  8765. logs.Error(err)
  8766. return
  8767. }
  8768. ymy.YmySyncBar(pastureinfo.Werks, pastureid)
  8769. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8770. }
  8771. func DelFeedTemplet(c *gin.Context) {
  8772. appG := app.Gin{C: c}
  8773. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8774. fsions := gofasion.NewFasion(string(dataByte))
  8775. ftId := fsions.Get("ftId").ValueStr()
  8776. // userId := fsions.Get("userId").ValueStr()
  8777. tx := restful.Engine.NewSession()
  8778. defer tx.Close()
  8779. _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
  8780. if err != nil {
  8781. logs.Error(err)
  8782. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8783. return
  8784. }
  8785. /*
  8786. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8787. if err != nil {
  8788. logs.Error(err)
  8789. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8790. return
  8791. }
  8792. */
  8793. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8794. if err != nil {
  8795. logs.Error(err)
  8796. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8797. return
  8798. }
  8799. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8800. if err != nil {
  8801. logs.Error(err)
  8802. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8803. return
  8804. }
  8805. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8806. if count > 0 {
  8807. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8808. if err != nil {
  8809. logs.Error(err)
  8810. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8811. return
  8812. }
  8813. }
  8814. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8815. if err != nil {
  8816. logs.Error(err)
  8817. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8818. return
  8819. }
  8820. // var barIdStr []string
  8821. // for _, bar := range barIdList {
  8822. // barIdStr = append(barIdStr, bar["barid"])
  8823. // }
  8824. // if len(barIdStr) > 0 {
  8825. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8826. // if err != nil {
  8827. // logs.Error(err)
  8828. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8829. // return
  8830. // }
  8831. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8832. // if err != nil {
  8833. // logs.Error(err)
  8834. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8835. // return
  8836. // }
  8837. // now := time.Now()
  8838. // for _, newFpd := range newFpdDataList {
  8839. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8840. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8841. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8842. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8843. // if err != nil {
  8844. // logs.Error(err)
  8845. // appG.Response(http.StatusOK, e.ERROR, false)
  8846. // return
  8847. // }
  8848. // }
  8849. // for _, newFeedp := range newFeedpList {
  8850. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8851. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8852. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8853. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8854. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8855. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8856. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8857. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8858. // if err != nil {
  8859. // logs.Error(err)
  8860. // appG.Response(http.StatusOK, e.ERROR, false)
  8861. // return
  8862. // }
  8863. // }
  8864. // }
  8865. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8866. }
  8867. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8868. sysOpt := new(models.SysOpt)
  8869. tx.Table("sysopt").Where("inforname = ?", "separateVehicles").Get(sysOpt)
  8870. lweight := 0.0
  8871. if sysOpt.InforValue != "" {
  8872. lweight, _ = strconv.ParseFloat(sysOpt.InforValue, 64)
  8873. } else if sysOpt.InforValue == "" || sysOpt.InforValue == "0" {
  8874. return
  8875. }
  8876. fmt.Println(sysOpt)
  8877. data := fasion["parammaps"].(map[string]interface{})
  8878. // plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(2) ").Count()
  8879. downloadedplanList := make([]*models.DownloadedPlan, 0)
  8880. tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype = 2 ").Find(&downloadedplanList)
  8881. fmt.Println(lweight)
  8882. for _, downloadedplan := range downloadedplanList {
  8883. if downloadedplan.LWeight < lweight {
  8884. break
  8885. }
  8886. downloadplandtl1List := make([]*models.DownloadPlanDtl1, 0)
  8887. downloadplandtl1ExecList := make([]*models.DownloadPlanDtl1Exec, 0)
  8888. downloadplandtl2List := make([]*models.DownloadPlanDtl2, 0)
  8889. tx.Table("downloadplandtl1").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1List)
  8890. tx.Table("downloadplandtl2").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl2List)
  8891. tx.Table("downloadplandtl1_exec").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1ExecList)
  8892. lweightCount := math.Floor(downloadedplan.LWeight / lweight)
  8893. for i := 0; i <= int(lweightCount); i++ {
  8894. if i == 0 {
  8895. tx.Exec(` update downloadedplan set lweight = ? where id = ? `, lweight, downloadedplan.ID)
  8896. for _, downloadplandtl1 := range downloadplandtl1List {
  8897. tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl1.LWeight, downloadplandtl1.ID)
  8898. }
  8899. for _, downloadplandtl2 := range downloadplandtl2List {
  8900. tx.Exec(` update downloadplandtl2 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8901. }
  8902. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  8903. tx.Exec(` update downloadplandtl1_exec set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8904. }
  8905. // && downloadedplan.LWeight >lweight
  8906. } else if i < int(lweightCount) {
  8907. parts := strings.Split(downloadedplan.ProjName, ".")
  8908. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  8909. data := &models.DownloadedPlan{
  8910. PastureID: downloadedplan.PastureID,
  8911. MyDate: downloadedplan.MyDate,
  8912. ProjName: strings.Join(parts, "."),
  8913. DataCaptureNo: downloadedplan.DataCaptureNo,
  8914. TmrID: downloadedplan.TmrID,
  8915. TmrtName: downloadedplan.TmrtName,
  8916. HaveButton: downloadedplan.HaveButton,
  8917. InButtonType: downloadedplan.InButtonType,
  8918. PlanTime: downloadedplan.PlanTime,
  8919. InTime: downloadedplan.InTime,
  8920. CompletedTime: downloadedplan.CompletedTime,
  8921. IsCompleted: downloadedplan.IsCompleted,
  8922. LpPlanType: downloadedplan.LpPlanType,
  8923. Times: downloadedplan.Times,
  8924. Sort: downloadedplan.Sort,
  8925. Remark: downloadedplan.Remark,
  8926. ItemNum: downloadedplan.ItemNum,
  8927. OutItems: downloadedplan.OutItems,
  8928. FeedPName: downloadedplan.FeedPName,
  8929. FeedPCount: downloadedplan.FeedPCount,
  8930. Pid: downloadedplan.Pid,
  8931. TempID: downloadedplan.TempID,
  8932. TempletName: downloadedplan.TempletName,
  8933. PtsTempID: downloadedplan.PtsTempID,
  8934. PtsTempletName: downloadedplan.PtsTempletName,
  8935. ThoWeight: downloadedplan.ThoWeight,
  8936. FpWeight: downloadedplan.FpWeight,
  8937. LWeight: lweight,
  8938. IWeight: downloadedplan.IWeight,
  8939. OWeight: downloadedplan.OWeight,
  8940. TVersion: downloadedplan.TVersion,
  8941. PtVersion: downloadedplan.PtVersion,
  8942. Enable: downloadedplan.Enable,
  8943. IsUse: downloadedplan.IsUse,
  8944. OldTmrID: downloadedplan.OldTmrID,
  8945. DriverID: downloadedplan.DriverID,
  8946. Artificial: downloadedplan.Artificial,
  8947. }
  8948. _, err := tx.Insert(data)
  8949. fmt.Println(data, err)
  8950. for _, downloadplandtl1 := range downloadplandtl1List {
  8951. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8952. d1 := &models.DownloadPlanDtl1{
  8953. PastureID: downloadplandtl1.PastureID,
  8954. Pid: data.ID,
  8955. Flpid: downloadplandtl1.Flpid,
  8956. Fid: downloadplandtl1.Fid,
  8957. LWeight: lweight / downloadedplan.LWeight * downloadplandtl1.LWeight,
  8958. Sort: downloadplandtl1.Sort,
  8959. ButtonType: downloadplandtl1.ButtonType,
  8960. OptDevice: downloadplandtl1.OptDevice,
  8961. FeedCode: downloadplandtl1.FeedCode,
  8962. FName: downloadplandtl1.FName,
  8963. FeedSort: downloadplandtl1.FeedSort,
  8964. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  8965. StirDelay: downloadplandtl1.StirDelay,
  8966. FWeight: downloadplandtl1.FWeight,
  8967. TmrLoadName: downloadplandtl1.TmrLoadName,
  8968. DryFeed: downloadplandtl1.DryFeed,
  8969. PriceFeed: downloadplandtl1.PriceFeed,
  8970. OutWeight: downloadplandtl1.OutWeight,
  8971. ErrRatio: downloadplandtl1.ErrRatio,
  8972. Date: downloadplandtl1.Date,
  8973. ButtonSucc: downloadplandtl1.ButtonSucc,
  8974. Type: downloadplandtl1.Type,
  8975. Deviation: downloadplandtl1.Deviation,
  8976. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  8977. }
  8978. tx.Insert(d1)
  8979. }
  8980. for _, downloadplandtl2 := range downloadplandtl2List {
  8981. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8982. d2 := &models.DownloadPlanDtl2{
  8983. PastureID: downloadplandtl2.PastureID,
  8984. Pid: data.ID,
  8985. Flpid: downloadplandtl2.Flpid,
  8986. Fbarid: downloadplandtl2.Fbarid,
  8987. FName: downloadplandtl2.FName,
  8988. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8989. LWeightHis: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8990. RemainLeftW: downloadplandtl2.RemainLeftW,
  8991. AllowRW: downloadplandtl2.AllowRW,
  8992. Sort: downloadplandtl2.Sort,
  8993. HaveButton: downloadplandtl2.HaveButton,
  8994. BeginTag: downloadplandtl2.BeginTag,
  8995. EndTag: downloadplandtl2.EndTag,
  8996. ButtonType: downloadplandtl2.ButtonType,
  8997. OptDevice: downloadplandtl2.OptDevice,
  8998. CowCount: downloadplandtl2.CowCount,
  8999. CowClassID: downloadplandtl2.CowClassID,
  9000. CowClassName: downloadplandtl2.CowClassName,
  9001. BigCowName: downloadplandtl2.BigCowName,
  9002. PWeight: downloadplandtl2.PWeight,
  9003. CCountRatio: downloadplandtl2.CCountRatio,
  9004. SumRTime: downloadplandtl2.SumRTime,
  9005. FeedTempletID: downloadplandtl2.FeedTempletID,
  9006. FeedTempletName: downloadplandtl2.FeedTempletName,
  9007. DryWeight: downloadplandtl2.DryWeight,
  9008. SumWeight: downloadplandtl2.SumWeight,
  9009. PriceWeight: downloadplandtl2.PriceWeight,
  9010. // ProcessTime :downloadplandtl2.ProcessTime ,
  9011. Fpid: downloadplandtl2.Fpid,
  9012. UseInBarType: downloadplandtl2.UseInBarType,
  9013. Date: downloadplandtl2.Date,
  9014. AllowRatio: downloadplandtl2.AllowRatio,
  9015. ErrRatio: downloadplandtl2.ErrRatio,
  9016. ButtonSucc: downloadplandtl2.ButtonSucc,
  9017. Type: downloadplandtl2.Type,
  9018. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9019. XxwBarCode: downloadplandtl2.XxwBarCode,
  9020. }
  9021. _, err := tx.Insert(d2)
  9022. fmt.Println(err)
  9023. }
  9024. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9025. d2 := &models.DownloadPlanDtl1Exec{
  9026. PastureID: downloadplandtl2.PastureID,
  9027. Pid: data.ID,
  9028. Flpid: downloadplandtl2.Flpid,
  9029. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9030. HaveButton: downloadplandtl2.HaveButton,
  9031. ButtonType: downloadplandtl2.ButtonType,
  9032. OptDevice: downloadplandtl2.OptDevice,
  9033. Sort: downloadplandtl2.Sort,
  9034. FName: downloadplandtl2.FName,
  9035. FCount: downloadplandtl2.FCount,
  9036. TmrLoadName: downloadplandtl2.TmrLoadName,
  9037. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9038. StirDelay: downloadplandtl2.StirDelay,
  9039. ButtonSucc: downloadplandtl2.ButtonSucc,
  9040. ErrRatio: downloadplandtl2.ErrRatio,
  9041. Date: downloadplandtl2.Date,
  9042. Type: downloadplandtl2.Type,
  9043. Deviation: downloadplandtl2.Deviation,
  9044. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9045. }
  9046. _, err := tx.Insert(d2)
  9047. fmt.Println(err)
  9048. }
  9049. } else {
  9050. parts := strings.Split(downloadedplan.ProjName, ".")
  9051. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  9052. if downloadedplan.LWeight-float64(i)*lweight <= 0 {
  9053. continue
  9054. }
  9055. data := &models.DownloadedPlan{
  9056. PastureID: downloadedplan.PastureID,
  9057. MyDate: downloadedplan.MyDate,
  9058. ProjName: strings.Join(parts, "."),
  9059. DataCaptureNo: downloadedplan.DataCaptureNo,
  9060. TmrID: downloadedplan.TmrID,
  9061. TmrtName: downloadedplan.TmrtName,
  9062. HaveButton: downloadedplan.HaveButton,
  9063. InButtonType: downloadedplan.InButtonType,
  9064. PlanTime: downloadedplan.PlanTime,
  9065. InTime: downloadedplan.InTime,
  9066. CompletedTime: downloadedplan.CompletedTime,
  9067. IsCompleted: downloadedplan.IsCompleted,
  9068. LpPlanType: downloadedplan.LpPlanType,
  9069. Times: downloadedplan.Times,
  9070. Sort: downloadedplan.Sort,
  9071. Remark: downloadedplan.Remark,
  9072. ItemNum: downloadedplan.ItemNum,
  9073. OutItems: downloadedplan.OutItems,
  9074. FeedPName: downloadedplan.FeedPName,
  9075. FeedPCount: downloadedplan.FeedPCount,
  9076. Pid: downloadedplan.Pid,
  9077. TempID: downloadedplan.TempID,
  9078. TempletName: downloadedplan.TempletName,
  9079. PtsTempID: downloadedplan.PtsTempID,
  9080. PtsTempletName: downloadedplan.PtsTempletName,
  9081. ThoWeight: downloadedplan.ThoWeight,
  9082. FpWeight: downloadedplan.FpWeight,
  9083. LWeight: downloadedplan.LWeight - float64(i)*lweight,
  9084. IWeight: downloadedplan.IWeight,
  9085. OWeight: downloadedplan.OWeight,
  9086. TVersion: downloadedplan.TVersion,
  9087. PtVersion: downloadedplan.PtVersion,
  9088. Enable: downloadedplan.Enable,
  9089. IsUse: downloadedplan.IsUse,
  9090. OldTmrID: downloadedplan.OldTmrID,
  9091. DriverID: downloadedplan.DriverID,
  9092. Artificial: downloadedplan.Artificial,
  9093. }
  9094. _, err := tx.Insert(data)
  9095. fmt.Println(data, err)
  9096. for _, downloadplandtl1 := range downloadplandtl1List {
  9097. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9098. d1 := &models.DownloadPlanDtl1{
  9099. PastureID: downloadplandtl1.PastureID,
  9100. Pid: data.ID,
  9101. Flpid: downloadplandtl1.Flpid,
  9102. Fid: downloadplandtl1.Fid,
  9103. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl1.LWeight,
  9104. Sort: downloadplandtl1.Sort,
  9105. ButtonType: downloadplandtl1.ButtonType,
  9106. OptDevice: downloadplandtl1.OptDevice,
  9107. FeedCode: downloadplandtl1.FeedCode,
  9108. FName: downloadplandtl1.FName,
  9109. FeedSort: downloadplandtl1.FeedSort,
  9110. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  9111. StirDelay: downloadplandtl1.StirDelay,
  9112. FWeight: downloadplandtl1.FWeight,
  9113. TmrLoadName: downloadplandtl1.TmrLoadName,
  9114. DryFeed: downloadplandtl1.DryFeed,
  9115. PriceFeed: downloadplandtl1.PriceFeed,
  9116. OutWeight: downloadplandtl1.OutWeight,
  9117. ErrRatio: downloadplandtl1.ErrRatio,
  9118. Date: downloadplandtl1.Date,
  9119. ButtonSucc: downloadplandtl1.ButtonSucc,
  9120. Type: downloadplandtl1.Type,
  9121. Deviation: downloadplandtl1.Deviation,
  9122. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  9123. }
  9124. tx.Insert(d1)
  9125. }
  9126. for _, downloadplandtl2 := range downloadplandtl2List {
  9127. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9128. d2 := &models.DownloadPlanDtl2{
  9129. PastureID: downloadplandtl2.PastureID,
  9130. Pid: data.ID,
  9131. Flpid: downloadplandtl2.Flpid,
  9132. Fbarid: downloadplandtl2.Fbarid,
  9133. FName: downloadplandtl2.FName,
  9134. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9135. LWeightHis: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9136. RemainLeftW: downloadplandtl2.RemainLeftW,
  9137. AllowRW: downloadplandtl2.AllowRW,
  9138. Sort: downloadplandtl2.Sort,
  9139. HaveButton: downloadplandtl2.HaveButton,
  9140. BeginTag: downloadplandtl2.BeginTag,
  9141. EndTag: downloadplandtl2.EndTag,
  9142. ButtonType: downloadplandtl2.ButtonType,
  9143. OptDevice: downloadplandtl2.OptDevice,
  9144. CowCount: downloadplandtl2.CowCount,
  9145. CowClassID: downloadplandtl2.CowClassID,
  9146. CowClassName: downloadplandtl2.CowClassName,
  9147. BigCowName: downloadplandtl2.BigCowName,
  9148. PWeight: downloadplandtl2.PWeight,
  9149. CCountRatio: downloadplandtl2.CCountRatio,
  9150. SumRTime: downloadplandtl2.SumRTime,
  9151. FeedTempletID: downloadplandtl2.FeedTempletID,
  9152. FeedTempletName: downloadplandtl2.FeedTempletName,
  9153. DryWeight: downloadplandtl2.DryWeight,
  9154. SumWeight: downloadplandtl2.SumWeight,
  9155. PriceWeight: downloadplandtl2.PriceWeight,
  9156. // ProcessTime :downloadplandtl2.ProcessTime ,
  9157. Fpid: downloadplandtl2.Fpid,
  9158. UseInBarType: downloadplandtl2.UseInBarType,
  9159. Date: downloadplandtl2.Date,
  9160. AllowRatio: downloadplandtl2.AllowRatio,
  9161. ErrRatio: downloadplandtl2.ErrRatio,
  9162. ButtonSucc: downloadplandtl2.ButtonSucc,
  9163. Type: downloadplandtl2.Type,
  9164. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9165. XxwBarCode: downloadplandtl2.XxwBarCode,
  9166. }
  9167. _, err := tx.Insert(d2)
  9168. fmt.Println(err)
  9169. }
  9170. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9171. d2 := &models.DownloadPlanDtl1Exec{
  9172. PastureID: downloadplandtl2.PastureID,
  9173. Pid: data.ID,
  9174. Flpid: downloadplandtl2.Flpid,
  9175. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9176. HaveButton: downloadplandtl2.HaveButton,
  9177. ButtonType: downloadplandtl2.ButtonType,
  9178. OptDevice: downloadplandtl2.OptDevice,
  9179. Sort: downloadplandtl2.Sort,
  9180. FName: downloadplandtl2.FName,
  9181. FCount: downloadplandtl2.FCount,
  9182. TmrLoadName: downloadplandtl2.TmrLoadName,
  9183. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9184. StirDelay: downloadplandtl2.StirDelay,
  9185. ButtonSucc: downloadplandtl2.ButtonSucc,
  9186. ErrRatio: downloadplandtl2.ErrRatio,
  9187. Date: downloadplandtl2.Date,
  9188. Type: downloadplandtl2.Type,
  9189. Deviation: downloadplandtl2.Deviation,
  9190. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9191. }
  9192. fmt.Println(d2)
  9193. _, err := tx.Insert(d2)
  9194. fmt.Println(err)
  9195. }
  9196. }
  9197. }
  9198. }
  9199. downloadedplanSortList := make([]*models.DownloadedPlan, 0)
  9200. tx.SQL(`SELECT * FROM downloadedplan WHERE mydate = ? ORDER BY projname`, data["startTime"]).Find(&downloadedplanSortList)
  9201. for i, d := range downloadedplanSortList {
  9202. tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, d.ID)
  9203. }
  9204. }
  9205. func EditPlanSort(c *gin.Context) {
  9206. appG := app.Gin{C: c}
  9207. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9208. fsions := gofasion.NewFasion(string(dataByte))
  9209. planIdStr := fsions.Get("planId").ValueStr()
  9210. mydate := fsions.Get("mydate").ValueStr()
  9211. sort := fsions.Get("sort").ValueStr()
  9212. tx := restful.Engine.NewSession()
  9213. defer tx.Close()
  9214. tx.Begin()
  9215. type downloadedplan struct {
  9216. Id int64 `xorm:"id"`
  9217. Sort int `xorm:"sort"`
  9218. Pid int64 `xorm:"pid"`
  9219. }
  9220. planInfo := new(downloadedplan)
  9221. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  9222. if err != nil {
  9223. logs.Error(err)
  9224. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9225. tx.Rollback()
  9226. return
  9227. }
  9228. sort1, _ := strconv.Atoi(sort)
  9229. if sort1 == planInfo.Sort {
  9230. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  9231. tx.Rollback()
  9232. return
  9233. }
  9234. 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()
  9235. if err != nil {
  9236. logs.Error(err)
  9237. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9238. tx.Rollback()
  9239. return
  9240. }
  9241. if count1 == 0 {
  9242. tx.Rollback()
  9243. logs.Error(err)
  9244. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  9245. return
  9246. }
  9247. 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()
  9248. if err != nil {
  9249. logs.Error(err)
  9250. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9251. tx.Rollback()
  9252. return
  9253. }
  9254. if count > 0 {
  9255. tx.Rollback()
  9256. logs.Error(err)
  9257. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  9258. return
  9259. }
  9260. if planInfo.Sort > sort1 {
  9261. 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()
  9262. if err != nil {
  9263. logs.Error(err)
  9264. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9265. tx.Rollback()
  9266. return
  9267. }
  9268. var minSort, pidCount int
  9269. for _, sort := range minSortList {
  9270. minSort, _ = strconv.Atoi(sort["sort"])
  9271. }
  9272. planList := make([]*downloadedplan, 0)
  9273. 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)
  9274. if err != nil {
  9275. logs.Error(err)
  9276. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9277. tx.Rollback()
  9278. return
  9279. }
  9280. planPid := planInfo.Pid
  9281. planList1 := make([]*downloadedplan, 0)
  9282. planList2 := make([]*downloadedplan, 0)
  9283. for _, plan := range planList {
  9284. if plan.Pid == planPid {
  9285. pidCount++
  9286. planList1 = append(planList1, plan)
  9287. } else {
  9288. planList2 = append(planList2, plan)
  9289. }
  9290. }
  9291. planList1 = append(planList1, planList2...)
  9292. for i, plan := range planList1 {
  9293. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  9294. if err != nil {
  9295. logs.Error(err)
  9296. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9297. tx.Rollback()
  9298. return
  9299. }
  9300. }
  9301. } else {
  9302. 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()
  9303. if err != nil {
  9304. logs.Error(err)
  9305. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9306. tx.Rollback()
  9307. return
  9308. }
  9309. var maxSort int
  9310. for _, sort := range maxSortList {
  9311. maxSort, _ = strconv.Atoi(sort["sort"])
  9312. }
  9313. planList := make([]*downloadedplan, 0)
  9314. 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)
  9315. if err != nil {
  9316. logs.Error(err)
  9317. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9318. tx.Rollback()
  9319. return
  9320. }
  9321. planPid := planInfo.Pid
  9322. planList1 := make([]*downloadedplan, 0)
  9323. planList2 := make([]*downloadedplan, 0)
  9324. for _, plan := range planList {
  9325. if plan.Pid == planPid {
  9326. // pidCount++
  9327. planList1 = append(planList1, plan)
  9328. } else {
  9329. planList2 = append(planList2, plan)
  9330. }
  9331. }
  9332. planList2 = append(planList2, planList1...)
  9333. for i, plan := range planList2 {
  9334. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  9335. if err != nil {
  9336. logs.Error(err)
  9337. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9338. tx.Rollback()
  9339. return
  9340. }
  9341. }
  9342. }
  9343. err = tx.Commit()
  9344. if err != nil {
  9345. logs.Error(err)
  9346. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9347. tx.Rollback()
  9348. return
  9349. }
  9350. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9351. }
  9352. func EditDownloadedplanArtificial(c *gin.Context) {
  9353. appG := app.Gin{C: c}
  9354. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9355. fsions := gofasion.NewFasion(string(dataByte))
  9356. planIdStr := fsions.Get("planId").ValueStr()
  9357. tx := restful.Engine.NewSession()
  9358. defer tx.Close()
  9359. tx.Begin()
  9360. planIdList := strings.Split(planIdStr, ",")
  9361. for _, planId := range planIdList {
  9362. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? `, planId)
  9363. if err != nil {
  9364. logs.Error(err)
  9365. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9366. tx.Rollback()
  9367. return
  9368. }
  9369. }
  9370. err := tx.Commit()
  9371. if err != nil {
  9372. logs.Error(err)
  9373. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9374. tx.Rollback()
  9375. return
  9376. }
  9377. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9378. }
  9379. type PlanRFID struct {
  9380. RFID string `json:"RFID"`
  9381. Lweight string `json:"lweight"`
  9382. Gear string `json:"gear"`
  9383. Speed string `json:"speed"`
  9384. }
  9385. func GetPlanRFID(c *gin.Context) {
  9386. appG := app.Gin{C: c}
  9387. RFIDStr := c.Query("RFID")
  9388. planRFIDList := make([]*PlanRFID, 0)
  9389. planRFIDList = append(planRFIDList, &PlanRFID{
  9390. RFID: RFIDStr,
  9391. Lweight: "1411.1",
  9392. Gear: "1",
  9393. Speed: "10",
  9394. })
  9395. planRFIDList = append(planRFIDList, &PlanRFID{
  9396. RFID: RFIDStr,
  9397. Lweight: "1322.1",
  9398. Gear: "1",
  9399. Speed: "10",
  9400. })
  9401. planRFIDList = append(planRFIDList, &PlanRFID{
  9402. RFID: RFIDStr,
  9403. Lweight: "1904.1",
  9404. Gear: "1",
  9405. Speed: "10",
  9406. })
  9407. planRFIDList = append(planRFIDList, &PlanRFID{
  9408. RFID: RFIDStr,
  9409. Lweight: "1870.1",
  9410. Gear: "1",
  9411. Speed: "10",
  9412. })
  9413. planRFIDList = append(planRFIDList, &PlanRFID{
  9414. RFID: RFIDStr,
  9415. Lweight: "2041.1",
  9416. Gear: "1",
  9417. Speed: "10",
  9418. })
  9419. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  9420. }
  9421. type tmrEquipmentMuster struct {
  9422. A string
  9423. N string
  9424. }
  9425. func GetTmrEquipmentMuster(c *gin.Context) {
  9426. appG := app.Gin{C: c}
  9427. id := c.Query("id")
  9428. tx := restful.Engine.NewSession()
  9429. defer tx.Close()
  9430. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  9431. if err != nil {
  9432. logs.Error(err)
  9433. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9434. return
  9435. }
  9436. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  9437. for _, data := range dataList {
  9438. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  9439. for _, g := range tmrEquipmentMusterList {
  9440. a, _ := strconv.ParseFloat(g.A, 64)
  9441. n, _ := strconv.ParseFloat(g.N, 64)
  9442. a1, n1 := ddmmtoddd(a, n)
  9443. g.A = fmt.Sprintf("%f", n1)
  9444. g.N = fmt.Sprintf("%f", a1)
  9445. }
  9446. }
  9447. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  9448. }
  9449. func ddmmtoddd(lng, lat float64) (float64, float64) {
  9450. lngDegree := fmt.Sprintf("%f", lng/100)
  9451. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  9452. lngDegreeInt := int(lngDegreefloat * 1000000)
  9453. dd := lngDegreeInt / 100 * 100 / 60
  9454. fmt.Println(dd)
  9455. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  9456. latDegree := fmt.Sprintf("%f", lat/100)
  9457. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  9458. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  9459. latDegreeInt := int(latDegreefloat * 1000000)
  9460. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  9461. a, _ := strconv.ParseFloat(lngStr, 64)
  9462. b, _ := strconv.ParseFloat(latStr, 64)
  9463. return coordtransform.WGS84toGCJ02(b, a)
  9464. }
  9465. func EditDownloadedplanExecWeight(c *gin.Context) {
  9466. appG := app.Gin{C: c}
  9467. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9468. fsions := gofasion.NewFasion(string(dataByte))
  9469. pid := fsions.Get("pid").ValueStr()
  9470. sort := fsions.Get("sort").ValueStr()
  9471. weight := fsions.Get("weight").ValueStr()
  9472. userId := fsions.Get("userId").ValueStr()
  9473. tx := restful.Engine.NewSession()
  9474. defer tx.Close()
  9475. tx.Begin()
  9476. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  9477. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  9478. pid, sort, pid, sort, weight, userId)
  9479. if err != nil {
  9480. logs.Error(err)
  9481. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9482. tx.Rollback()
  9483. return
  9484. }
  9485. _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9486. if err != nil {
  9487. logs.Error(err)
  9488. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9489. tx.Rollback()
  9490. return
  9491. }
  9492. _, 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)
  9493. if err != nil {
  9494. logs.Error(err)
  9495. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9496. tx.Rollback()
  9497. return
  9498. }
  9499. err = tx.Commit()
  9500. if err != nil {
  9501. logs.Error(err)
  9502. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9503. tx.Rollback()
  9504. return
  9505. }
  9506. appG.Response(http.StatusOK, e.SUCCESS, true)
  9507. }
  9508. func EditDownloadplandtl2Weight(c *gin.Context) {
  9509. appG := app.Gin{C: c}
  9510. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9511. fsions := gofasion.NewFasion(string(dataByte))
  9512. pid := fsions.Get("pid").ValueStr()
  9513. sort := fsions.Get("sort").ValueStr()
  9514. weight := fsions.Get("weight").ValueStr()
  9515. userId := fsions.Get("userId").ValueStr()
  9516. tx := restful.Engine.NewSession()
  9517. defer tx.Close()
  9518. tx.Begin()
  9519. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9520. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9521. pid, sort, pid, sort, weight, userId)
  9522. if err != nil {
  9523. logs.Error(err)
  9524. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9525. tx.Rollback()
  9526. return
  9527. }
  9528. _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9529. if err != nil {
  9530. logs.Error(err)
  9531. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9532. tx.Rollback()
  9533. return
  9534. }
  9535. err = tx.Commit()
  9536. if err != nil {
  9537. logs.Error(err)
  9538. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9539. tx.Rollback()
  9540. return
  9541. }
  9542. appG.Response(http.StatusOK, e.SUCCESS, true)
  9543. }
  9544. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9545. params := fasion.Get("parammaps")
  9546. surplus := params.Get("surplus").ValueStr()
  9547. surplusId := params.Get("surplusId").ValueStr()
  9548. tx := restful.Engine.NewSession()
  9549. defer tx.Close()
  9550. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9551. if surplusId != "0" {
  9552. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9553. if err != nil {
  9554. log.Println("PostDataByName-error-1: ", err)
  9555. return errors.New("配方修改失败!")
  9556. }
  9557. type ftdetail struct {
  9558. Id string
  9559. Fname string
  9560. Sort int64
  9561. }
  9562. ftList := make([]*ftdetail, 0)
  9563. for _, data := range dataList {
  9564. ft := new(ftdetail)
  9565. ft.Fname = data["fname"]
  9566. ft.Id = data["id"]
  9567. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9568. if err != nil {
  9569. log.Println("PostDataByName-error-2: ", err)
  9570. return err
  9571. }
  9572. ft.Sort = sort
  9573. ftList = append(ftList, ft)
  9574. }
  9575. if surplus == "日粮" {
  9576. for _, ft := range ftList {
  9577. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9578. }
  9579. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9580. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9581. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9582. fmt.Println(err)
  9583. } else {
  9584. var sort int64
  9585. for _, ft := range ftList {
  9586. if ft.Fname == surplus {
  9587. sort = ft.Sort
  9588. break
  9589. }
  9590. }
  9591. if sort == 0 {
  9592. for _, ft := range ftList {
  9593. ft.Sort = ft.Sort + 1
  9594. }
  9595. } else {
  9596. for _, ft := range ftList {
  9597. if ft.Sort >= sort {
  9598. ft.Sort = ft.Sort + 1
  9599. }
  9600. }
  9601. }
  9602. for _, ft := range ftList {
  9603. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9604. }
  9605. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9606. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9607. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9608. if err != nil {
  9609. log.Println("PostDataByName-error-1: ", err)
  9610. fmt.Println(err)
  9611. return errors.New("配方修改失败!")
  9612. }
  9613. }
  9614. }
  9615. return nil
  9616. }
  9617. func FeedSurplus(fasion *gofasion.Fasion) {
  9618. tx := restful.Engine.NewSession()
  9619. defer tx.Close()
  9620. params := fasion.Get("parammaps")
  9621. feedId := params.Get("id").ValueStr()
  9622. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9623. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9624. }
  9625. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9626. // params := fasion.Get("parammaps")
  9627. // surplus := params.Get("surplus").ValueStr()
  9628. // surplusId := params.Get("surplusId").ValueStr()
  9629. tx := restful.Engine.NewSession()
  9630. defer tx.Close()
  9631. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9632. if surplusId != "0" {
  9633. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9634. if err != nil {
  9635. log.Println("PostDataByName-error-1: ", err)
  9636. return errors.New("配方修改失败!")
  9637. }
  9638. type ftdetail struct {
  9639. Id string
  9640. Fname string
  9641. Sort int64
  9642. }
  9643. ftList := make([]*ftdetail, 0)
  9644. for _, data := range dataList {
  9645. ft := new(ftdetail)
  9646. ft.Fname = data["fname"]
  9647. ft.Id = data["id"]
  9648. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9649. if err != nil {
  9650. log.Println("PostDataByName-error-2: ", err)
  9651. return err
  9652. }
  9653. ft.Sort = sort
  9654. ftList = append(ftList, ft)
  9655. }
  9656. if surplus == "日粮" {
  9657. for _, ft := range ftList {
  9658. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9659. }
  9660. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9661. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9662. pastureId, id, surplusId, surplusId, surplusId)
  9663. fmt.Println(err)
  9664. } else {
  9665. var sort int64
  9666. for _, ft := range ftList {
  9667. if ft.Fname == surplus {
  9668. sort = ft.Sort
  9669. break
  9670. }
  9671. }
  9672. if sort == 0 {
  9673. for _, ft := range ftList {
  9674. ft.Sort = ft.Sort + 1
  9675. }
  9676. } else {
  9677. for _, ft := range ftList {
  9678. if ft.Sort >= sort {
  9679. ft.Sort = ft.Sort + 1
  9680. }
  9681. }
  9682. }
  9683. for _, ft := range ftList {
  9684. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9685. }
  9686. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9687. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9688. id, surplusId, surplusId, sort, surplusId, pastureId)
  9689. if err != nil {
  9690. log.Println("PostDataByName-error-1: ", err)
  9691. fmt.Println(err)
  9692. return errors.New("配方修改失败!")
  9693. }
  9694. }
  9695. }
  9696. return nil
  9697. }
  9698. func GetLanguageStatus() string {
  9699. tx := restful.Engine.NewSession()
  9700. defer tx.Close()
  9701. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9702. if err != nil {
  9703. log.Println(err)
  9704. return "0"
  9705. }
  9706. return dataList[0]["inforvalue"]
  9707. }
  9708. func EditLanguage(c *gin.Context) {
  9709. appG := app.Gin{C: c}
  9710. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9711. fsions := gofasion.NewFasion(string(dataByte))
  9712. language := fsions.Get("language").ValueStr()
  9713. tx := restful.Engine.NewSession()
  9714. defer tx.Close()
  9715. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9716. if err != nil {
  9717. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9718. return
  9719. }
  9720. if language == "0" {
  9721. _, err := tx.Exec(`delete from dictlist `)
  9722. if err != nil {
  9723. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9724. return
  9725. }
  9726. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9727. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9728. if err != nil {
  9729. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9730. return
  9731. }
  9732. } else {
  9733. _, err := tx.Exec(`delete from dictlist `)
  9734. if err != nil {
  9735. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9736. return
  9737. }
  9738. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9739. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9740. if err != nil {
  9741. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9742. return
  9743. }
  9744. }
  9745. appG.Response(http.StatusOK, e.SUCCESS, true)
  9746. }
  9747. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9748. tx := restful.Engine.NewSession()
  9749. defer tx.Close()
  9750. 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
  9751. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9752. if err != nil {
  9753. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9754. return
  9755. }
  9756. for _, dataexcel := range barList {
  9757. // dataexcel := make(map[string]interface{}, 0)
  9758. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9759. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9760. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9761. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9762. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9763. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9764. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9765. // if err != nil {
  9766. // logs.Error(err)
  9767. // return
  9768. // }
  9769. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9770. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9771. // if err != nil {
  9772. // logs.Error(err)
  9773. // return
  9774. // }
  9775. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9776. continue
  9777. }
  9778. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9779. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9780. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9781. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9782. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9783. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9784. /*
  9785. tx.SQL(` update lpplandtl1 set lweight = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9786. if err != nil {
  9787. logs.Error(err)
  9788. return
  9789. }
  9790. tx.SQL(` update fpdetail set ptuse = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9791. if err != nil {
  9792. logs.Error(err)
  9793. return
  9794. }
  9795. */
  9796. exist, err := tx.SQL(` select id from feedp where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9797. if err != nil {
  9798. logs.Error(err)
  9799. return
  9800. }
  9801. if !exist {
  9802. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9803. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9804. if err != nil {
  9805. logs.Error(err)
  9806. return
  9807. }
  9808. }
  9809. var feedpargs []interface{}
  9810. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9811. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9812. if _, ok := dataexcel["ftname"]; ok {
  9813. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9814. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9815. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9816. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9817. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9818. } else {
  9819. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9820. }
  9821. if _, ok := dataexcel["ptsfname"]; ok {
  9822. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9823. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9824. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9825. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9826. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9827. } else {
  9828. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9829. }
  9830. upFeedpSql += " where barname = ? and pastureid = ? "
  9831. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9832. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9833. if err != nil {
  9834. logs.Error(err)
  9835. return
  9836. }
  9837. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9838. if err != nil {
  9839. logs.Error(err)
  9840. return
  9841. }
  9842. if !exist1 {
  9843. _, 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) `,
  9844. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9845. if err != nil {
  9846. logs.Error(err)
  9847. return
  9848. }
  9849. }
  9850. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9851. if err != nil {
  9852. logs.Error(err)
  9853. return
  9854. }
  9855. if !exist2 {
  9856. _, 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) `,
  9857. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9858. if err != nil {
  9859. logs.Error(err)
  9860. return
  9861. }
  9862. }
  9863. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9864. if err != nil {
  9865. logs.Error(err)
  9866. return
  9867. }
  9868. if !exist3 {
  9869. _, 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) `,
  9870. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9871. if err != nil {
  9872. logs.Error(err)
  9873. return
  9874. }
  9875. }
  9876. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9877. if err != nil {
  9878. logs.Error(err)
  9879. return
  9880. }
  9881. if !exist4 {
  9882. _, 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) `,
  9883. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9884. if err != nil {
  9885. logs.Error(err)
  9886. return
  9887. }
  9888. }
  9889. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9890. if err != nil {
  9891. logs.Error(err)
  9892. return
  9893. }
  9894. if !exist5 {
  9895. _, 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) `,
  9896. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9897. if err != nil {
  9898. logs.Error(err)
  9899. return
  9900. }
  9901. }
  9902. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9903. if err != nil {
  9904. logs.Error(err)
  9905. return
  9906. }
  9907. if !exist6 {
  9908. _, 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) `,
  9909. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9910. if err != nil {
  9911. logs.Error(err)
  9912. return
  9913. }
  9914. }
  9915. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9916. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9917. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9918. and pastureid = ? and times = ?`
  9919. var fpdargs1 []interface{}
  9920. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9921. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9922. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9923. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9924. if err != nil {
  9925. fmt.Println(err)
  9926. return
  9927. }
  9928. var fpdargs2 []interface{}
  9929. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9930. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9931. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9932. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9933. if err != nil {
  9934. fmt.Println(err)
  9935. return
  9936. }
  9937. var fpdargs3 []interface{}
  9938. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9939. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9940. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9941. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9942. if err != nil {
  9943. fmt.Println(err)
  9944. return
  9945. }
  9946. var fpdargs4 []interface{}
  9947. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9948. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9949. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9950. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9951. if err != nil {
  9952. fmt.Println(err)
  9953. return
  9954. }
  9955. var fpdargs5 []interface{}
  9956. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9957. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9958. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9959. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9960. if err != nil {
  9961. fmt.Println(err)
  9962. return
  9963. }
  9964. var fpdargs6 []interface{}
  9965. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  9966. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9967. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  9968. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  9969. if err != nil {
  9970. fmt.Println(err)
  9971. return
  9972. }
  9973. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  9974. 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()
  9975. if err != nil {
  9976. return
  9977. }
  9978. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9979. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9980. upFpdetailList := make([]*upFpdetail, 0)
  9981. for _, newfpd := range newList {
  9982. for _, oldfpd := range oldFpdList {
  9983. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  9984. var oldweight, newweight float64
  9985. if oldfpd["weight"] != nil {
  9986. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  9987. }
  9988. if newfpd["weight"] != nil {
  9989. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  9990. }
  9991. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  9992. upFpdetailList = append(upFpdetailList, &upFpdetail{
  9993. Old: oldweight,
  9994. New: newweight,
  9995. Times: newfpd["times"].(int64),
  9996. Ptid: newfpd["ptid"].(int64),
  9997. Fweight: fweight,
  9998. Id: oldfpd["id"].(int64),
  9999. })
  10000. break
  10001. }
  10002. }
  10003. }
  10004. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  10005. }
  10006. }
  10007. func AddXxwFtdetail(c *gin.Context) {
  10008. appG := app.Gin{C: c}
  10009. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  10010. c.Bind(&xxwFtdetailList)
  10011. tx := restful.Engine.NewSession()
  10012. defer tx.Close()
  10013. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  10014. if err != nil {
  10015. logs.Error(err)
  10016. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10017. }
  10018. _, err = tx.Insert(xxwFtdetailList)
  10019. if err != nil {
  10020. logs.Error(err)
  10021. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10022. }
  10023. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  10024. appG.Response(http.StatusOK, e.SUCCESS, true)
  10025. }
  10026. func AddXxwFeedtemplet(c *gin.Context) {
  10027. appG := app.Gin{C: c}
  10028. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  10029. c.Bind(&xxwFeedtempletList)
  10030. tx := restful.Engine.NewSession()
  10031. defer tx.Close()
  10032. pastureinfo := new(udPastureInfo)
  10033. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  10034. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  10035. if err != nil {
  10036. logs.Error(err)
  10037. return
  10038. }
  10039. for _, ft := range xxwFeedtempletList {
  10040. ids, err := setting.SnowIds.NextId()
  10041. if err != nil {
  10042. ids = time.Now().UnixNano()
  10043. logging.Info("create SnowIds err", err)
  10044. }
  10045. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  10046. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  10047. ft.RecipeobjName, ft.RecipeobjName)
  10048. if err != nil {
  10049. logs.Error(err)
  10050. return
  10051. }
  10052. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  10053. _, 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')),
  10054. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  10055. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  10056. if err != nil {
  10057. logs.Error(err)
  10058. return
  10059. }
  10060. }
  10061. appG.Response(http.StatusOK, e.SUCCESS, true)
  10062. }
  10063. func ProcessExcel(c *gin.Context) {
  10064. appG := app.Gin{C: c}
  10065. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10066. fasion := gofasion.NewFasion(string(dataByte))
  10067. params := fasion.Get("parammaps")
  10068. pastureid := params.Get("pastureid").ValueStr()
  10069. startTime := params.Get("startTime").ValueStr()
  10070. stopTime := params.Get("stopTime").ValueStr()
  10071. iscompleted := params.Get("iscompleted").ValueStr()
  10072. lpplantype := params.Get("lpplantype").ValueStr()
  10073. error := params.Get("error").ValueStr()
  10074. hlwc1 := params.Get("hlwc1").ValueStr()
  10075. hlwc2 := params.Get("hlwc2").ValueStr()
  10076. slwc1 := params.Get("slwc1").ValueStr()
  10077. slwc2 := params.Get("slwc2").ValueStr()
  10078. hlzq1 := params.Get("hlzq1").ValueStr()
  10079. hlzq2 := params.Get("hlzq2").ValueStr()
  10080. slzq1 := params.Get("slzq1").ValueStr()
  10081. slzq2 := params.Get("slzq2").ValueStr()
  10082. fclassid := params.Get("fclassid").ValueStr()
  10083. minproesstime := params.Get("minproesstime").ValueStr()
  10084. maxproesstime := params.Get("maxproesstime").ValueStr()
  10085. tx := restful.Engine.NewSession()
  10086. defer tx.Close()
  10087. planList, err := tx.SQL(`SELECT
  10088. 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
  10089. FROM downloadedplan d
  10090. join pasture p on p.pastureid = d.pastureid
  10091. WHERE d.pastureid= ? and d.intime IS NOT NULL
  10092. AND mydate >= ? AND mydate <= ?
  10093. AND (iscompleted=? or ?='')
  10094. AND (lpplantype = ? or ? = '')
  10095. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  10096. 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
  10097. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  10098. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10099. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  10100. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10101. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  10102. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10103. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  10104. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10105. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  10106. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  10107. 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,
  10108. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  10109. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  10110. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  10111. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10112. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  10113. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  10114. or (?= '' and ? = '' ))
  10115. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  10116. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  10117. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  10118. maxproesstime, minproesstime, maxproesstime).QueryString()
  10119. if err != nil {
  10120. logs.Error(err)
  10121. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10122. return
  10123. }
  10124. planExecList, err := tx.SQL(`SELECT
  10125. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10126. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10127. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  10128. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10129. ) proesstime,
  10130. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10131. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  10132. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10133. sumproesstime, d1.pid,
  10134. d1.sort,
  10135. d1.fname,
  10136. d1.lweight,
  10137. d1.actualweightminus,
  10138. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  10139. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  10140. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  10141. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  10142. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  10143. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  10144. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  10145. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10146. d1.begintime stoptime,
  10147. d1.lastactualweight,
  10148. d1.actualweight,
  10149. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  10150. case d1.buttontype
  10151. when 1 then '自动'
  10152. when 2 then '手动'
  10153. when 3 then '手动'
  10154. end,
  10155. case d1.buttontype
  10156. when 1 then 'Automatic'
  10157. when 2 then 'Manual'
  10158. when 3 then 'Manual'
  10159. end
  10160. ) buttontype
  10161. FROM
  10162. downloadplandtl1_exec d1
  10163. WHERE d1.date between ? and ?
  10164. ORDER BY sort
  10165. `, startTime, stopTime).QueryString()
  10166. if err != nil {
  10167. logs.Error(err)
  10168. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10169. return
  10170. }
  10171. planExec2, err := tx.SQL(`SELECT
  10172. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  10173. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10174. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10175. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  10176. ) proesstime,
  10177. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  10178. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10179. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  10180. d1.sort,
  10181. d1.fname,
  10182. d1.lweight,
  10183. d1.actualweightminus,
  10184. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  10185. ABS(d1.lweight- d1.actualweightminus) diff,
  10186. 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,
  10187. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10188. d1.begintime stoptime,
  10189. d1.lastactualweight,
  10190. d1.actualweight,d1.pid
  10191. FROM
  10192. downloadplandtl2 d1
  10193. WHERE d1.date between ? and ?
  10194. ORDER BY sort`, startTime, stopTime).QueryString()
  10195. if err != nil {
  10196. logs.Error(err)
  10197. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10198. return
  10199. }
  10200. // 创建一个新的 Excel 文件
  10201. f := excelizexuri.NewFile()
  10202. // 创建工作表名称
  10203. sheetName := "Sheet1"
  10204. // border := []excelizexuri.Border{
  10205. // {Type: "left", Color: "000000", Style: 1},
  10206. // {Type: "right", Color: "000000", Style: 1},
  10207. // {Type: "top", Color: "000000", Style: 1},
  10208. // {Type: "bottom", Color: "000000", Style: 1},
  10209. // }
  10210. // 创建新的样式
  10211. style := &excelizexuri.Style{
  10212. // Border: border,
  10213. Alignment: &excelizexuri.Alignment{
  10214. Vertical: "center",
  10215. Horizontal: "center",
  10216. ShrinkToFit: true,
  10217. WrapText: true,
  10218. },
  10219. }
  10220. styleTitle := &excelizexuri.Style{
  10221. Fill: excelizexuri.Fill{
  10222. Color: []string{"FFFF0000"}, // 尝试使用完整的ARGB格式
  10223. },
  10224. // Border: border,
  10225. Font: &excelizexuri.Font{
  10226. Bold: true, // 加粗
  10227. Size: 24, // 字体大小
  10228. // Name: "宋体", // 字体名称
  10229. // WrapText :true,
  10230. Color: "000000", // 字体颜色(黑色)
  10231. },
  10232. Alignment: &excelizexuri.Alignment{
  10233. Vertical: "center", // 垂直居中
  10234. Horizontal: "center", // 水平居中
  10235. ShrinkToFit: true,
  10236. WrapText: true,
  10237. },
  10238. }
  10239. // 创建样式 ID
  10240. styleTitleId, err := f.NewStyle(styleTitle)
  10241. if err != nil {
  10242. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10243. return
  10244. }
  10245. // 创建样式 ID
  10246. styleID, err := f.NewStyle(style)
  10247. if err != nil {
  10248. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10249. return
  10250. }
  10251. // 合并单元格并设置内容
  10252. f.MergeCell(sheetName, "A1", "K1")
  10253. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  10254. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  10255. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  10256. planExecMap := make(map[string][]map[string]string, 0)
  10257. for _, planExec := range planExecList {
  10258. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  10259. }
  10260. plan2Map := make(map[string][]map[string]string, 0)
  10261. for _, plan2 := range planExec2 {
  10262. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  10263. }
  10264. num := 2
  10265. var notBorder []int
  10266. for _, plan := range planList {
  10267. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  10268. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10269. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10270. for i, header := range headers {
  10271. // 从 A2 开始
  10272. if header == "开始日期" {
  10273. cell := "%" + fmt.Sprintf("c%d", num)
  10274. cell = fmt.Sprintf(cell, 'A'+i+1)
  10275. f.SetCellValue(sheetName, cell, header)
  10276. f.SetCellStyle(sheetName, cell, cell, styleID)
  10277. continue
  10278. }
  10279. cell := "%" + fmt.Sprintf("c%d", num)
  10280. cell = fmt.Sprintf(cell, 'A'+i)
  10281. f.SetCellValue(sheetName, cell, header)
  10282. f.SetCellStyle(sheetName, cell, cell, styleID)
  10283. }
  10284. num += 1
  10285. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  10286. cell := "%" + fmt.Sprintf("c%d", num)
  10287. cell = fmt.Sprintf(cell, 'A'+0)
  10288. f.SetCellValue(sheetName, cell, plan["pastureName"])
  10289. f.SetCellStyle(sheetName, cell, cell, styleID)
  10290. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  10291. cell = "%" + fmt.Sprintf("c%d", num)
  10292. cell = fmt.Sprintf(cell, 'A'+1)
  10293. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  10294. f.SetCellStyle(sheetName, cell, cell, styleID)
  10295. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  10296. cell = "%" + fmt.Sprintf("c%d", num)
  10297. cell = fmt.Sprintf(cell, 'A'+2)
  10298. f.SetCellValue(sheetName, cell, plan["projname"])
  10299. f.SetCellStyle(sheetName, cell, cell, styleID)
  10300. cell = "%" + fmt.Sprintf("c%d", num)
  10301. cell = fmt.Sprintf(cell, 'A'+3)
  10302. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10303. f.SetCellValue(sheetName, cell, plan["mydate"])
  10304. f.SetCellStyle(sheetName, cell, cell, styleID)
  10305. cell = "%" + fmt.Sprintf("c%d", num)
  10306. cell = fmt.Sprintf(cell, 'A'+6)
  10307. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10308. f.SetCellValue(sheetName, cell, plan["intime"])
  10309. f.SetCellStyle(sheetName, cell, cell, styleID)
  10310. num += 1
  10311. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10312. for i, header := range headers1 {
  10313. cell = "%" + fmt.Sprintf("c%d", num)
  10314. cell = fmt.Sprintf(cell, 'C'+i)
  10315. f.SetCellValue(sheetName, cell, header)
  10316. f.SetCellStyle(sheetName, cell, cell, styleID)
  10317. // maxWidth := len(header)
  10318. // colName := string('C' + i)
  10319. // f.SetColWidth(sheetName, colName, colName, 20)
  10320. f.SetColWidth(sheetName, header, header, 40)
  10321. }
  10322. num += 1
  10323. // 在循环外部创建红色样式(只创建一次)
  10324. redStyle := &excelizexuri.Style{
  10325. Fill: excelizexuri.Fill{
  10326. Type: "pattern",
  10327. Color: []string{"FF0000"},
  10328. Pattern: 1,
  10329. },
  10330. // Font: &excelizexuri.Font{
  10331. // Bold: true, // 加粗
  10332. // Size: 24, // 字体大小
  10333. // // Name: "宋体", // 字体名称
  10334. // // WrapText :true,
  10335. // Color: "FFFF0000", // 字体颜色(黑色)
  10336. // },
  10337. Alignment: &excelizexuri.Alignment{
  10338. Vertical: "center",
  10339. Horizontal: "center",
  10340. ShrinkToFit: true,
  10341. WrapText: true,
  10342. },
  10343. }
  10344. redStyleID, err := f.NewStyle(redStyle)
  10345. if err != nil {
  10346. c.String(http.StatusInternalServerError, "Failed to create red style: "+err.Error())
  10347. return
  10348. }
  10349. // 在循环内部正确使用条件判断
  10350. for _, planExec := range planExecMap[plan["id"]] {
  10351. var currentStyleID int
  10352. if planExec["abnormal"] == "1" {
  10353. currentStyleID = redStyleID
  10354. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, planExec["abnormal"]) // 调试
  10355. } else {
  10356. currentStyleID = styleID
  10357. }
  10358. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10359. sort, _ := strconv.Atoi(planExec["sort"])
  10360. f.SetCellValue(sheetName, cell, sort)
  10361. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10362. cell = fmt.Sprintf("D%d", num)
  10363. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  10364. f.SetCellValue(sheetName, cell, lweight)
  10365. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10366. cell = fmt.Sprintf("E%d", num)
  10367. if _, ok := planExec["actualweightminus"]; ok {
  10368. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  10369. f.SetCellValue(sheetName, cell, actualweightminus)
  10370. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10371. } else {
  10372. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  10373. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10374. }
  10375. cell = fmt.Sprintf("F%d", num)
  10376. f.SetCellValue(sheetName, cell, planExec["fname"])
  10377. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10378. cell = fmt.Sprintf("G%d", num)
  10379. if _, ok := planExec["diff"]; ok {
  10380. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  10381. f.SetCellValue(sheetName, cell, diff)
  10382. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10383. } else {
  10384. f.SetCellValue(sheetName, cell, planExec["diff"])
  10385. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10386. }
  10387. cell = fmt.Sprintf("H%d", num)
  10388. if _, ok := planExec["diffRate"]; ok {
  10389. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  10390. f.SetCellValue(sheetName, cell, diffRate)
  10391. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10392. } else {
  10393. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  10394. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10395. }
  10396. cell = fmt.Sprintf("I%d", num)
  10397. f.SetCellValue(sheetName, cell, planExec["intime"])
  10398. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10399. cell = fmt.Sprintf("J%d", num)
  10400. if _, ok := planExec["lastactualweight"]; ok {
  10401. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  10402. f.SetCellValue(sheetName, cell, lastactualweight)
  10403. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10404. } else {
  10405. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  10406. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10407. }
  10408. cell = fmt.Sprintf("K%d", num)
  10409. if _, ok := planExec["actualweight"]; ok {
  10410. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  10411. f.SetCellValue(sheetName, cell, actualweight)
  10412. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10413. } else {
  10414. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  10415. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10416. }
  10417. num += 1
  10418. }
  10419. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10420. for i, header := range headers2 {
  10421. cell := "%" + fmt.Sprintf("c%d", num)
  10422. cell = fmt.Sprintf(cell, 'C'+i)
  10423. f.SetCellValue(sheetName, cell, header)
  10424. f.SetCellStyle(sheetName, cell, cell, styleID)
  10425. maxWidth := len(header)
  10426. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  10427. }
  10428. num += 1
  10429. for _, plan2 := range plan2Map[plan["id"]] {
  10430. var currentStyleID int
  10431. if plan2["abnormal"] == "1" {
  10432. currentStyleID = redStyleID
  10433. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, plan2["abnormal"]) // 调试
  10434. } else {
  10435. currentStyleID = styleID
  10436. }
  10437. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10438. sort, _ := strconv.Atoi(plan2["sort"])
  10439. f.SetCellValue(sheetName, cell, sort)
  10440. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10441. cell = fmt.Sprintf("D%d", num)
  10442. f.SetCellValue(sheetName, cell, plan2["fname"])
  10443. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10444. cell = fmt.Sprintf("E%d", num)
  10445. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  10446. f.SetCellValue(sheetName, cell, lweight)
  10447. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10448. cell = fmt.Sprintf("F%d", num)
  10449. if _, ok := plan2["actualweightminus"]; ok {
  10450. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  10451. f.SetCellValue(sheetName, cell, actualweightminus)
  10452. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10453. } else {
  10454. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  10455. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10456. }
  10457. cell = fmt.Sprintf("G%d", num)
  10458. if _, ok := plan2["diff"]; ok {
  10459. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  10460. f.SetCellValue(sheetName, cell, diff)
  10461. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10462. } else {
  10463. f.SetCellValue(sheetName, cell, plan2["diff"])
  10464. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10465. }
  10466. cell = fmt.Sprintf("H%d", num)
  10467. if _, ok := plan2["diffRate"]; ok {
  10468. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  10469. f.SetCellValue(sheetName, cell, diffRate)
  10470. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10471. } else {
  10472. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  10473. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10474. }
  10475. cell = fmt.Sprintf("I%d", num)
  10476. f.SetCellValue(sheetName, cell, plan2["intime"])
  10477. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10478. cell = fmt.Sprintf("J%d", num)
  10479. if _, ok := plan2["lastactualweight"]; ok {
  10480. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  10481. f.SetCellValue(sheetName, cell, lastactualweight)
  10482. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10483. } else {
  10484. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  10485. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10486. }
  10487. cell = fmt.Sprintf("K%d", num)
  10488. if _, ok := plan2["lastactualweight"]; ok {
  10489. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  10490. f.SetCellValue(sheetName, cell, actualweight)
  10491. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10492. } else {
  10493. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  10494. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10495. }
  10496. num += 1
  10497. }
  10498. num += 1
  10499. notBorder = append(notBorder, num)
  10500. }
  10501. // for i := 2; i < num; i++ {
  10502. // exist := false
  10503. // for _, n := range notBorder {
  10504. // if i+1 == n {
  10505. // exist = true
  10506. // break
  10507. // }
  10508. // }
  10509. // if !exist {
  10510. // // 为 A-K 列设置边框
  10511. // for col := 'A'; col <= 'K'; col++ {
  10512. // cellName := fmt.Sprintf("%c%d", col, i)
  10513. // style, _ := f.NewStyle(&excelizexuri.Style{
  10514. // // Border: border,
  10515. // Alignment: &excelizexuri.Alignment{
  10516. // Vertical: "center",
  10517. // Horizontal: "center",
  10518. // ShrinkToFit: true,
  10519. // WrapText: true,
  10520. // },
  10521. // })
  10522. // f.SetCellStyle(sheetName, cellName, cellName, style)
  10523. // }
  10524. // }
  10525. // }
  10526. for col := 'A'; col <= 'K'; col++ {
  10527. colName := string(col)
  10528. switch colName {
  10529. case "A", "B": // 牧场名称、TMR列
  10530. f.SetColWidth(sheetName, colName, colName, 10)
  10531. case "C": // 操作编号列
  10532. f.SetColWidth(sheetName, colName, colName, 10)
  10533. case "D", "E": // 计划重量、实际重量列
  10534. f.SetColWidth(sheetName, colName, colName, 12)
  10535. case "F": // 代表成分/投料位置列
  10536. f.SetColWidth(sheetName, colName, colName, 20)
  10537. case "G", "H": // 误差数、准确率列
  10538. f.SetColWidth(sheetName, colName, colName, 12)
  10539. case "I": // 完成时间列
  10540. f.SetColWidth(sheetName, colName, colName, 15)
  10541. case "J", "K": // 起始读数重量、完成读数重量列
  10542. f.SetColWidth(sheetName, colName, colName, 15)
  10543. }
  10544. }
  10545. // 设置响应头
  10546. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10547. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10548. c.Header("Content-Transfer-Encoding", "binary")
  10549. // 写入 Excel 文件到响应
  10550. if err := f.Write(c.Writer); err != nil {
  10551. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10552. return
  10553. }
  10554. }
  10555. func RestartMqtt(c *gin.Context) {
  10556. appG := app.Gin{C: c}
  10557. // 发送 GET 请求到 MQTT 重启接口
  10558. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10559. if err != nil {
  10560. logging.Error("RestartMqtt request failed:", err)
  10561. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10562. return
  10563. }
  10564. defer resp.Body.Close()
  10565. // 读取响应内容f
  10566. body, err := ioutil.ReadAll(resp.Body)
  10567. if err != nil {
  10568. logging.Error("RestartMqtt read response failed:", err)
  10569. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10570. return
  10571. }
  10572. // 检查响应状态码
  10573. if resp.StatusCode != http.StatusOK {
  10574. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10575. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10576. return
  10577. }
  10578. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10579. }
  10580. func FpdBatchEditByWeight(c *gin.Context) {
  10581. appG := app.Gin{C: c}
  10582. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10583. fsions := gofasion.NewFasion(string(dataByte))
  10584. barList := fsions.Get("barList").Array()
  10585. pastureid := fsions.Get("pastureId").ValueStr()
  10586. tx := restful.Engine.NewSession()
  10587. defer tx.Close()
  10588. 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
  10589. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10590. if err != nil {
  10591. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10592. return
  10593. }
  10594. for _, barFsions := range barList {
  10595. dataexcel := make(map[string]interface{}, 0)
  10596. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10597. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10598. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10599. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10600. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10601. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10602. continue
  10603. }
  10604. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10605. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10606. // if err != nil {
  10607. // logs.Error(err)
  10608. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10609. // return
  10610. // }
  10611. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10612. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10613. // if err != nil {
  10614. // logs.Error(err)
  10615. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10616. // return
  10617. // }
  10618. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10619. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10620. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10621. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10622. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10623. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10624. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10625. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10626. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10627. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10628. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10629. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10630. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10631. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10632. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10633. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10634. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10635. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10636. if err != nil {
  10637. logs.Error(err)
  10638. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10639. return
  10640. }
  10641. if !ftexist {
  10642. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10643. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10644. if err != nil {
  10645. logs.Error(err)
  10646. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10647. return
  10648. }
  10649. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10650. if err != nil {
  10651. logs.Error(err)
  10652. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10653. return
  10654. }
  10655. }
  10656. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10657. if err != nil {
  10658. logs.Error(err)
  10659. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10660. return
  10661. }
  10662. if !exist {
  10663. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10664. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10665. if err != nil {
  10666. logs.Error(err)
  10667. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10668. return
  10669. }
  10670. }
  10671. var feedpargs []interface{}
  10672. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10673. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10674. if _, ok := dataexcel["ftname"]; ok {
  10675. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10676. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10677. // upFeedpSql += `,ftweight = ? `
  10678. // feedpargs = append(feedpargs, weight)
  10679. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10680. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10681. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10682. } else {
  10683. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10684. }
  10685. // if _, ok := dataexcel["ptsfname"]; ok {
  10686. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10687. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10688. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10689. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10690. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10691. // } else {
  10692. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10693. // }
  10694. upFeedpSql += " where barname = ? and pastureid = ? "
  10695. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10696. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10697. if err != nil {
  10698. logs.Error(err)
  10699. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10700. return
  10701. }
  10702. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10703. if err != nil {
  10704. logs.Error(err)
  10705. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10706. return
  10707. }
  10708. if !exist1 {
  10709. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10710. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10711. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10712. if err != nil {
  10713. logs.Error(err)
  10714. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10715. return
  10716. }
  10717. }
  10718. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10719. if err != nil {
  10720. logs.Error(err)
  10721. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10722. return
  10723. }
  10724. if !exist2 {
  10725. _, 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) `,
  10726. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10727. if err != nil {
  10728. logs.Error(err)
  10729. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10730. return
  10731. }
  10732. }
  10733. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10734. if err != nil {
  10735. logs.Error(err)
  10736. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10737. return
  10738. }
  10739. if !exist3 {
  10740. _, 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) `,
  10741. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10742. if err != nil {
  10743. logs.Error(err)
  10744. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10745. return
  10746. }
  10747. }
  10748. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10749. if err != nil {
  10750. logs.Error(err)
  10751. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10752. return
  10753. }
  10754. if !exist4 {
  10755. _, 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) `,
  10756. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10757. if err != nil {
  10758. logs.Error(err)
  10759. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10760. return
  10761. }
  10762. }
  10763. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  10764. if err != nil {
  10765. logs.Error(err)
  10766. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10767. return
  10768. }
  10769. if !exist5 {
  10770. _, 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) `,
  10771. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10772. if err != nil {
  10773. logs.Error(err)
  10774. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10775. return
  10776. }
  10777. }
  10778. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  10779. if err != nil {
  10780. logs.Error(err)
  10781. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10782. return
  10783. }
  10784. if !exist6 {
  10785. _, 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) `,
  10786. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10787. if err != nil {
  10788. logs.Error(err)
  10789. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10790. return
  10791. }
  10792. }
  10793. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10794. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10795. and pastureid = ? and times = ?`
  10796. var fpdargs1 []interface{}
  10797. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10798. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10799. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10800. if err != nil {
  10801. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10802. return
  10803. }
  10804. var fpdargs2 []interface{}
  10805. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10806. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10807. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10808. if err != nil {
  10809. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10810. return
  10811. }
  10812. var fpdargs3 []interface{}
  10813. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10814. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10815. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10816. if err != nil {
  10817. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10818. return
  10819. }
  10820. var fpdargs4 []interface{}
  10821. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10822. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10823. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10824. if err != nil {
  10825. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10826. return
  10827. }
  10828. var fpdargs5 []interface{}
  10829. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10830. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10831. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10832. if err != nil {
  10833. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10834. return
  10835. }
  10836. var fpdargs6 []interface{}
  10837. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10838. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10839. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10840. if err != nil {
  10841. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10842. return
  10843. }
  10844. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10845. 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()
  10846. if err != nil {
  10847. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10848. return
  10849. }
  10850. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10851. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10852. upFpdetailList := make([]*upFpdetail, 0)
  10853. for _, newfpd := range newList {
  10854. for _, oldfpd := range oldFpdList {
  10855. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10856. var oldweight, newweight float64
  10857. if oldfpd["weight"] != nil {
  10858. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10859. }
  10860. if newfpd["weight"] != nil {
  10861. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10862. }
  10863. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10864. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10865. Old: oldweight,
  10866. New: newweight,
  10867. Times: newfpd["times"].(int64),
  10868. Ptid: newfpd["ptid"].(int64),
  10869. Fweight: fweight,
  10870. Id: oldfpd["id"].(int64),
  10871. })
  10872. break
  10873. }
  10874. }
  10875. }
  10876. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10877. }
  10878. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10879. }
  10880. func FtImportExcel(c *gin.Context) {
  10881. appG := app.Gin{C: c}
  10882. inputdata := ""
  10883. c.Request.ParseForm()
  10884. params := c.Request.Form
  10885. file, _, err := c.Request.FormFile("file")
  10886. if err != nil {
  10887. appG.Response(http.StatusOK, e.ERROR, err)
  10888. return
  10889. }
  10890. sqlnamestrs := params.Get("name")
  10891. sheetname := params.Get("sheetname")
  10892. pastureid := params.Get("pastureid")
  10893. //importParams := params.Get("importParams")
  10894. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10895. // 必输项参数 (字符串格式 "field1,field2,field3")
  10896. requiredParams := params.Get("requiredParams")
  10897. // 日期参数
  10898. dateParams := params.Get("dateParams")
  10899. // 数字参数
  10900. numParams := params.Get("numParams")
  10901. //将字符串分割开
  10902. dateParamslist := strings.Split(dateParams, ",")
  10903. requiredParamslist := strings.Split(requiredParams, ",")
  10904. numParamslist := strings.Split(numParams, ",")
  10905. queryData := make([]interface{}, 0)
  10906. sqlslist := strings.Split(sqlnamestrs, ",")
  10907. xlsx1, err := excelize.OpenReader(file)
  10908. if err != nil {
  10909. fmt.Println(err)
  10910. return
  10911. }
  10912. ok := 0
  10913. error := 0
  10914. isdone := true
  10915. rows := xlsx1.GetRows(sheetname)
  10916. // 限制10000条,多余的截取掉
  10917. if len(rows) > 10000 {
  10918. rows = rows[:10000]
  10919. }
  10920. tx := restful.Engine.NewSession()
  10921. ftNameList := make(map[string]interface{})
  10922. var ftNames []interface{}
  10923. for i, row := range rows {
  10924. if i > 0 {
  10925. entry := make(map[string]interface{})
  10926. outentry := make(map[string]interface{})
  10927. for j, colCell := range rows[0] {
  10928. for k, colCell1 := range row {
  10929. if j == k {
  10930. outentry[colCell] = colCell1
  10931. entry[colCell] = colCell1
  10932. }
  10933. }
  10934. }
  10935. inputdata = ""
  10936. a := ""
  10937. fmt.Println(outentry, entry)
  10938. //校验日期格式
  10939. for _, v := range dateParamslist {
  10940. if v == "" {
  10941. continue
  10942. }
  10943. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10944. dtime, err := TransfTime(d.(string))
  10945. if err != nil {
  10946. a = strings.Trim(v, " ")
  10947. break
  10948. }
  10949. outentry[strings.Trim(v, " ")] = dtime
  10950. }
  10951. }
  10952. if a != "" {
  10953. outentry["error_msg"] = a + " 格式错误"
  10954. error++
  10955. queryData = append(queryData, outentry)
  10956. continue
  10957. }
  10958. a = ""
  10959. //校验必填格式
  10960. for _, v := range requiredParamslist {
  10961. if v == "" {
  10962. continue
  10963. }
  10964. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  10965. a = strings.Trim(v, " ")
  10966. break
  10967. }
  10968. }
  10969. if a != "" {
  10970. outentry["error_msg"] = a + " 未填或格式错误"
  10971. error++
  10972. queryData = append(queryData, outentry)
  10973. continue
  10974. }
  10975. a = ""
  10976. //校验数字格式
  10977. for _, v := range numParamslist {
  10978. if v == "" {
  10979. continue
  10980. }
  10981. d, ok := outentry[strings.Trim(v, " ")]
  10982. if !ok || d == "" {
  10983. outentry[strings.Trim(v, " ")] = 0
  10984. } else {
  10985. var fl float64
  10986. switch d.(type) {
  10987. case string:
  10988. fl, err = strconv.ParseFloat(d.(string), 64)
  10989. }
  10990. if err != nil || fl < 0 {
  10991. a = strings.Trim(v, " ")
  10992. break
  10993. }
  10994. }
  10995. }
  10996. if a != "" {
  10997. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  10998. error++
  10999. queryData = append(queryData, outentry)
  11000. continue
  11001. }
  11002. err := tx.Begin()
  11003. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  11004. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  11005. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  11006. }
  11007. for _, sqlnamestr := range sqlslist {
  11008. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  11009. paramslist := strings.Split(paramslists, ",")
  11010. if len(paramslist) > 0 {
  11011. s_params := make([]interface{}, 0)
  11012. for _, value := range paramslist {
  11013. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  11014. if tempv, exists := c.Get("jwt_username"); exists {
  11015. s_params = append(s_params, tempv.(string))
  11016. } else {
  11017. s_params = append(s_params, "")
  11018. }
  11019. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  11020. s_params = append(s_params, pastureid)
  11021. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  11022. ids, err := setting.SnowIds.NextId()
  11023. if err != nil {
  11024. ids = time.Now().UnixNano()
  11025. logging.Info("create SnowIds err", err)
  11026. }
  11027. s_params = append(s_params, ids)
  11028. } else {
  11029. if outentry[strings.Trim(value, " ")] == nil {
  11030. s_params = append(s_params, "")
  11031. } else {
  11032. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  11033. }
  11034. }
  11035. }
  11036. outentry["input"] = inputdata
  11037. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  11038. if err != nil {
  11039. if tx != nil {
  11040. tx.Rollback()
  11041. }
  11042. if tx != nil {
  11043. tx.Close()
  11044. }
  11045. msg := geterrmsg(err.Error())
  11046. outentry["error_msg"] = msg
  11047. error++
  11048. queryData = append(queryData, outentry)
  11049. isdone = true
  11050. break
  11051. } else {
  11052. if len(returnmsgmap1) > 0 {
  11053. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  11054. if tx != nil {
  11055. tx.Rollback()
  11056. }
  11057. if tx != nil {
  11058. tx.Close()
  11059. }
  11060. msg := geterrmsg(va.(string))
  11061. outentry["error_msg"] = msg
  11062. error++
  11063. queryData = append(queryData, outentry)
  11064. isdone = true
  11065. break
  11066. }
  11067. }
  11068. isdone = false
  11069. }
  11070. }
  11071. }
  11072. ftNames = append(ftNames, outentry["配方名称"])
  11073. switch {
  11074. case err != nil:
  11075. if tx != nil {
  11076. tx.Rollback()
  11077. }
  11078. default:
  11079. if tx != nil {
  11080. err = tx.Commit()
  11081. }
  11082. }
  11083. if tx != nil {
  11084. tx.Close()
  11085. }
  11086. }
  11087. if !isdone {
  11088. ok++
  11089. isdone = true
  11090. }
  11091. }
  11092. go ftSync(ftNames, pastureid)
  11093. data := make(map[string]interface{})
  11094. data["result"] = queryData
  11095. data["success"] = ok
  11096. data["err_count"] = error
  11097. appG.Response(http.StatusOK, e.SUCCESS, data)
  11098. }
  11099. func ftSync(ftNameList []interface{}, pastureId string) {
  11100. tx := restful.Engine.NewSession()
  11101. defer tx.Close()
  11102. for _, ftName := range ftNameList {
  11103. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  11104. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  11105. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  11106. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  11107. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  11108. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  11109. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  11110. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  11111. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, ftName).QueryString()
  11112. FpdBatchEditGrfd(pastureId, values1)
  11113. }
  11114. }
  11115. func CopyFeedtemplet(c *gin.Context) {
  11116. appG := app.Gin{C: c}
  11117. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11118. fsion := gofasion.NewFasion(string(dataByte))
  11119. pastureid := fsion.Get("pastureid").ValueStr()
  11120. newName := fsion.Get("newName").ValueStr()
  11121. id := fsion.Get("id").ValueStr()
  11122. tx := restful.Engine.NewSession()
  11123. defer tx.Close()
  11124. count, err := tx.SQL(` select count(1) from feedtemplet where tname = ? `, newName).Count()
  11125. if err != nil {
  11126. appG.Response(http.StatusOK, e.ERROR, err)
  11127. return
  11128. }
  11129. if count > 0 {
  11130. appG.Response(http.StatusOK, e.ERROR, "配方名称重复!")
  11131. return
  11132. }
  11133. type ftCode struct {
  11134. Tcode string `xorm:"tcode"`
  11135. }
  11136. code := new(ftCode)
  11137. err = tx.SQL(`select if(left((select max(tcode) from feedtemplet where pastureid = ?),8) =
  11138. (select DATE_FORMAT(now(),"%Y%m%d")),(select max(tcode)+1 from feedtemplet where pastureid = ?),
  11139. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))) tcode`, pastureid, pastureid).GetFirst(code).Error
  11140. if err != nil {
  11141. appG.Response(http.StatusOK, e.ERROR, err)
  11142. return
  11143. }
  11144. if code.Tcode == "" {
  11145. appG.Response(http.StatusOK, e.ERROR, "配方编码生产失败!")
  11146. return
  11147. }
  11148. _, err = tx.Exec(`INSERT INTO feedtemplet(pastureid,tname,tcode,tcolor,ccid,ccname,fttype,fttypeid,source,
  11149. remark,enable,sort,volume,autozone)
  11150. select pastureid,?,?,tcolor,ccid,ccname,fttype,fttypeid,source,
  11151. remark,enable,sort,volume,autozone from feedtemplet where id = ? `, newName, code.Tcode, id)
  11152. if err != nil {
  11153. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11154. return
  11155. }
  11156. _, err = tx.Exec(`insert into ftdetail(pastureid,ftid,fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11157. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry)
  11158. select pastureid,(select id from feedtemplet where tcode = ? ),fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11159. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry
  11160. from ftdetail where ftid = ? `, code.Tcode, id)
  11161. if err != nil {
  11162. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11163. return
  11164. }
  11165. appG.Response(http.StatusOK, e.SUCCESS, true)
  11166. }
  11167. func Test(c *gin.Context) {
  11168. appG := app.Gin{C: c}
  11169. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11170. appG.Response(http.StatusOK, e.SUCCESS, string(dataByte))
  11171. }
  11172. func GetPlanDry(c *gin.Context) {
  11173. appG := app.Gin{C: c}
  11174. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11175. fsion := gofasion.NewFasion(string(dataByte))
  11176. date := fsion.Get("date").ValueStr()
  11177. tx := restful.Engine.NewSession()
  11178. defer tx.Close()
  11179. dataList, err := tx.SQL(`SELECT
  11180. t.feedtempletName,
  11181. ifnull(t.feedtempletPrice,0)feedtempletPrice,
  11182. ifnull(t.feedtempletWeight,0)feedtempletWeight,
  11183. ifnull(t.feedtempletDryWeight,0)feedtempletDryWeight,
  11184. t.tmrno,
  11185. t.bname,
  11186. t.barid,
  11187. t.dry,
  11188. t.actualweightminus,
  11189. t.mydate,
  11190. t.pasturename,
  11191. t.endDate,
  11192. t.startDate,
  11193. t.times,
  11194. -- 计算startDate和endDate的中间时间
  11195. ifnull(DATE_FORMAT(
  11196. DATE_ADD(
  11197. t.startDate,
  11198. INTERVAL TIMESTAMPDIFF(SECOND, t.startDate, t.endDate)/2 SECOND
  11199. ),
  11200. '%Y-%m-%d %H:%i:%s'
  11201. ),'') AS midTime
  11202. FROM (
  11203. SELECT
  11204. (SELECT sort FROM downloadedplan WHERE pid = d.pid AND mydate = d.mydate AND lpplantype IN (0,1)) tmrno,
  11205. b.bname,
  11206. b.id barid,
  11207. 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
  11208. JOIN downloadplandtl1 dd1 ON dd.id = dd1.pid
  11209. JOIN feednur fn ON fn.fid = dd1.fid
  11210. WHERE dd.pid = d.pid AND dd.mydate = d.mydate AND lpplantype IN (0,1,4))/100),2) dry,
  11211. 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,
  11212. DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate,
  11213. p.pasture_name pastureName,
  11214. DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endDate,
  11215. DATE_FORMAT(IFNULL(
  11216. (SELECT MAX(intime) FROM downloadplandtl2 d1
  11217. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d1.intime<d2.intime),
  11218. (SELECT MAX(intime) FROM downloadplandtl1_exec de
  11219. WHERE de.date=d2.date AND de.pastureid = d2.pastureid AND de.pid=d2.pid)
  11220. ), '%Y-%m-%d %H:%i:%s') startDate,
  11221. d.times ,
  11222. ( SELECT
  11223. round(SUM(
  11224. IF(ftd.preftid<>0,
  11225. ftd.fweight*IFNULL((SELECT SUM(ftd1.fweight*f1.dry/100)/SUM(ftd1.fweight) FROM ftdetaildate ftd1
  11226. JOIN feednur f1 ON f1.fid= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11227. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11228. ftd.fweight*f.dry/100)) ,2)
  11229. dryweight
  11230. FROM ftdetaildate ftd
  11231. LEFT JOIN feednur f ON f.fid= ftd.fid AND f.pastureid = ftd.pastureid
  11232. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletDryWeight,(
  11233. select
  11234. sum(ftd.fweight)
  11235. FROM ftdetaildate ftd
  11236. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletWeight,
  11237. ( SELECT
  11238. round(SUM(
  11239. IF(ftd.preftid<>0,
  11240. IFNULL((SELECT SUM(ftd1.fweight*f1.uprice) FROM ftdetaildate ftd1
  11241. JOIN feed f1 ON f1.id= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11242. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11243. ftd.fweight*f.uprice)) ,2)
  11244. dryweight
  11245. FROM ftdetaildate ftd
  11246. LEFT JOIN feed f ON f.id= ftd.fid AND f.pastureid = ftd.pastureid
  11247. WHERE ftd.ftid = d.tempid and ftd.date = d2.date )
  11248. feedtempletPrice,d.templetname feedtempletName
  11249. FROM downloadedplan d
  11250. JOIN downloadplandtl2 d2 ON d.id=d2.PID
  11251. JOIN bar b ON b.id = d2.fbarid
  11252. JOIN pasture p ON p.pastureid = d.pastureid
  11253. WHERE d.mydate = DATE_FORMAT(?,'%Y-%m-%d')
  11254. AND d2.type = 0
  11255. AND d.havebutton = 1
  11256. ) t
  11257. WHERE 1=1 `, date).QueryString()
  11258. if err != nil {
  11259. logs.Error(err)
  11260. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11261. return
  11262. }
  11263. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11264. }
  11265. func GetBar(c *gin.Context) {
  11266. appG := app.Gin{C: c}
  11267. tx := restful.Engine.NewSession()
  11268. defer tx.Close()
  11269. pastureinfo := new(udPastureInfo)
  11270. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  11271. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  11272. if err != nil {
  11273. logs.Error(err)
  11274. return
  11275. }
  11276. dataList, err := tx.SQL(` select id,bname from bar where pastureid = ?`, pastureinfo.Pastureid).QueryString()
  11277. if err != nil {
  11278. logs.Error(err)
  11279. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11280. return
  11281. }
  11282. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11283. }
  11284. func GetHomepage(c *gin.Context) {
  11285. appG := app.Gin{C: c}
  11286. tx := restful.Engine.NewSession()
  11287. defer tx.Close()
  11288. dataList, err := tx.SQL(` SELECT
  11289. ifnull((SELECT CONCAT(ROUND(if(SUM(lweight) <= SUM(iweight),SUM(lweight)/SUM(iweight),SUM(iweight)/SUM(lweight))*100,2),'%') yesRateHL
  11290. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11291. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) ),'0.00%')yesRateHL, -- 昨日混料准确率
  11292. (SELECT CONCAT(ROUND(SUM(iweight)/SUM(lweight)*100,2),'%') yesRateHL
  11293. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11294. 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日混料准确率
  11295. ifnull((SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11296. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11297. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) ),'0.00%')yesRateSL, -- 昨日撒料准确率
  11298. (SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11299. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11300. 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日撒料准确率
  11301. 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),'%') -- 正确率
  11302. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11303. WHERE dt.pastureid = d.pastureid AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')),'0.00%') yesRateSLR, -- 昨日正确率
  11304. (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),'%') -- 正确率
  11305. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11306. WHERE dt.pastureid = d.pastureid
  11307. 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日正确率
  11308. (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,
  11309. (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,
  11310. 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,
  11311. 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,
  11312. ifnull(round(getSLtimeDiffSINGEL(d.pastureid,d.mydate),2),0.00) temtime,
  11313. ifnull(round(getSLtimeDiffMonth(d.pastureid) ,2),0.00) montime
  11314. FROM
  11315. (SELECT (select column_default as pastureid from information_schema.COLUMNS
  11316. 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()
  11317. if err != nil {
  11318. logs.Error(err)
  11319. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11320. return
  11321. }
  11322. dataList1, err := tx.SQL(`select
  11323. 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
  11324. LEFT JOIN ftdetail ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1'
  11325. join feed f on f.id = ifnull(ftd.fid,d1.fid) where d1.date = date_format(now(),'%Y-%m-%d') `).QueryString()
  11326. if err != nil {
  11327. logs.Error(err)
  11328. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11329. return
  11330. }
  11331. for _, data := range dataList {
  11332. for _, data1 := range dataList1 {
  11333. data["totalCost"] = data1["totalCost"]
  11334. data["cost"] = data1["cost"]
  11335. }
  11336. }
  11337. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11338. }
  11339. func GetFeedingManagement(c *gin.Context) {
  11340. appG := app.Gin{C: c}
  11341. typea := c.Query("typea") // 0 栏舍 1 日期
  11342. startDate := c.Query("startdate")
  11343. endDate := c.Query("enddate")
  11344. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11345. // fsion := gofasion.NewFasion(string(dataByte))
  11346. tx := restful.Engine.NewSession()
  11347. defer tx.Close()
  11348. if typea == "0" {
  11349. 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
  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. )
  11357. )actualweightminus ,
  11358. SUM(
  11359. 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 ,
  11360. 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)*
  11361. 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 )),
  11362. 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)*
  11363. 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 ))
  11364. ) * ifnull(fn.dry,0)
  11365. ) dryweight , SUM(
  11366. 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 ,
  11367. 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)*
  11368. 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 )),
  11369. 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)*
  11370. 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 ))
  11371. ) * ifnull(f.uprice,0)
  11372. ) priceweight
  11373. ,(select ccount from feedpdate where date = d1.date and barid = d2.fbarid) ccount,b.bname
  11374. FROM
  11375. downloadedplan d
  11376. JOIN downloadplandtl2 d2
  11377. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11378. JOIN downloadplandtl1 d1
  11379. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11380. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11381. 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
  11382. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11383. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11384. left join feednur fn on fn.fid = f.id
  11385. WHERE d.mydate BETWEEN ? AND ? GROUP BY d2.fbarid ) t `, startDate, endDate).QueryString()
  11386. if err != nil {
  11387. logs.Error(err)
  11388. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11389. return
  11390. }
  11391. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11392. } else {
  11393. 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
  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. )
  11401. )actualweightminus ,
  11402. SUM(
  11403. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11404. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11405. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11406. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11407. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11408. ) * ifnull(fn.dry,0)
  11409. ) dryweight , SUM(
  11410. 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 ,
  11411. 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)*
  11412. 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 )),
  11413. 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)*
  11414. 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 ))
  11415. ) * ifnull(f.uprice,0)
  11416. ) priceweight
  11417. ,(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
  11418. FROM
  11419. downloadedplan d
  11420. JOIN downloadplandtl2 d2
  11421. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11422. JOIN downloadplandtl1 d1
  11423. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11424. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11425. 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
  11426. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11427. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11428. left join feednur fn on fn.fid = f.id
  11429. WHERE d.mydate BETWEEN ? AND ?
  11430. GROUP BY d.mydate) t `, startDate, endDate).QueryString()
  11431. if err != nil {
  11432. logs.Error(err)
  11433. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11434. return
  11435. }
  11436. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11437. }
  11438. }
  11439. func GetFpdetailFname(c *gin.Context) {
  11440. appG := app.Gin{C: c}
  11441. // id := c.Query("id")
  11442. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11443. fsion := gofasion.NewFasion(string(dataByte))
  11444. id := fsion.Get("id").ValueDefaultStr("")
  11445. tx := restful.Engine.NewSession()
  11446. defer tx.Close()
  11447. fpdetailFnameList := make([]*models.FpdetailFname, 0)
  11448. err := tx.SQL(` SELECT
  11449. TRIM(ftid)ftid,TRIM(fid)fid,
  11450. IFNULL((SELECT fname FROM feed WHERE pastureid =ftdetail.pastureid AND id = ftdetail.fid),ftdetail. fname) fname,
  11451. fweight,sort,
  11452. TRIM(ftdetail.id) id, fweight /(select sum(fweight) from ftdetail where ftid = (select ftid from feedp where barid = ? ) ) sumFweight
  11453. FROM
  11454. ftdetail
  11455. WHERE ( ftid=(select ftid from feedp where barid = ? )) AND is_show = 1
  11456. ORDER BY ftdetail.sort,ftdetail.id `, id, id).Find(&fpdetailFnameList)
  11457. if err != nil {
  11458. logs.Error(err)
  11459. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11460. return
  11461. }
  11462. fpdetailList := make([]*models.Fpdetail, 0)
  11463. err = tx.SQL(`select id,barid,barname,times,weight from fpdetail where barid = ?`, id).Find(&fpdetailList)
  11464. if err != nil {
  11465. logs.Error(err)
  11466. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11467. return
  11468. }
  11469. for _, f := range fpdetailFnameList {
  11470. f.FWeight = 0
  11471. for _, fpd := range fpdetailList {
  11472. value := f.SumFWeight * fpd.Weight
  11473. // 将其四舍五入到小数点后两位
  11474. roundedValue := math.Round(value*100) / 100
  11475. if fpd.Times == 1 {
  11476. f.TimesOne = roundedValue
  11477. } else if fpd.Times == 2 {
  11478. f.TimesTwo = roundedValue
  11479. } else if fpd.Times == 3 {
  11480. f.TimesThree = roundedValue
  11481. } else if fpd.Times == 4 {
  11482. f.TimesFour = roundedValue
  11483. } else if fpd.Times == 5 {
  11484. f.TimesFive = roundedValue
  11485. } else if fpd.Times == 6 {
  11486. f.TimesSix = roundedValue
  11487. }
  11488. f.FWeight += value
  11489. }
  11490. }
  11491. fpdetailFname := new(models.FpdetailFname)
  11492. fpdetailFname.FName = "合计"
  11493. for _, f := range fpdetailFnameList {
  11494. fpdetailFname.TimesOne += f.TimesOne
  11495. fpdetailFname.TimesTwo += f.TimesTwo
  11496. fpdetailFname.TimesThree += f.TimesThree
  11497. fpdetailFname.TimesFour += f.TimesFour
  11498. fpdetailFname.TimesFive += f.TimesFive
  11499. fpdetailFname.TimesSix += f.TimesSix
  11500. fpdetailFname.FWeight += f.FWeight
  11501. f.FWeight = RoundFloat(f.FWeight, 2)
  11502. }
  11503. // 在处理代码中
  11504. fpdetailFname.TimesOne = RoundFloat(fpdetailFname.TimesOne, 2)
  11505. fpdetailFname.TimesTwo = RoundFloat(fpdetailFname.TimesTwo, 2)
  11506. fpdetailFname.TimesThree = RoundFloat(fpdetailFname.TimesThree, 2)
  11507. fpdetailFname.TimesFour = RoundFloat(fpdetailFname.TimesFour, 2)
  11508. fpdetailFname.TimesFive = RoundFloat(fpdetailFname.TimesFive, 2)
  11509. fpdetailFname.TimesSix = RoundFloat(fpdetailFname.TimesSix, 2)
  11510. fpdetailFname.FWeight = RoundFloat(fpdetailFname.FWeight, 2)
  11511. fpdetailFnameList = append(fpdetailFnameList, fpdetailFname)
  11512. appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11513. }
  11514. func RoundFloat(x float64, prec int) float64 {
  11515. output := math.Pow(10, float64(prec))
  11516. return math.Round(x*output) / output
  11517. }
  11518. func GetLyUdData(c *gin.Context) {
  11519. appG := app.Gin{C: c}
  11520. // id := c.Query("id")
  11521. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11522. fsion := gofasion.NewFasion(string(dataByte))
  11523. myDate := fsion.Get("myDate").ValueDefaultStr("")
  11524. times := fsion.Get("Times").ValueDefaultStr("")
  11525. name := fsion.Get("name").ValueDefaultStr("")
  11526. tx := restful.Engine.NewSession()
  11527. defer tx.Close()
  11528. if name == "dateplanlist" {
  11529. 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
  11530. join pasture p on dl.pastureId=p.pastureid JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId
  11531. where dl.Mydate = ? AND dl.lpplanType =0 and dl.Times= ? GROUP BY dl.id union all
  11532. 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
  11533. from downloadedplan dl join pasture p on dl.pastureId=p.pastureid
  11534. 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
  11535. where dl.Mydate = ? AND dl.lpplanType =2 and dl.Times= ?
  11536. GROUP BY dl.id order by ProjName `, myDate, times, myDate, times).Query().List()
  11537. fmt.Println(err)
  11538. appG.Response(http.StatusOK, e.SUCCESS, data)
  11539. return
  11540. } else if name == "getAddFeed" {
  11541. 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,
  11542. 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,
  11543. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM downloadedplan dd
  11544. JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11545. 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
  11546. join feedtemplet ftd on ftd.id = d.tempid and ftd.pastureId = d.pastureId
  11547. JOIN feed f ON f.id = d1.fid AND f.pastureId = d.pastureId
  11548. WHERE DATE_FORMAT(dd.Mydate ,'%Y-%m-%d' ) = ? and dd.Times =? and d1.type = 0
  11549. 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,
  11550. round(d1.LWEIGHT *(ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and ftid = ftdd.ftid and pastureId = d.pastureId )),2) expWeight,
  11551. 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,
  11552. '' 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,
  11553. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM
  11554. downloadedplan dd JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11555. 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
  11556. join feedtemplet ftd on ftd.id = d1.fid and ftd.pastureId = d.pastureId
  11557. join ftdetaildate ftdd on ftdd.ftid = ftd.id and ftdd.date = d.Mydate and ftdd.pastureId = d.pastureId
  11558. join feed f on f.id = ftdd.fid and f.pastureId = d.pastureId
  11559. 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()
  11560. appG.Response(http.StatusOK, e.SUCCESS, data)
  11561. return
  11562. } else if name == "getDeleteFeed" {
  11563. 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,
  11564. 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 ,
  11565. (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
  11566. ,d2.xxwBarCode as penId,if(d.lpplanType=2,(select id from downloadedplan p where p.pid=d.pid and p.mydate=? and p.Times=?
  11567. and p.lpplanType=1 limit 1),d2.pid) Id from downloadedplan d LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID
  11568. and d.pastureId=d2.pastureId where d.mydate=? AND d.lpplanType in (0,2) and d.Times=?`, myDate, times, myDate, times).Query().List()
  11569. appG.Response(http.StatusOK, e.SUCCESS, data)
  11570. return
  11571. }
  11572. // appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11573. }