ops.go 459 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669
  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. fmt.Println(time.Now())
  217. if sqlnamestr == "getHomepageStr" {
  218. parammaps := fsion.Get("parammaps")
  219. pastureid := parammaps.Get("pastureid").ValueStr()
  220. var montimeList []float64
  221. var montime float64
  222. var wg sync.WaitGroup
  223. now := time.Now()
  224. for i := 0; i < 30; i++ {
  225. wg.Add(1)
  226. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  227. go func(nowstr string) {
  228. defer wg.Done()
  229. fmt.Println(nowstr)
  230. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  231. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  232. fmt.Println(nowstr)
  233. if len(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})) > 0 {
  234. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  235. montimeList = append(montimeList, m)
  236. }
  237. }(nowstr)
  238. }
  239. fmt.Println(time.Now())
  240. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  241. if err != nil {
  242. logging.Error("GetDataByName err: ", err)
  243. msg := geterrmsg(err.Error())
  244. appG.Response(http.StatusOK, e.ERROR, msg)
  245. }
  246. fmt.Println(time.Now())
  247. wg.Wait()
  248. for _, m := range montimeList {
  249. montime += m
  250. }
  251. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  252. fmt.Println(time.Now())
  253. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  254. return
  255. }
  256. // if sqlnamestr == "getHomepageStr" {
  257. // }
  258. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  259. if err != nil {
  260. logging.Error("GetDataByName err: ", err)
  261. msg := geterrmsg(err.Error())
  262. appG.Response(http.StatusOK, e.ERROR, msg)
  263. } else {
  264. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  265. }
  266. }
  267. } else {
  268. appG.Response(http.StatusOK, e.SUCCESS, nil)
  269. }
  270. }
  271. // @Summary 根据APISQL表中SQL执行得到数据集
  272. // @Tags GetDataByName
  273. // @Accept json
  274. // @Produce json
  275. // @Param sqlname body string true "sqlname"
  276. // @Param offset body int true "offset"
  277. // @Param pagecount body int true "pagecount"
  278. // @Param returntype body string true "returntype"
  279. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  280. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  281. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  282. // @Router /data/GetDataByName [POST]
  283. func GetDataBySqlIN(c *gin.Context) {
  284. appG := app.Gin{C: c}
  285. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  286. fsion := gofasion.NewFasion(string(dataByte))
  287. sqlnamestr := fsion.Get("name").ValueStr()
  288. offset := fsion.Get("offset").ValueDefaultInt(0)
  289. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  290. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  291. tx := restful.Engine.NewSession()
  292. err := tx.Begin()
  293. defer func() {
  294. switch {
  295. case err != nil:
  296. logging.Error("tx.Begin 事务启动失败__error:", err)
  297. if tx != nil {
  298. tx.Rollback()
  299. }
  300. default:
  301. if tx != nil {
  302. err = tx.Commit()
  303. }
  304. }
  305. if tx != nil {
  306. tx.Close()
  307. }
  308. }()
  309. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  310. if sql != "" {
  311. s_params := make([]interface{}, 0)
  312. if fsion.HasKey("parammaps") {
  313. parammaps := fsion.Get("parammaps")
  314. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  315. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  316. }
  317. paramslist := strings.Split(p, ",")
  318. if len(paramslist) > 0 && p != "" {
  319. for _, value := range paramslist {
  320. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  321. if tempv, exists := c.Get("jwt_username"); exists {
  322. s_params = append(s_params, tempv.(string))
  323. } else {
  324. s_params = append(s_params, "")
  325. }
  326. } else {
  327. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  328. }
  329. }
  330. }
  331. } else if fsion.HasKey("params") {
  332. params := fsion.Get("params").Array()
  333. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  334. for _, v_params := range params {
  335. s_params = append(s_params, v_params.ValueStr())
  336. }
  337. }
  338. if returntype == "xlsx" {
  339. var xlsxfile *xlsx.File
  340. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  341. //c.File("c:/dd.xlsx")
  342. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  343. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  344. c.Header("Content-Transfer-Encoding", "binary")
  345. _ = xlsxfile.Write(c.Writer)
  346. } else {
  347. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  348. if err != nil {
  349. logging.Error("GetDataByName err: ", err)
  350. msg := geterrmsg(err.Error())
  351. appG.Response(http.StatusOK, e.ERROR, msg)
  352. } else {
  353. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  354. }
  355. }
  356. } else {
  357. appG.Response(http.StatusOK, e.SUCCESS, nil)
  358. }
  359. }
  360. // 错误处理
  361. // 将报错信息处理成汉字
  362. func geterrmsg(errstr string) (msgstr string) {
  363. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  364. rs := []rune(errstr)
  365. if hzRegexp.MatchString(string(rs[0])) {
  366. msgstr = errstr
  367. return
  368. }
  369. if strings.Contains(errstr, "Duplicate entry") {
  370. strs := strings.Split(errstr, ` key '`)
  371. if len(strs) > 1 {
  372. if len(strs[len(strs)-1]) > 1 {
  373. errstr = "Duplicate entry :" + strs[len(strs)-1]
  374. }
  375. }
  376. }
  377. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  378. if err != nil {
  379. msgstr = errstr
  380. return
  381. }
  382. if msg == nil || len(msg) == 0 {
  383. var param []interface{}
  384. param = append(param, errstr, errstr)
  385. go func() {
  386. tx := restful.Engine.NewSession()
  387. err := tx.Begin()
  388. defer func() {
  389. switch {
  390. case err != nil:
  391. logging.Error("tx.Begin 事务启动失败__error:", err)
  392. if tx != nil {
  393. tx.Rollback()
  394. }
  395. default:
  396. if tx != nil {
  397. err = tx.Commit()
  398. }
  399. }
  400. if tx != nil {
  401. tx.Close()
  402. }
  403. }()
  404. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  405. if err != nil {
  406. logging.Error("insert into err_msg(err,msg) err", err)
  407. }
  408. }()
  409. msgstr = errstr
  410. } else {
  411. msgstr = msg[0]["msg"]
  412. }
  413. return
  414. }
  415. // @Summary 根据APISQL表中SQL执行得到数据集
  416. // @Tags GetDataByNameForm
  417. // @Accept json
  418. // @Produce json
  419. // @Param sqlname body json true "sqlname"
  420. // @Param offset query int true "offset"
  421. // @Param pagecount query int true "pagecount"
  422. // @Param returntype query string true "returntype"
  423. // @Param s formData json true "ss"
  424. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  425. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  426. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  427. // @Router /data/GetDataByNameForm [POST]
  428. func GetDataByNameForm(c *gin.Context) {
  429. appG := app.Gin{C: c}
  430. //sqlnamestr := c.PostForm("measureNumber")
  431. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  432. //fsion := gofasion.NewFasion(string(dataByte))
  433. //sqlnamestr := fsion.Get("name").ValueStr()
  434. //offset := fsion.Get("offset").ValueInt()
  435. //pagecount := fsion.Get("pagecount").ValueInt()
  436. //returntype := fsion.Get("returntype").ValueStr()
  437. //params := fsion.Get("params").Array()
  438. c.Request.ParseForm()
  439. params := c.Request.Form
  440. offset := 0
  441. pageSize_ := 0
  442. returntype := params.Get("page")
  443. if returntype == "" {
  444. returntype = "0"
  445. }
  446. if tempv, exists := c.Get("jwt_username"); exists {
  447. params.Set("JwtUserName", tempv.(string))
  448. } else {
  449. params.Set("JwtUserName", "")
  450. }
  451. sqlnamestr := params.Get("name")
  452. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  453. s_params := make([]interface{}, 0)
  454. if returntype == "1" {
  455. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  456. if error != nil {
  457. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  458. }
  459. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  460. if error != nil {
  461. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  462. }
  463. pageSize_ = pageSize
  464. offset = pageNum
  465. }
  466. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  467. paramslist := strings.Split(p, ",")
  468. if len(paramslist) > 0 && p != "" {
  469. for _, value := range paramslist {
  470. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  471. }
  472. }
  473. if sql != "" {
  474. if returntype == "xlsx" {
  475. var xlsxfile *xlsx.File
  476. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  477. c.Header("Content-Type", "application/octet-stream")
  478. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  479. c.Header("Content-Transfer-Encoding", "binary")
  480. _ = xlsxfile.Write(c.Writer)
  481. } else {
  482. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  483. if err != nil {
  484. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  485. } else {
  486. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  487. }
  488. }
  489. } else {
  490. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  491. }
  492. }
  493. // @Summary 递归获取所有
  494. // @Tags menu
  495. // @Accept json
  496. // @Produce json
  497. // @Param Ton query string true "Ton"
  498. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  499. // @Router /authdata/GetRoleMenus [GET]
  500. func GetRecuDataByName(c *gin.Context) {
  501. appG := app.Gin{C: c}
  502. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  503. fsion := gofasion.NewFasion(string(dataByte))
  504. sqlnamestr := fsion.Get("name").ValueStr()
  505. parentidname := fsion.Get("idname").ValueStr()
  506. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  507. params := make(map[string]interface{})
  508. s_params := make([]interface{}, 0)
  509. if fsion.HasKey("params") {
  510. for _, v_params := range fsion.Get("params").Array() {
  511. s_params = append(s_params, v_params.ValueStr())
  512. }
  513. params["params"] = s_params
  514. } else {
  515. jparams := fsion.Get("parammaps")
  516. paramslist := strings.Split(p, ",")
  517. if len(paramslist) > 0 && p != "" {
  518. for _, value := range paramslist {
  519. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  520. if tempv, exists := c.Get("jwt_username"); exists {
  521. params[value] = tempv.(string)
  522. } else {
  523. params[value] = ""
  524. }
  525. } else {
  526. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  527. }
  528. }
  529. }
  530. }
  531. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  532. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  533. if err != nil {
  534. appG.Response(http.StatusOK, e.ERROR, err.Error())
  535. }
  536. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  537. }
  538. // @Summary 根据APISQL表中SQL执行得到数据集
  539. // @Tags GetDataByNames
  540. // @Accept json
  541. // @Produce json
  542. // @RequestBody sqlname query string true "sqlname"
  543. // @Param offset query int true "offset"
  544. // @Param pagecount query int true "pagecount"
  545. // @Param returntype query string true "returntype"
  546. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  547. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  548. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  549. // @Router /data/GetDataByNames [POST]
  550. func GetDataByNames(c *gin.Context) {
  551. appG := app.Gin{C: c}
  552. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  553. fsion := gofasion.NewFasion(string(dataByte))
  554. sqlParams := fsion.Array()
  555. queryData := make(map[string]interface{})
  556. for _, v := range sqlParams {
  557. fsion2 := gofasion.NewFasion(v.Json())
  558. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  559. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  560. if sql == "" {
  561. errorm := make(map[string]interface{})
  562. errorm["code"] = e.ERROR
  563. errorm["message"] = "sql没找到"
  564. queryData[fsion2.Get("name").ValueStr()] = errorm
  565. continue
  566. } else if sql != "" {
  567. offset := fsion2.Get("offset").ValueInt()
  568. pagecount := fsion2.Get("pagecount").ValueInt()
  569. returntype := fsion2.Get("returntype").ValueStr()
  570. s_params := make([]interface{}, 0)
  571. if fsion2.HasKey("parammaps") {
  572. parammaps := fsion2.Get("parammaps")
  573. paramslist := strings.Split(p, ",")
  574. if len(paramslist) > 0 && p != "" {
  575. for _, value := range paramslist {
  576. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  577. if tempv, exists := c.Get("jwt_username"); exists {
  578. s_params = append(s_params, tempv.(string))
  579. } else {
  580. s_params = append(s_params, "")
  581. }
  582. } else {
  583. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  584. }
  585. }
  586. }
  587. } else if fsion2.HasKey("params") {
  588. params := fsion2.Get("params").Array()
  589. for _, v_params := range params {
  590. s_params = append(s_params, v_params.ValueStr())
  591. }
  592. }
  593. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  594. if err != nil {
  595. errorm := make(map[string]interface{})
  596. errorm["code"] = e.ERROR
  597. errorm["message"] = err.Error()
  598. queryData[fsion2.Get("name").ValueStr()] = errorm
  599. logging.Error("GetDataByNames err: ", err)
  600. continue
  601. } else {
  602. queryData[fsion2.Get("name").ValueStr()] = queryData1
  603. }
  604. }
  605. }
  606. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  607. }
  608. // @Summary 根据APISQL表中SQL执行得到数据集
  609. // @Tags PostDataByNameForm
  610. // @Accept json
  611. // @Produce json
  612. // @Param sqlname query string true "sqlname"
  613. // @Param offset query int true "offset"
  614. // @Param pagecount query int true "pagecount"
  615. // @Param returntype query string true "returntype"
  616. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  617. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  618. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  619. // @Router /data/PostDataByNameForm [POST]
  620. func PostDataByNameForm(c *gin.Context) {
  621. appG := app.Gin{C: c}
  622. c.Request.ParseForm()
  623. params := c.Request.Form
  624. sqlnamestr := params.Get("name")
  625. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  626. s_params := make([]interface{}, 0)
  627. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  628. paramslist := strings.Split(p, ",")
  629. if len(paramslist) > 0 {
  630. for _, value := range paramslist {
  631. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  632. }
  633. }
  634. if sql != "" {
  635. queryData, err := execDataBySql(sql, s_params)
  636. if err != nil {
  637. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  638. } else {
  639. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  640. }
  641. } else {
  642. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  643. }
  644. }
  645. // GetReportform 将数据集转换格式
  646. // @Tags PostDataByNameForm
  647. // @Accept json
  648. // @Produce json
  649. // @Param sqlname query string true "sqlname"
  650. // @Param offset query int true "offset"
  651. // @Param pagecount query int true "pagecount"
  652. // @Param returntype query string true "returntype"
  653. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  654. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  655. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  656. func GetReportform(c *gin.Context) {
  657. appG := app.Gin{C: c}
  658. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  659. fsion := gofasion.NewFasion(string(dataByte))
  660. sqlnamestr := fsion.Get("name").ValueStr()
  661. checked := fsion.Get("checked").ValueStr()
  662. offset := fsion.Get("offset").ValueDefaultInt(0)
  663. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  664. parammaps := fsion.Get("parammaps")
  665. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  666. mode := parammaps.Get("mode").ValueDefaultInt(0)
  667. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  668. tx := restful.Engine.NewSession()
  669. err := tx.Begin()
  670. defer func() {
  671. switch {
  672. case err != nil:
  673. if tx != nil {
  674. tx.Rollback()
  675. }
  676. default:
  677. if tx != nil {
  678. err = tx.Commit()
  679. }
  680. }
  681. if tx != nil {
  682. tx.Close()
  683. }
  684. }()
  685. //fmt.Println("***************************************")
  686. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  687. if err != nil {
  688. appG.Response(http.StatusOK, e.ERROR, err.Error())
  689. } else {
  690. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  691. }
  692. }
  693. // GetUpkeepPlan 保养计划
  694. func GetUpkeepPlan(c *gin.Context) {
  695. appG := app.Gin{C: c}
  696. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  697. fsion := gofasion.NewFasion(string(dataByte))
  698. sqlnamestr := fsion.Get("name").ValueStr()
  699. offset := fsion.Get("offset").ValueDefaultInt(0)
  700. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  701. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  702. month := fsion.Get("month").ValueDefaultStr("map")
  703. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  704. tx := restful.Engine.NewSession()
  705. err := tx.Begin()
  706. defer func() {
  707. switch {
  708. case err != nil:
  709. if tx != nil {
  710. tx.Rollback()
  711. }
  712. default:
  713. if tx != nil {
  714. err = tx.Commit()
  715. }
  716. }
  717. if tx != nil {
  718. tx.Close()
  719. }
  720. }()
  721. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  722. if sql != "" {
  723. s_params := make([]interface{}, 0)
  724. if fsion.HasKey("parammaps") {
  725. parammaps := fsion.Get("parammaps")
  726. paramslist := strings.Split(p, ",")
  727. if len(paramslist) > 0 && p != "" {
  728. for _, value := range paramslist {
  729. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  730. if tempv, exists := c.Get("jwt_username"); exists {
  731. s_params = append(s_params, tempv.(string))
  732. } else {
  733. s_params = append(s_params, "")
  734. }
  735. } else {
  736. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  737. }
  738. }
  739. }
  740. } else if fsion.HasKey("params") {
  741. params := fsion.Get("params").Array()
  742. for _, v_params := range params {
  743. s_params = append(s_params, v_params.ValueStr())
  744. }
  745. }
  746. if returntype == "xlsx" {
  747. var xlsxfile *xlsx.File
  748. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  749. //c.File("c:/dd.xlsx")
  750. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  751. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  752. c.Header("Content-Transfer-Encoding", "binary")
  753. _ = xlsxfile.Write(c.Writer)
  754. } else {
  755. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  756. if err != nil {
  757. appG.Response(http.StatusOK, e.ERROR, err.Error())
  758. } else {
  759. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  760. if v, ok := value["id"]; ok {
  761. //month = "2020-03"
  762. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  763. if seviceplans != nil {
  764. for _, va := range seviceplans { //根据保养计划获取保养单
  765. //day,_ :=strconv.Atoi(va["day"])
  766. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  767. //buk := make(map[string]map[string]string)
  768. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  769. jstr := ""
  770. if bu["plantime"][8:9] == "0" {
  771. jstr = "m" + bu["plantime"][9:]
  772. } else {
  773. jstr = "m" + bu["plantime"][8:]
  774. }
  775. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  776. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  777. } else {
  778. if bu["flowCompeleted"] >= "2" {
  779. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  780. } else {
  781. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  782. }
  783. }
  784. }
  785. }
  786. }
  787. }
  788. }
  789. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  790. }
  791. }
  792. } else {
  793. appG.Response(http.StatusOK, e.SUCCESS, nil)
  794. }
  795. }
  796. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  797. // todo 优化性能 children统一查询
  798. // @Tags PostDataByNameForm
  799. // @Accept json
  800. // @Produce json
  801. // @Param sqlname query string true "sqlname"
  802. // @Param offset query int true "offset"
  803. // @Param pagecount query int true "pagecount"
  804. // @Param returntype query string true "returntype"
  805. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  806. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  807. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  808. func GetArrList(c *gin.Context) {
  809. appG := app.Gin{C: c}
  810. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  811. fsion := gofasion.NewFasion(string(dataByte))
  812. sqlnamestr := fsion.Get("name").ValueStr()
  813. sqlnamestr1 := fsion.Get("name1").ValueStr()
  814. offset := fsion.Get("offset").ValueDefaultInt(0)
  815. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  816. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  817. month := fsion.Get("month").ValueDefaultStr("map")
  818. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  819. tx := restful.Engine.NewSession()
  820. err := tx.Begin()
  821. defer func() {
  822. switch {
  823. case err != nil:
  824. if tx != nil {
  825. tx.Rollback()
  826. }
  827. default:
  828. if tx != nil {
  829. err = tx.Commit()
  830. }
  831. }
  832. if tx != nil {
  833. tx.Close()
  834. }
  835. }()
  836. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  837. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  838. if sql != "" {
  839. s_params := make([]interface{}, 0)
  840. if fsion.HasKey("parammaps") {
  841. parammaps := fsion.Get("parammaps")
  842. paramslist := strings.Split(p, ",")
  843. if len(paramslist) > 0 && p != "" {
  844. for _, value := range paramslist {
  845. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  846. if tempv, exists := c.Get("jwt_username"); exists {
  847. s_params = append(s_params, tempv.(string))
  848. } else {
  849. s_params = append(s_params, "")
  850. }
  851. } else {
  852. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  853. }
  854. }
  855. }
  856. }
  857. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  858. if err != nil {
  859. appG.Response(http.StatusOK, e.ERROR, err.Error())
  860. } else {
  861. paramslist1 := strings.Split(p1, ",")
  862. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  863. s_params1 := make([]interface{}, 0)
  864. if len(paramslist1) > 0 && p1 != "" {
  865. for _, v := range paramslist1 {
  866. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  867. }
  868. }
  869. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  870. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  871. }
  872. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  873. }
  874. } else {
  875. appG.Response(http.StatusOK, e.SUCCESS, nil)
  876. }
  877. }
  878. func GetAccount(c *gin.Context) {
  879. appG := app.Gin{C: c}
  880. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  881. fsion := gofasion.NewFasion(string(dataByte))
  882. sqlnamestr := fsion.Get("name").ValueStr()
  883. offset := fsion.Get("offset").ValueDefaultInt(0)
  884. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  885. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  886. tx := restful.Engine.NewSession()
  887. err := tx.Begin()
  888. defer func() {
  889. switch {
  890. case err != nil:
  891. logging.Error("tx.Begin 事务启动失败__error:", err)
  892. if tx != nil {
  893. tx.Rollback()
  894. }
  895. default:
  896. if tx != nil {
  897. err = tx.Commit()
  898. }
  899. }
  900. if tx != nil {
  901. tx.Close()
  902. }
  903. }()
  904. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  905. if sql != "" {
  906. s_params := make([]interface{}, 0)
  907. if fsion.HasKey("parammaps") {
  908. parammaps := fsion.Get("parammaps")
  909. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  910. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  911. }
  912. paramslist := strings.Split(p, ",")
  913. if len(paramslist) > 0 && p != "" {
  914. for _, value := range paramslist {
  915. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  916. if tempv, exists := c.Get("jwt_username"); exists {
  917. s_params = append(s_params, tempv.(string))
  918. } else {
  919. s_params = append(s_params, "")
  920. }
  921. } else {
  922. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  923. }
  924. }
  925. }
  926. } else if fsion.HasKey("params") {
  927. params := fsion.Get("params").Array()
  928. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  929. for _, v_params := range params {
  930. s_params = append(s_params, v_params.ValueStr())
  931. }
  932. }
  933. if returntype == "xlsx" {
  934. var xlsxfile *xlsx.File
  935. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  936. //c.File("c:/dd.xlsx")
  937. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  938. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  939. c.Header("Content-Transfer-Encoding", "binary")
  940. _ = xlsxfile.Write(c.Writer)
  941. } else {
  942. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  943. if err != nil {
  944. logging.Error("GetDataByName err: ", err)
  945. msg := geterrmsg(err.Error())
  946. appG.Response(http.StatusOK, e.ERROR, msg)
  947. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  948. } else {
  949. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  950. }
  951. }
  952. } else {
  953. appG.Response(http.StatusOK, e.SUCCESS, nil)
  954. }
  955. }
  956. // PostDataByName 根据APISQL表中SQL执行得到数据集
  957. // @Accept json
  958. // @Produce json
  959. // @Param sqlname query string true "sqlname"
  960. // @Param offset query int true "offset"
  961. // @Param pagecount query int true "pagecount"
  962. // @Param returntype query string true "returntype"
  963. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  964. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  965. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  966. // @Router /data/PostDataByName [POST]
  967. func PostDataByName(c *gin.Context) {
  968. appG := app.Gin{C: c}
  969. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  970. fsion := gofasion.NewFasion(string(dataByte))
  971. var err error
  972. queryData, err := module.PostDataByName(c, fsion)
  973. if err != nil {
  974. appG.Response(http.StatusOK, e.ERROR, err.Error())
  975. return
  976. }
  977. var (
  978. keyWord string
  979. )
  980. switch fsion.Get("name").ValueStr() {
  981. case "insertFeedclass":
  982. keyWord = "feed"
  983. err = module.GroupCategorySync(keyWord, fsion)
  984. case "deleteFeedclass":
  985. keyWord = "feed_delete"
  986. err = module.GroupCategoryDelete(keyWord, fsion)
  987. case "insertCowclass":
  988. keyWord = "cow"
  989. err = module.GroupCategorySync(keyWord, fsion)
  990. case "deleteCowclass":
  991. keyWord = "cow_delete"
  992. err = module.GroupCategoryDelete(keyWord, fsion)
  993. // case "updateFT":
  994. // FtdetailSurplus(fsion)
  995. // case "updateFeed":
  996. // FeedSurplus(fsion)
  997. default:
  998. }
  999. if err != nil {
  1000. logging.Error(keyWord, err)
  1001. }
  1002. if queryData != nil {
  1003. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1004. return
  1005. }
  1006. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1007. }
  1008. //人脸识别/格润富德接口
  1009. func GetRJSBData(c *gin.Context) {
  1010. appG := app.Gin{C: c}
  1011. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1012. fsion := gofasion.NewFasion(string(dataByte))
  1013. sqlnamestr := fsion.Get("name").ValueStr()
  1014. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1015. offset := fsion.Get("offset").ValueDefaultInt(0)
  1016. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1017. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1018. month := fsion.Get("month").ValueDefaultStr("map")
  1019. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1020. pagecount = 1
  1021. tx := restful.Engine.NewSession()
  1022. err := tx.Begin()
  1023. defer func() {
  1024. switch {
  1025. case err != nil:
  1026. if tx != nil {
  1027. tx.Rollback()
  1028. }
  1029. default:
  1030. if tx != nil {
  1031. err = tx.Commit()
  1032. }
  1033. }
  1034. if tx != nil {
  1035. tx.Close()
  1036. }
  1037. }()
  1038. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1039. _, 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 )
  1040. where id = (select tmrid from downloadedplan d where d.pid = (select pid from downloadedplan where lpplantype = 5 and mydate =
  1041. date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted= 0 ) and mydate = date_format(now() ,'%Y-%m-%d')
  1042. and lpplantype in(0,1)) `).Execute()
  1043. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1044. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1045. if sql != "" {
  1046. s_params := make([]interface{}, 0)
  1047. if fsion.HasKey("parammaps") {
  1048. parammaps := fsion.Get("parammaps")
  1049. paramslist := strings.Split(p, ",")
  1050. if len(paramslist) > 0 && p != "" {
  1051. for _, value := range paramslist {
  1052. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1053. if tempv, exists := c.Get("jwt_username"); exists {
  1054. s_params = append(s_params, tempv.(string))
  1055. } else {
  1056. s_params = append(s_params, "")
  1057. }
  1058. } else {
  1059. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1060. }
  1061. }
  1062. }
  1063. }
  1064. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1065. if err != nil {
  1066. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1067. } else {
  1068. paramslist1 := strings.Split(p1, ",")
  1069. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1070. s_params1 := make([]interface{}, 0)
  1071. if len(paramslist1) > 0 && p1 != "" {
  1072. for _, v := range paramslist1 {
  1073. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1074. }
  1075. }
  1076. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1077. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1078. }
  1079. var wg sync.WaitGroup
  1080. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1081. wg.Add(1)
  1082. go func(value map[string]interface{}) {
  1083. defer wg.Done()
  1084. // ,havebutton = 1
  1085. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1086. }(value)
  1087. }
  1088. wg.Wait()
  1089. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1090. }
  1091. fmt.Println("先锋获取数据:", time.Now(), queryData)
  1092. } else {
  1093. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1094. }
  1095. }
  1096. func PostRJSBData(c *gin.Context) {
  1097. appG := app.Gin{C: c}
  1098. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1099. fsion := gofasion.NewFasion(string(dataByte))
  1100. logging.Info("PostRJSBData err: ", string(dataByte))
  1101. s_params := make([]interface{}, 0)
  1102. tx := restful.Engine.NewSession()
  1103. err := tx.Begin()
  1104. defer func() {
  1105. switch {
  1106. case err != nil:
  1107. if tx != nil {
  1108. tx.Rollback()
  1109. }
  1110. default:
  1111. if tx != nil {
  1112. err = tx.Commit()
  1113. }
  1114. }
  1115. if tx != nil {
  1116. tx.Close()
  1117. }
  1118. }()
  1119. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1120. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1121. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1122. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1123. if !fsion.HasKey("parammaps") {
  1124. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1125. return
  1126. }
  1127. parammaps := fsion.Get("parammaps")
  1128. paramslist := strings.Split(p, ",")
  1129. if len(paramslist) > 0 && p != "" {
  1130. for _, value := range paramslist {
  1131. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1132. }
  1133. }
  1134. projuctid := parammaps.Get("projuctid").ValueStr()
  1135. _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
  1136. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1137. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1138. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1139. and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1140. if err != nil {
  1141. logging.Error("PostRJSBData-0 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. _, err = tx.SQL(sql, s_params...).Execute()
  1148. if err != nil {
  1149. logging.Error("PostRJSBData err: ", err)
  1150. msg := geterrmsg(err.Error())
  1151. // appG.Response(http.StatusOK, e.ERROR, msg)
  1152. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1153. return
  1154. }
  1155. s_params = make([]interface{}, 0)
  1156. paramslist = strings.Split(p1, ",")
  1157. if len(paramslist) > 0 && p1 != "" {
  1158. for _, value := range paramslist {
  1159. // if value == "ID" {
  1160. // id := parammaps.Get("ID").ValueStr()
  1161. // pastureid := parammaps.Get("pastureid").ValueStr()
  1162. // 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
  1163. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1164. // if err != nil {
  1165. // logging.Error("PostRJSBData err: ", err)
  1166. // msg := geterrmsg(err.Error())
  1167. // appG.Response(http.StatusOK, e.ERROR, msg)
  1168. // return
  1169. // }
  1170. // for _, item := range datalist {
  1171. // id = item["id"]
  1172. // }
  1173. // s_params = append(s_params, id)
  1174. // } else {
  1175. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1176. // }
  1177. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1178. }
  1179. }
  1180. _, err = tx.SQL(sql1, s_params...).Execute()
  1181. if err != nil {
  1182. logging.Error("PostRJSBData1 err: ", err)
  1183. msg := geterrmsg(err.Error())
  1184. appG.Response(http.StatusOK, e.ERROR, msg)
  1185. return
  1186. }
  1187. s_params = make([]interface{}, 0)
  1188. paramslist = strings.Split(p2, ",")
  1189. if len(paramslist) > 0 && p2 != "" {
  1190. for _, value := range paramslist {
  1191. if value == "ID" {
  1192. id := parammaps.Get("ID").ValueStr()
  1193. pastureid := parammaps.Get("pastureid").ValueStr()
  1194. 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
  1195. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1196. if err != nil {
  1197. logging.Error("PostRJSBData err: ", err)
  1198. msg := geterrmsg(err.Error())
  1199. appG.Response(http.StatusOK, e.ERROR, msg)
  1200. return
  1201. }
  1202. for _, item := range datalist {
  1203. id = item["id"]
  1204. }
  1205. s_params = append(s_params, id)
  1206. } else {
  1207. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1208. }
  1209. }
  1210. }
  1211. _, err = tx.SQL(sql2, s_params...).Execute()
  1212. if err != nil {
  1213. logging.Error("PostRJSBData2 err: ", err)
  1214. msg := geterrmsg(err.Error())
  1215. appG.Response(http.StatusOK, e.ERROR, msg)
  1216. return
  1217. }
  1218. s_params = make([]interface{}, 0)
  1219. paramslist = strings.Split(p3, ",")
  1220. if len(paramslist) > 0 && p3 != "" {
  1221. for _, value := range paramslist {
  1222. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1223. }
  1224. }
  1225. _, err = tx.SQL(sql3, s_params...).Execute()
  1226. if err != nil {
  1227. logging.Error("PostRJSBData3 err: ", err)
  1228. msg := geterrmsg(err.Error())
  1229. appG.Response(http.StatusOK, e.ERROR, msg)
  1230. return
  1231. }
  1232. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1233. }
  1234. func PostRJSBDatas(c *gin.Context) {
  1235. appG := app.Gin{C: c}
  1236. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1237. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1238. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1239. fmt.Println("先锋回传数据:", time.Now(), string(dataByte))
  1240. tx := restful.Engine.NewSession()
  1241. err := tx.Begin()
  1242. defer func() {
  1243. switch {
  1244. case err != nil:
  1245. if tx != nil {
  1246. tx.Rollback()
  1247. }
  1248. default:
  1249. if tx != nil {
  1250. err = tx.Commit()
  1251. }
  1252. }
  1253. if tx != nil {
  1254. tx.Close()
  1255. }
  1256. }()
  1257. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1258. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1259. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1260. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1261. for _, fsion := range fsions {
  1262. if !fsion.HasKey("parammaps") {
  1263. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1264. return
  1265. }
  1266. parammaps := fsion.Get("parammaps")
  1267. ID := parammaps.Get("ID").ValueStr()
  1268. if ID == "" {
  1269. continue
  1270. }
  1271. s_params := make([]interface{}, 0)
  1272. paramslist := strings.Split(p, ",")
  1273. if len(paramslist) > 0 && p != "" {
  1274. for _, value := range paramslist {
  1275. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1276. }
  1277. }
  1278. _, err := tx.SQL(sql, s_params...).Execute()
  1279. if err != nil {
  1280. logging.Error("PostRJSBData err: ", err)
  1281. msg := geterrmsg(err.Error())
  1282. // appG.Response(http.StatusOK, e.ERROR, msg)
  1283. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1284. return
  1285. }
  1286. s_params = make([]interface{}, 0)
  1287. paramslist = strings.Split(p1, ",")
  1288. if len(paramslist) > 0 && p1 != "" {
  1289. for _, value := range paramslist {
  1290. // if value == "ID" {
  1291. // id := parammaps.Get("ID").ValueStr()
  1292. // pastureid := parammaps.Get("pastureid").ValueStr()
  1293. // 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
  1294. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1295. // if err != nil {
  1296. // logging.Error("PostRJSBData err: ", err)
  1297. // msg := geterrmsg(err.Error())
  1298. // appG.Response(http.StatusOK, e.ERROR, msg)
  1299. // return
  1300. // }
  1301. // for _, item := range datalist {
  1302. // id = item["id"]
  1303. // }
  1304. // s_params = append(s_params, id)
  1305. // } else {
  1306. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1307. // }
  1308. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1309. }
  1310. }
  1311. _, err = tx.SQL(sql1, s_params...).Execute()
  1312. if err != nil {
  1313. logging.Error("PostRJSBData1 err: ", err)
  1314. msg := geterrmsg(err.Error())
  1315. appG.Response(http.StatusOK, e.ERROR, msg)
  1316. return
  1317. }
  1318. s_params = make([]interface{}, 0)
  1319. paramslist = strings.Split(p2, ",")
  1320. if len(paramslist) > 0 && p2 != "" {
  1321. for _, value := range paramslist {
  1322. if value == "ID" {
  1323. id := parammaps.Get("ID").ValueStr()
  1324. pastureid := parammaps.Get("pastureid").ValueStr()
  1325. 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
  1326. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1327. if err != nil {
  1328. logging.Error("PostRJSBData err: ", err)
  1329. msg := geterrmsg(err.Error())
  1330. appG.Response(http.StatusOK, e.ERROR, msg)
  1331. return
  1332. }
  1333. for _, item := range datalist {
  1334. id = item["id"]
  1335. }
  1336. s_params = append(s_params, id)
  1337. } else {
  1338. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1339. }
  1340. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1341. }
  1342. }
  1343. _, err = tx.SQL(sql2, s_params...).Execute()
  1344. if err != nil {
  1345. logging.Error("PostRJSBData2 err: ", err)
  1346. msg := geterrmsg(err.Error())
  1347. appG.Response(http.StatusOK, e.ERROR, msg)
  1348. return
  1349. }
  1350. s_params = make([]interface{}, 0)
  1351. paramslist = strings.Split(p3, ",")
  1352. if len(paramslist) > 0 && p3 != "" {
  1353. for _, value := range paramslist {
  1354. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1355. }
  1356. }
  1357. _, err = tx.SQL(sql3, s_params...).Execute()
  1358. if err != nil {
  1359. logging.Error("PostRJSBData3 err: ", err)
  1360. msg := geterrmsg(err.Error())
  1361. appG.Response(http.StatusOK, e.ERROR, msg)
  1362. return
  1363. }
  1364. // ALTER TABLE `tmr`
  1365. // ADD COLUMN `concentrate` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 未回传 1 已回传' AFTER `appoint`
  1366. projuctid := parammaps.Get("projuctid").ValueStr()
  1367. _, err = tx.SQL(`update tmr set xianfeng = 0, concentrate = (select d.id from downloadedplan d
  1368. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1369. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1370. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1371. and lpplantype in(0,1)) and ( select count(1) from downloadedplan where id = ? and iscompleted = 0 ) = 0 `,
  1372. projuctid, projuctid, projuctid, projuctid, projuctid).Execute()
  1373. if err != nil {
  1374. logging.Error("PostRJSBData-0 err: ", err)
  1375. msg := geterrmsg(err.Error())
  1376. // appG.Response(http.StatusOK, e.ERROR, msg)
  1377. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1378. return
  1379. }
  1380. count, _ := tx.SQL(`select count(1) from downloadedplan where id = ? and iscompleted = 0`, projuctid).Count()
  1381. if count == 0 {
  1382. fmt.Println(projuctid, "先锋回传计划已完成", count, err)
  1383. }
  1384. }
  1385. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1386. }
  1387. // @Summary 根据APISQL表中SQL执行得到数据集
  1388. // @Tags ExecDataByConfig
  1389. // @Accept json
  1390. // @Produce json
  1391. // @Param sqlname query string true "sqlname"
  1392. // @Param offset query int true "offset"
  1393. // @Param pagecount query int true "pagecount"
  1394. // @Param returntype query string true "returntype"
  1395. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1396. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1397. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1398. // @Router /data/PostDataByName [POST]
  1399. func ExecDataByConfig(c *gin.Context) {
  1400. appG := app.Gin{C: c}
  1401. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1402. tempval_ := make(map[string]interface{})
  1403. tempCommon := make(map[string]interface{})
  1404. tempval := make([]map[string]interface{}, 0)
  1405. err := json.Unmarshal(dataByte, &tempval_)
  1406. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1407. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1408. if err != nil {
  1409. } else {
  1410. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1411. tempCommon = v
  1412. }
  1413. if v, ok := tempval_["data"].([]interface{}); ok {
  1414. for _, Tvalue := range v {
  1415. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1416. tempval = append(tempval, v1)
  1417. }
  1418. }
  1419. }
  1420. tx := restful.Engine.NewSession()
  1421. err := tx.Begin()
  1422. if err != nil {
  1423. logging.Error("tx.Begin 事务启动失败__error:", err)
  1424. }
  1425. defer func() {
  1426. switch {
  1427. case err != nil:
  1428. if tx != nil {
  1429. tx.Rollback()
  1430. }
  1431. default:
  1432. if tx != nil {
  1433. err = tx.Commit()
  1434. }
  1435. }
  1436. if tx != nil {
  1437. tx.Close()
  1438. }
  1439. }()
  1440. if err == nil {
  1441. if tempv, exists := c.Get("jwt_username"); exists {
  1442. tempCommon["jwt_username"] = tempv.(string)
  1443. }
  1444. for _, paramvalue := range tempval {
  1445. fmt.Println(paramvalue["name"])
  1446. if paramvalue["name"].(string) == "updateBigFP" {
  1447. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1448. if err != nil {
  1449. msg := geterrmsg(err.Error())
  1450. appG.Response(http.StatusOK, e.ERROR, msg)
  1451. return
  1452. }
  1453. }
  1454. }
  1455. for _, paramvalue := range tempval {
  1456. if _, ok := paramvalue["resultname"]; !ok {
  1457. paramvalue["resultname"] = paramvalue["name"]
  1458. }
  1459. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1460. if err != nil {
  1461. logging.Error("ExecDataParam error:", err)
  1462. break
  1463. }
  1464. // if paramvalue["name"].(string) == "createdownloadedplan" {
  1465. // checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1466. // }
  1467. }
  1468. if err == nil {
  1469. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1470. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1471. } else {
  1472. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1473. }
  1474. } else {
  1475. msg := geterrmsg(err.Error())
  1476. appG.Response(http.StatusOK, e.ERROR, msg)
  1477. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1478. }
  1479. }
  1480. }
  1481. if err != nil {
  1482. msg := geterrmsg(err.Error())
  1483. appG.Response(http.StatusOK, e.ERROR, msg)
  1484. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1485. }
  1486. }
  1487. func interfacetostring(val interface{}) string {
  1488. switch val.(type) {
  1489. case string:
  1490. ss := val.(string)
  1491. return ss
  1492. break
  1493. case int:
  1494. ss := val.(int)
  1495. return strconv.Itoa(ss)
  1496. break
  1497. case int64:
  1498. ss := val.(int64)
  1499. return strconv.FormatInt(ss, 10)
  1500. break
  1501. case float64:
  1502. ss := val.(float64)
  1503. return strconv.FormatFloat(ss, 'E', -1, 32)
  1504. break
  1505. }
  1506. return ""
  1507. }
  1508. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1509. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1510. tempstrb := strings.IndexAny(valuestring, "@")
  1511. tempstre := strings.IndexAny(valuestring, ".")
  1512. if tempstrb > -1 && tempstre > -1 {
  1513. for _, ParamMapList := range ParamMap {
  1514. if v, ok := ParamMapList["resultname"]; ok {
  1515. if v == valuestring[tempstrb+1:tempstre] {
  1516. if v1, ok := ParamMapList["resultmaps"]; ok {
  1517. if newA, ok := v1.([]map[string]interface{}); ok {
  1518. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1519. } else if newA, ok := v1.(map[string]interface{}); ok {
  1520. return interfacetostring(newA[valuestring[tempstre+1:]])
  1521. }
  1522. }
  1523. }
  1524. }
  1525. }
  1526. } else {
  1527. return valuestring
  1528. }
  1529. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1530. return fmt.Sprintf("%f", valuestring)
  1531. }
  1532. return ""
  1533. }
  1534. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1535. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1536. tempstrb := strings.IndexAny(valuestring, "@")
  1537. tempstre := strings.IndexAny(valuestring, ".")
  1538. if tempstrb > -1 && tempstre > -1 {
  1539. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1540. if s, ok := v.(string); ok {
  1541. return s
  1542. } else if s, ok := v.(float64); ok {
  1543. return strconv.FormatFloat(s, 'f', -1, 64)
  1544. // return strconv.FormatInt(int64(s), 10)
  1545. }
  1546. }
  1547. }
  1548. }
  1549. return ""
  1550. }
  1551. 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) {
  1552. sqlname := fasion["name"].(string)
  1553. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1554. if v, ok := fasion["type"]; ok {
  1555. sqltype = v.(string)
  1556. }
  1557. sql := ""
  1558. p := ""
  1559. s_params := make([]interface{}, 0)
  1560. if sqltype != "" {
  1561. sql, p = restful.GetSqlByName(sqlname, tx)
  1562. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1563. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1564. paramslist := strings.Split(p, ",")
  1565. if len(paramslist) > 0 && p != "" {
  1566. for _, value := range paramslist {
  1567. ss := ""
  1568. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1569. ids, err := setting.SnowIds.NextId()
  1570. if err != nil {
  1571. ids = time.Now().UnixNano()
  1572. logging.Info("create SnowIds err", err)
  1573. }
  1574. s_params = append(s_params, ids)
  1575. } else {
  1576. if ss == "" && CommonParamMap != nil {
  1577. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1578. ss = valuestring
  1579. tempstrb := strings.IndexAny(valuestring, "@")
  1580. tempstre := strings.IndexAny(valuestring, ".")
  1581. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1582. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1583. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1584. }
  1585. } else {
  1586. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1587. ss = ""
  1588. }
  1589. }
  1590. }
  1591. }
  1592. if ss == "" && ParentParamMap != nil {
  1593. ss = getParamValue_(v, value, ParentParamMap)
  1594. }
  1595. if ss == "" && sameParamMap != nil {
  1596. ss = getParamValue(v, value, sameParamMap)
  1597. }
  1598. if ss == "" && ParamMap != nil {
  1599. ss = getParamValue(v, value, ParamMap)
  1600. }
  1601. s_params = append(s_params, ss)
  1602. }
  1603. }
  1604. }
  1605. }
  1606. }
  1607. if sql == "" {
  1608. sqltype = ""
  1609. }
  1610. if sqltype == "s1" {
  1611. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1612. if v, ok := tempValParam.(map[string]interface{}); ok {
  1613. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1614. }
  1615. if err != nil {
  1616. return nil, err
  1617. }
  1618. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1619. if err != nil {
  1620. return nil, err
  1621. }
  1622. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1623. } else if sqltype == "sm" {
  1624. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1625. if v, ok := tempValParam.(map[string]interface{}); ok {
  1626. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1627. } else {
  1628. }
  1629. if err != nil {
  1630. return nil, err
  1631. }
  1632. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1633. if err != nil {
  1634. return nil, err
  1635. }
  1636. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1637. } else if sqltype == "v" {
  1638. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1639. if v, ok := tempValParam.(map[string]interface{}); ok {
  1640. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1641. } else {
  1642. }
  1643. if err != nil {
  1644. return nil, err
  1645. }
  1646. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1647. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1648. }
  1649. } else if sqltype == "e" {
  1650. tempVal_arrary := make([]map[string]interface{}, 0)
  1651. tempVal_map := make(map[string]interface{})
  1652. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1653. if err == nil {
  1654. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1655. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1656. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1657. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1658. return tempVal_arrary, err
  1659. }
  1660. return nil, err
  1661. } else {
  1662. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1663. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1664. if err != nil {
  1665. return nil, err
  1666. }
  1667. return nil, err
  1668. }
  1669. }
  1670. return nil, nil
  1671. }
  1672. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1673. var err error
  1674. subarray, ok := fasion["children"]
  1675. if ok {
  1676. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1677. tempVal_arrary := make([]map[string]interface{}, 0)
  1678. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1679. tempVal_ := make(map[string]interface{})
  1680. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1681. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1682. } else {
  1683. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1684. }
  1685. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1686. if err != nil {
  1687. return err
  1688. }
  1689. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1690. }
  1691. v.(map[string]interface{})["children"] = tempVal_arrary
  1692. }
  1693. }
  1694. return nil
  1695. }
  1696. // @Summary 删除图片
  1697. // @Tags RemovePicByName
  1698. // @Accept json
  1699. // @Produce json
  1700. // @Param sqlname query string true "sqlname"
  1701. // @Param offset query int true "offset"
  1702. // @Param pagecount query int true "pagecount"
  1703. // @Param returntype query string true "returntype"
  1704. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1705. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1706. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1707. // @Router /data/PostDataByName [POST]
  1708. func RemovePicByName(c *gin.Context) {
  1709. logging.Info("RemovePicByName ", c.Keys)
  1710. appG := app.Gin{C: c}
  1711. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1712. fsion := gofasion.NewFasion(string(dataByte))
  1713. sqlnamestr := fsion.Get("name").ValueStr()
  1714. picname := fsion.Get("picname").ValueStr()
  1715. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1716. params := fsion.Get("params").Array()
  1717. s_params := make([]interface{}, 0)
  1718. for _, v_params := range params {
  1719. s_params = append(s_params, v_params.ValueStr())
  1720. }
  1721. if sql != "" {
  1722. queryData, err := execDataBySql(sql, s_params)
  1723. if picname != "" {
  1724. // Destination
  1725. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1726. err := os.Remove(distPath) //删除文件test.txt
  1727. if err != nil {
  1728. //如果删除失败则输出 file remove Error!
  1729. fmt.Println("file remove Error!")
  1730. //输出错误详细信息
  1731. fmt.Printf("%s", err)
  1732. } else {
  1733. //如果删除成功则输出 file remove OK!
  1734. fmt.Print("file remove OK!")
  1735. }
  1736. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1737. err = os.Remove(distPath) //删除文件test.txt
  1738. if err != nil {
  1739. //如果删除失败则输出 file remove Error!
  1740. fmt.Println("file remove Error!")
  1741. //输出错误详细信息
  1742. fmt.Printf("%s", err)
  1743. } else {
  1744. //如果删除成功则输出 file remove OK!
  1745. fmt.Print("file remove OK!")
  1746. }
  1747. }
  1748. if err != nil {
  1749. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1750. } else {
  1751. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1752. }
  1753. } else {
  1754. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1755. }
  1756. }
  1757. // @Summary 删除文件
  1758. // @Tags RemoveFileByName
  1759. // @Accept json
  1760. // @Produce json
  1761. // @Param sqlname query string true "sqlname"
  1762. // @Param offset query int true "offset"
  1763. // @Param pagecount query int true "pagecount"
  1764. // @Param returntype query string true "returntype"
  1765. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1766. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1767. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1768. // @Router /data/PostDataByName [POST]
  1769. func RemoveFileByName(c *gin.Context) {
  1770. appG := app.Gin{C: c}
  1771. id := c.Param("id")
  1772. logging.Info("DownloadFile ", c.Keys, id)
  1773. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1774. if eqdoc == nil {
  1775. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1776. return
  1777. }
  1778. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1779. err = os.Remove(distPath) //删除文件test.txt
  1780. if err != nil {
  1781. //如果删除失败则输出 file remove Error!
  1782. fmt.Println("file remove Error!")
  1783. //输出错误详细信息
  1784. fmt.Printf("%s", err)
  1785. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1786. return
  1787. }
  1788. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1789. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1790. }
  1791. // @Summary 根据APISQL表中SQL执行得到数据集
  1792. // @Tags PostDataByName
  1793. // @Accept json
  1794. // @Produce json
  1795. // @Param sqlname query string true "sqlname"
  1796. // @Param offset query int true "offset"
  1797. // @Param pagecount query int true "pagecount"
  1798. // @Param returntype query string true "returntype"
  1799. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1800. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1801. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1802. // @Router /data/PostDataByName [POST]
  1803. func UpdateDataRelation(c *gin.Context) {
  1804. appG := app.Gin{C: c}
  1805. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1806. fsion := gofasion.NewFasion(string(dataByte))
  1807. tablename := fsion.Get("name").ValueStr()
  1808. dataname := fsion.Get("dataname").ValueStr()
  1809. datavalue := fsion.Get("datavalue").ValueStr()
  1810. valuename := fsion.Get("valuename").ValueStr()
  1811. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1812. values := fsion.Get("values").Array()
  1813. tx := restful.Engine.NewSession()
  1814. err := tx.Begin()
  1815. defer func() {
  1816. switch {
  1817. case err != nil:
  1818. if tx != nil {
  1819. tx.Rollback()
  1820. }
  1821. default:
  1822. if tx != nil {
  1823. err = tx.Commit()
  1824. }
  1825. }
  1826. if tx != nil {
  1827. tx.Close()
  1828. }
  1829. }()
  1830. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1831. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1832. d_params := make([]interface{}, 4)
  1833. d_params[0] = datavalue
  1834. s_params := ""
  1835. for _, v_values := range values {
  1836. d_params[1] = v_values.ValueStr()
  1837. if s_params == "" {
  1838. s_params = v_values.ValueStr()
  1839. } else {
  1840. s_params = s_params + "," + v_values.ValueStr()
  1841. }
  1842. d_params[2] = d_params[1]
  1843. d_params[3] = d_params[0]
  1844. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1845. if err != nil {
  1846. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1847. break
  1848. }
  1849. }
  1850. if s_params != "" {
  1851. deleteSqlstr := "delete from " + tablename + " " +
  1852. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1853. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1854. if err != nil {
  1855. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1856. } else if err == nil {
  1857. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1858. }
  1859. } else {
  1860. deleteSqlstr := "delete from " + tablename + " " +
  1861. " where " + dataname + " = " + datavalue
  1862. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1863. if err != nil {
  1864. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1865. } else if err == nil {
  1866. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1867. }
  1868. }
  1869. }
  1870. // @Summary 根据APISQL表中SQL执行得到数据集
  1871. // @Tags PostDatasByName
  1872. // @Accept json
  1873. // @Produce json
  1874. // @Param sqlname query string true "sqlname"
  1875. // @Param offset query int true "offset"
  1876. // @Param pagecount query int true "pagecount"
  1877. // @Param returntype query string true "returntype"
  1878. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1879. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1880. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1881. // @Router /data/PostDatasByName [POST]
  1882. func PostDataByNames(c *gin.Context) {
  1883. appG := app.Gin{C: c}
  1884. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1885. fsion := gofasion.NewFasion(string(dataByte))
  1886. sqlParams := fsion.Get("array").Array()
  1887. queryData := make(map[string]interface{})
  1888. for _, v := range sqlParams {
  1889. fsion2 := gofasion.NewFasion(v.Json())
  1890. ss := fsion2.Get("name")
  1891. aa := fsion2.Get("params")
  1892. fmt.Println(ss, aa)
  1893. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1894. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1895. if sql == "" {
  1896. errorm := make(map[string]interface{})
  1897. errorm["code"] = e.ERROR
  1898. errorm["message"] = "sql没有找到"
  1899. errorm["param"] = ""
  1900. queryData[fsion2.Get("name").ValueStr()] = errorm
  1901. continue
  1902. } else if sql != "" {
  1903. s_params := make([]interface{}, 0)
  1904. if fsion2.HasKey("parammaps") {
  1905. parammaps := fsion2.Get("parammaps")
  1906. paramslist := strings.Split(p, ",")
  1907. if len(paramslist) > 0 && p != "" {
  1908. for _, value := range paramslist {
  1909. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1910. if tempv, exists := c.Get("jwt_username"); exists {
  1911. s_params = append(s_params, tempv.(string))
  1912. } else {
  1913. s_params = append(s_params, "")
  1914. }
  1915. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1916. ids, err := setting.SnowIds.NextId()
  1917. if err != nil {
  1918. ids = time.Now().UnixNano()
  1919. logging.Info("create SnowIds err", err)
  1920. }
  1921. s_params = append(s_params, ids)
  1922. } else {
  1923. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1924. }
  1925. }
  1926. }
  1927. } else if fsion2.HasKey("params") {
  1928. params := fsion2.Get("params").Array()
  1929. //ids,err := setting.SnowIds.NextId()
  1930. //if err !=nil{
  1931. // ids = time.Now().UnixNano()
  1932. // logging.Info("create SnowIds err",err)
  1933. //}
  1934. //s_params = append(s_params, ids)
  1935. for _, v_params := range params {
  1936. s_params = append(s_params, v_params.ValueStr())
  1937. }
  1938. }
  1939. _, err := execDataBySql(sql, s_params)
  1940. if err != nil {
  1941. logging.Error("PostDataByName err: ", err)
  1942. errorm := make(map[string]interface{})
  1943. errorm["code"] = e.ERROR
  1944. errorm["message"] = err.Error()
  1945. errorm["param"] = s_params
  1946. queryData[fsion2.Get("name").ValueStr()] = errorm
  1947. continue
  1948. } else {
  1949. errorm := make(map[string]interface{})
  1950. errorm["code"] = e.SUCCESS
  1951. errorm["message"] = "success"
  1952. queryData[fsion2.Get("name").ValueStr()] = errorm
  1953. continue
  1954. }
  1955. } else {
  1956. errorm := make(map[string]interface{})
  1957. errorm["code"] = e.ERROR
  1958. errorm["message"] = "NO SQL"
  1959. errorm["param"] = ""
  1960. queryData[fsion2.Get("name").ValueStr()] = errorm
  1961. }
  1962. }
  1963. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1964. }
  1965. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1966. if offset > 0 {
  1967. offset = offset - 1
  1968. }
  1969. //if pagecount == 0 {
  1970. // pagecount = setting.AppSetting.PageSize
  1971. //}else if pagecount>setting.AppSetting.PageSize{
  1972. // pagecount = setting.AppSetting.PageSize
  1973. //}
  1974. if returntype == "list" {
  1975. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1976. return queryData, err
  1977. } else if returntype == "listlist" {
  1978. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1979. return queryData, err
  1980. } else {
  1981. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1982. return queryData, err
  1983. }
  1984. }
  1985. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1986. if offset > 0 {
  1987. offset = offset - 1
  1988. }
  1989. //if pagecount == 0 {
  1990. // pagecount = setting.AppSetting.PageSize
  1991. //}else if pagecount>setting.AppSetting.PageSize{
  1992. // pagecount = setting.AppSetting.PageSize
  1993. //}
  1994. if returntype == "list" {
  1995. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1996. return queryData, err
  1997. } else if returntype == "listlist" {
  1998. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1999. return queryData, err
  2000. } else {
  2001. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  2002. return queryData, err
  2003. }
  2004. }
  2005. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  2006. paramslist := strings.Split(Params, ",")
  2007. s_params := make([]interface{}, 0)
  2008. if isList {
  2009. for _, v_params := range thisParams["params"].([]interface{}) {
  2010. s_params = append(s_params, v_params)
  2011. }
  2012. } else {
  2013. paramslist := strings.Split(Params, ",")
  2014. if len(paramslist) > 0 && Params != "" {
  2015. for _, value := range paramslist {
  2016. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2017. }
  2018. }
  2019. }
  2020. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  2021. for _, queryData_ := range queryData {
  2022. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  2023. if isList {
  2024. if queryData_[idname] != nil {
  2025. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  2026. }
  2027. } else {
  2028. if queryData_[idname] != nil {
  2029. thisParams[idname] = queryData_[idname].(interface{})
  2030. }
  2031. if len(paramslist) > 0 && Params != "" {
  2032. s_params = make([]interface{}, 0)
  2033. for _, value := range paramslist {
  2034. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2035. }
  2036. }
  2037. }
  2038. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  2039. } else {
  2040. }
  2041. }
  2042. return queryData, err
  2043. }
  2044. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2045. queryData, err := restful.ExecQuery(sqlstr, params)
  2046. return queryData, err
  2047. }
  2048. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2049. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2050. return queryData, err
  2051. }
  2052. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2053. queryData, err := restful.ExecQuery(sqlstr, params)
  2054. return queryData, err
  2055. }
  2056. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2057. // @Tags ImportExcel
  2058. // @Accept json
  2059. // @Produce json
  2060. // @Param file query string true "文件名"
  2061. // @Param name header string true "执行sql的名字"
  2062. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2063. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2064. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2065. // @Router /data/ImportExcel [POST]
  2066. func ImportExcel(c *gin.Context) {
  2067. appG := app.Gin{C: c}
  2068. inputdata := ""
  2069. c.Request.ParseForm()
  2070. params := c.Request.Form
  2071. file, _, err := c.Request.FormFile("file")
  2072. if err != nil {
  2073. appG.Response(http.StatusOK, e.ERROR, err)
  2074. return
  2075. }
  2076. sqlnamestrs := params.Get("name")
  2077. sheetname := params.Get("sheetname")
  2078. pastureid := params.Get("pastureid")
  2079. //importParams := params.Get("importParams")
  2080. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2081. // 必输项参数 (字符串格式 "field1,field2,field3")
  2082. requiredParams := params.Get("requiredParams")
  2083. // 日期参数
  2084. dateParams := params.Get("dateParams")
  2085. // 数字参数
  2086. numParams := params.Get("numParams")
  2087. //将字符串分割开
  2088. dateParamslist := strings.Split(dateParams, ",")
  2089. requiredParamslist := strings.Split(requiredParams, ",")
  2090. numParamslist := strings.Split(numParams, ",")
  2091. queryData := make([]interface{}, 0)
  2092. sqlslist := strings.Split(sqlnamestrs, ",")
  2093. xlsx1, err := excelize.OpenReader(file)
  2094. if err != nil {
  2095. fmt.Println(err)
  2096. return
  2097. }
  2098. ok := 0
  2099. error := 0
  2100. isdone := true
  2101. rows := xlsx1.GetRows(sheetname)
  2102. // 限制10000条,多余的截取掉
  2103. if len(rows) > 10000 {
  2104. rows = rows[:10000]
  2105. }
  2106. for i, row := range rows {
  2107. if i > 0 {
  2108. entry := make(map[string]interface{})
  2109. outentry := make(map[string]interface{})
  2110. for j, colCell := range rows[0] {
  2111. for k, colCell1 := range row {
  2112. if j == k {
  2113. outentry[colCell] = colCell1
  2114. entry[colCell] = colCell1
  2115. }
  2116. }
  2117. }
  2118. inputdata = ""
  2119. a := ""
  2120. fmt.Println(outentry, entry)
  2121. //校验日期格式
  2122. for _, v := range dateParamslist {
  2123. if v == "" {
  2124. continue
  2125. }
  2126. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2127. dtime, err := TransfTime(d.(string))
  2128. if err != nil {
  2129. a = strings.Trim(v, " ")
  2130. break
  2131. }
  2132. outentry[strings.Trim(v, " ")] = dtime
  2133. }
  2134. }
  2135. if a != "" {
  2136. outentry["error_msg"] = a + " 格式错误"
  2137. error++
  2138. queryData = append(queryData, outentry)
  2139. continue
  2140. }
  2141. a = ""
  2142. //校验必填格式
  2143. for _, v := range requiredParamslist {
  2144. if v == "" {
  2145. continue
  2146. }
  2147. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2148. a = strings.Trim(v, " ")
  2149. break
  2150. }
  2151. }
  2152. if a != "" {
  2153. outentry["error_msg"] = a + " 未填或格式错误"
  2154. error++
  2155. queryData = append(queryData, outentry)
  2156. continue
  2157. }
  2158. a = ""
  2159. //校验数字格式
  2160. for _, v := range numParamslist {
  2161. if v == "" {
  2162. continue
  2163. }
  2164. d, ok := outentry[strings.Trim(v, " ")]
  2165. if !ok || d == "" {
  2166. outentry[strings.Trim(v, " ")] = 0
  2167. } else {
  2168. var fl float64
  2169. switch d.(type) {
  2170. case string:
  2171. fl, err = strconv.ParseFloat(d.(string), 64)
  2172. }
  2173. if err != nil || fl < 0 {
  2174. a = strings.Trim(v, " ")
  2175. break
  2176. }
  2177. }
  2178. }
  2179. if a != "" {
  2180. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2181. error++
  2182. queryData = append(queryData, outentry)
  2183. continue
  2184. }
  2185. tx := restful.Engine.NewSession()
  2186. err := tx.Begin()
  2187. for _, sqlnamestr := range sqlslist {
  2188. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2189. paramslist := strings.Split(paramslists, ",")
  2190. if len(paramslist) > 0 {
  2191. s_params := make([]interface{}, 0)
  2192. for _, value := range paramslist {
  2193. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2194. if tempv, exists := c.Get("jwt_username"); exists {
  2195. s_params = append(s_params, tempv.(string))
  2196. } else {
  2197. s_params = append(s_params, "")
  2198. }
  2199. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2200. s_params = append(s_params, pastureid)
  2201. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2202. ids, err := setting.SnowIds.NextId()
  2203. if err != nil {
  2204. ids = time.Now().UnixNano()
  2205. logging.Info("create SnowIds err", err)
  2206. }
  2207. s_params = append(s_params, ids)
  2208. } else {
  2209. if outentry[strings.Trim(value, " ")] == nil {
  2210. s_params = append(s_params, "")
  2211. } else {
  2212. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2213. }
  2214. }
  2215. }
  2216. outentry["input"] = inputdata
  2217. fmt.Println(sql, s_params)
  2218. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2219. if err != nil {
  2220. if tx != nil {
  2221. tx.Rollback()
  2222. }
  2223. if tx != nil {
  2224. tx.Close()
  2225. }
  2226. msg := geterrmsg(err.Error())
  2227. outentry["error_msg"] = msg
  2228. error++
  2229. queryData = append(queryData, outentry)
  2230. isdone = true
  2231. break
  2232. } else {
  2233. if len(returnmsgmap1) > 0 {
  2234. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2235. if tx != nil {
  2236. tx.Rollback()
  2237. }
  2238. if tx != nil {
  2239. tx.Close()
  2240. }
  2241. msg := geterrmsg(va.(string))
  2242. outentry["error_msg"] = msg
  2243. error++
  2244. queryData = append(queryData, outentry)
  2245. isdone = true
  2246. break
  2247. }
  2248. }
  2249. isdone = false
  2250. }
  2251. }
  2252. }
  2253. switch {
  2254. case err != nil:
  2255. if tx != nil {
  2256. tx.Rollback()
  2257. }
  2258. default:
  2259. if tx != nil {
  2260. err = tx.Commit()
  2261. }
  2262. }
  2263. if tx != nil {
  2264. tx.Close()
  2265. }
  2266. }
  2267. if !isdone {
  2268. ok++
  2269. isdone = true
  2270. }
  2271. }
  2272. data := make(map[string]interface{})
  2273. data["result"] = queryData
  2274. data["success"] = ok
  2275. data["err_count"] = error
  2276. appG.Response(http.StatusOK, e.SUCCESS, data)
  2277. }
  2278. func TransfTime(timestr string) (string, error) {
  2279. if timestr == "" {
  2280. return time.Now().Format("2006-01-02"), nil
  2281. }
  2282. days, err := strconv.Atoi(timestr)
  2283. if err != nil {
  2284. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2285. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2286. }
  2287. _, err := time.Parse("2006-01-02", timestr)
  2288. if err != nil {
  2289. t, err := time.Parse("2006/01/02", timestr)
  2290. if err != nil {
  2291. t, err := time.Parse("2006.01.02", timestr)
  2292. if err != nil {
  2293. return "", err
  2294. } else {
  2295. return t.Format("2006-01-02"), nil
  2296. }
  2297. } else {
  2298. return t.Format("2006-01-02"), nil
  2299. }
  2300. } else {
  2301. return timestr, nil
  2302. }
  2303. }
  2304. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2305. times = times.AddDate(0, 0, days)
  2306. return times.Format("2006-01-02"), nil
  2307. }
  2308. func Createchart(c *gin.Context) {
  2309. appG := app.Gin{C: c}
  2310. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2311. fsion := gofasion.NewFasion(string(dataByte))
  2312. chart_name := fsion.Get("chart_name").ValueStr()
  2313. desc := fsion.Get("desc").ValueStr()
  2314. pastureid := fsion.Get("pastureid").ValueStr()
  2315. source_id := fsion.Get("source_id").ValueStr()
  2316. emp := fsion.Get("emp").ValueStr()
  2317. content := fsion.Get("content").Json()
  2318. var mapResult map[string]interface{}
  2319. err1 := json.Unmarshal([]byte(content), &mapResult)
  2320. if err1 != nil {
  2321. fmt.Println("JsonToMapDemo err: ", err1)
  2322. }
  2323. tx := restful.Engine.NewSession()
  2324. err := tx.Begin()
  2325. defer func() {
  2326. switch {
  2327. case err != nil:
  2328. logging.Error("tx.Begin 事务启动失败__error:", err)
  2329. if tx != nil {
  2330. tx.Rollback()
  2331. }
  2332. default:
  2333. if tx != nil {
  2334. err = tx.Commit()
  2335. }
  2336. }
  2337. if tx != nil {
  2338. tx.Close()
  2339. }
  2340. }()
  2341. ids, err := setting.SnowIds.NextId()
  2342. if err != nil {
  2343. ids = time.Now().UnixNano()
  2344. logging.Info("create SnowIds err", err)
  2345. }
  2346. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2347. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2348. if err != nil {
  2349. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2350. } else {
  2351. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2352. }
  2353. }
  2354. func Updatedashboard(c *gin.Context) {
  2355. appG := app.Gin{C: c}
  2356. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2357. fsion := gofasion.NewFasion(string(dataByte))
  2358. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2359. pastureid := fsion.Get("pastureid").ValueStr()
  2360. content := fsion.Get("content").Json()
  2361. var mapResult map[string]interface{}
  2362. err1 := json.Unmarshal([]byte(content), &mapResult)
  2363. if err1 != nil {
  2364. fmt.Println("JsonToMapDemo err: ", err1)
  2365. }
  2366. layout := mapResult["layout"]
  2367. tx := restful.Engine.NewSession()
  2368. err := tx.Begin()
  2369. defer func() {
  2370. switch {
  2371. case err != nil:
  2372. logging.Error("tx.Begin 事务启动失败__error:", err)
  2373. if tx != nil {
  2374. tx.Rollback()
  2375. }
  2376. default:
  2377. if tx != nil {
  2378. err = tx.Commit()
  2379. }
  2380. }
  2381. if tx != nil {
  2382. tx.Close()
  2383. }
  2384. }()
  2385. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2386. if err != nil {
  2387. println("2", err.Error())
  2388. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2389. } else {
  2390. if exec != nil {
  2391. if exec[0]["content"] == nil {
  2392. mapR := make(map[string]interface{})
  2393. mapR["layout"] = layout
  2394. mjson, _ := json.Marshal(mapR)
  2395. mString := string(mjson)
  2396. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2397. if err3 != nil {
  2398. println("3", err3.Error())
  2399. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2400. } else {
  2401. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2402. }
  2403. } else {
  2404. var mapR map[string]interface{}
  2405. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2406. if err1 != nil {
  2407. fmt.Println("JsonToMapDemo err: ", err2)
  2408. }
  2409. mapR["layout"] = layout
  2410. mjson, _ := json.Marshal(mapR)
  2411. mString := string(mjson)
  2412. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2413. if err3 != nil {
  2414. println("3", err3.Error())
  2415. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2416. } else {
  2417. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2418. }
  2419. }
  2420. } else {
  2421. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2422. }
  2423. }
  2424. }
  2425. func ExecSQL(c *gin.Context) {
  2426. appG := app.Gin{C: c}
  2427. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2428. fsion := gofasion.NewFasion(string(dataByte))
  2429. content := fsion.Get("content").Json()
  2430. pastureid := fsion.Get("pastureid").ValueStr()
  2431. var mapResult map[string]interface{}
  2432. err1 := json.Unmarshal([]byte(content), &mapResult)
  2433. if err1 != nil {
  2434. fmt.Println("JsonToMapDemo err: ", err1)
  2435. }
  2436. sqlstr := "select "
  2437. groupstr := " GROUP BY "
  2438. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2439. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2440. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2441. }
  2442. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2443. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2444. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2445. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2446. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2447. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2448. sqlstr = sqlstr + tem + ","
  2449. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2450. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2451. sqlstr = sqlstr + tem + ","
  2452. } else {
  2453. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2454. sqlstr = sqlstr + tem + ","
  2455. }
  2456. }
  2457. if _, ok := mapResult["selectedCalcul2"]; ok {
  2458. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2459. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2460. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2461. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2462. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2463. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2464. sqlstr = sqlstr + tem + ","
  2465. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2466. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2467. sqlstr = sqlstr + tem + ","
  2468. } else {
  2469. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2470. sqlstr = sqlstr + tem + ","
  2471. }
  2472. }
  2473. }
  2474. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2475. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2476. sqlstr = sqlstr + " where pastureid=" + pastureid
  2477. if len(mapResult["filters"].([]interface{})) > 0 {
  2478. sqlstr = sqlstr + " and "
  2479. }
  2480. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2481. for _, value := range mapResult["filters"].([]interface{}) {
  2482. switch value.(map[string]interface{})["filterOperator"].(string) {
  2483. case ">", "=", "<", ">=", "<=", "!=", "like":
  2484. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + value.(map[string]interface{})["filterOperator"].(string) + " " + value.(map[string]interface{})["value"].(map[string]interface{})["value1"].(string) + " AND "
  2485. case "IN":
  2486. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2487. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2488. sqlstr = sqlstr + value1.(string) + ","
  2489. }
  2490. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2491. sqlstr = sqlstr + ")" + " AND "
  2492. case "BETWEEN":
  2493. 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 "
  2494. }
  2495. }
  2496. if len(mapResult["filters"].([]interface{})) > 0 {
  2497. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2498. }
  2499. //
  2500. groupstr = groupstr[0 : len(groupstr)-1]
  2501. sqlstr = sqlstr + groupstr + " "
  2502. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2503. sqlstr = sqlstr + " order by "
  2504. }
  2505. //
  2506. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2507. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2508. sqlstr = sqlstr + value.(string) + " "
  2509. } else {
  2510. sqlstr = sqlstr + value.(string) + ","
  2511. }
  2512. }
  2513. //
  2514. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2515. tx := restful.Engine.NewSession()
  2516. err := tx.Begin()
  2517. defer func() {
  2518. switch {
  2519. case err != nil:
  2520. logging.Error("tx.Begin 事务启动失败__error:", err)
  2521. if tx != nil {
  2522. tx.Rollback()
  2523. }
  2524. default:
  2525. if tx != nil {
  2526. err = tx.Commit()
  2527. }
  2528. }
  2529. if tx != nil {
  2530. tx.Close()
  2531. }
  2532. }()
  2533. exec, err := tx.SQL(sqlstr).Query().List()
  2534. if err != nil {
  2535. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2536. } else {
  2537. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2538. }
  2539. }
  2540. func Dashboards(c *gin.Context) {
  2541. appG := app.Gin{C: c}
  2542. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2543. fsion := gofasion.NewFasion(string(dataByte))
  2544. sqlnamestr := fsion.Get("name").ValueStr()
  2545. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2546. offset := fsion.Get("offset").ValueDefaultInt(0)
  2547. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2548. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2549. month := fsion.Get("month").ValueDefaultStr("map")
  2550. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2551. tx := restful.Engine.NewSession()
  2552. err := tx.Begin()
  2553. defer func() {
  2554. switch {
  2555. case err != nil:
  2556. if tx != nil {
  2557. tx.Rollback()
  2558. }
  2559. default:
  2560. if tx != nil {
  2561. err = tx.Commit()
  2562. }
  2563. }
  2564. if tx != nil {
  2565. tx.Close()
  2566. }
  2567. }()
  2568. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2569. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2570. if sql != "" {
  2571. s_params := make([]interface{}, 0)
  2572. if fsion.HasKey("parammaps") {
  2573. parammaps := fsion.Get("parammaps")
  2574. paramslist := strings.Split(p, ",")
  2575. if len(paramslist) > 0 && p != "" {
  2576. for _, value := range paramslist {
  2577. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2578. if tempv, exists := c.Get("jwt_username"); exists {
  2579. s_params = append(s_params, tempv.(string))
  2580. } else {
  2581. s_params = append(s_params, "")
  2582. }
  2583. } else {
  2584. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2585. }
  2586. }
  2587. }
  2588. }
  2589. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2590. if err != nil {
  2591. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2592. } else {
  2593. //paramslist1 := strings.Split(p1, ",")
  2594. dids := make([]interface{}, 0)
  2595. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2596. var mapResult map[string]interface{}
  2597. dids = append(dids, value["dashboard_id"])
  2598. if value["content"] != nil {
  2599. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2600. if err1 != nil {
  2601. println("JsonToMapDemo1 err: ", err1)
  2602. }
  2603. temap := make(map[string]interface{})
  2604. tem := mapResult["layout"].([]interface{})
  2605. if v, ok := value["chartids"]; ok {
  2606. chartids := strings.Split(v.(string), ",")
  2607. for _, va := range chartids {
  2608. a := false
  2609. for _, v2 := range tem {
  2610. if v2.(map[string]interface{})["id"].(string) == va {
  2611. a = true
  2612. //println("va1======",va)
  2613. }
  2614. }
  2615. if !a {
  2616. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2617. va + "\",\"id\":\"" + va +
  2618. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2619. var mapTem map[string]interface{}
  2620. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2621. if err1 != nil {
  2622. println("JsonToMapDemo err: ", err1)
  2623. }
  2624. tem = append(tem, mapTem)
  2625. }
  2626. }
  2627. temap["layout"] = tem
  2628. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2629. }
  2630. } else {
  2631. temap := make(map[string]interface{})
  2632. tem := make([]interface{}, 0)
  2633. if v, ok := value["chartids"]; ok {
  2634. chartids := strings.Split(v.(string), ",")
  2635. for _, va := range chartids {
  2636. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2637. va + "\",\"id\":\"" + va +
  2638. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2639. var mapTem map[string]interface{}
  2640. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2641. if err1 != nil {
  2642. println("JsonToMapDemo err: ", err1)
  2643. }
  2644. tem = append(tem, mapTem)
  2645. }
  2646. temap["layout"] = tem
  2647. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2648. }
  2649. }
  2650. }
  2651. queryData.(map[string]interface{})["order"] = dids
  2652. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2653. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2654. }
  2655. } else {
  2656. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2657. }
  2658. }
  2659. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2660. fsion := gofasion.NewFasion(parammaps)
  2661. sqlnamestr := fsion.Get("name").ValueStr()
  2662. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2663. offset := fsion.Get("offset").ValueDefaultInt(0)
  2664. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2665. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2666. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2667. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2668. body := []byte("")
  2669. if sql != "" {
  2670. s_params := make([]interface{}, 0)
  2671. if fsion.HasKey("parammaps") {
  2672. parammaps := fsion.Get("parammaps")
  2673. paramslist := strings.Split(p, ",")
  2674. if len(paramslist) > 0 && p != "" {
  2675. for _, value := range paramslist {
  2676. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2677. }
  2678. }
  2679. }
  2680. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2681. if err != nil {
  2682. } else {
  2683. paramslist1 := strings.Split(p1, ",")
  2684. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2685. s_params1 := make([]interface{}, 0)
  2686. if len(paramslist1) > 0 && p1 != "" {
  2687. for _, v := range paramslist1 {
  2688. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2689. }
  2690. }
  2691. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2692. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2693. body, _ = json.Marshal(queryData)
  2694. }
  2695. }
  2696. }
  2697. bs := bytes.NewBuffer(body)
  2698. client := &http.Client{}
  2699. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2700. req, err := http.NewRequest(RequestMethod,
  2701. url,
  2702. bs,
  2703. )
  2704. if err != nil {
  2705. }
  2706. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2707. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2708. if err != nil {
  2709. // handle error
  2710. }
  2711. resp, err := client.Do(req)
  2712. if err != nil {
  2713. return ""
  2714. }
  2715. defer resp.Body.Close()
  2716. result_body, err := ioutil.ReadAll(resp.Body)
  2717. if err != nil {
  2718. return ""
  2719. }
  2720. fmt.Println(string(result_body))
  2721. return ""
  2722. }
  2723. func GetSummary(c *gin.Context) {
  2724. appG := app.Gin{C: c}
  2725. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2726. fsion := gofasion.NewFasion(string(dataByte))
  2727. offset := fsion.Get("offset").ValueDefaultInt(0)
  2728. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2729. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2730. parammaps := fsion.Get("parammaps")
  2731. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2732. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2733. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2734. tx := restful.Engine.NewSession()
  2735. defer tx.Close()
  2736. sqlnamestr := ""
  2737. if genre == "0" {
  2738. if status == "0" {
  2739. sqlnamestr = "getAccuracyJSY"
  2740. } else if status == "1" {
  2741. sqlnamestr = "getAccuracyHFT"
  2742. } else if status == "2" {
  2743. sqlnamestr = "getAccuracyHNS"
  2744. } else if status == "3" {
  2745. sqlnamestr = "getAccuracyHSC"
  2746. } else if status == "4" {
  2747. sqlnamestr = "getAccuracyHCC"
  2748. } else if status == "5" {
  2749. sqlnamestr = "getAccuracyMC"
  2750. } else if status == "6" {
  2751. sqlnamestr = "getAccuracyFeedHL"
  2752. } else if status == "7" {
  2753. sqlnamestr = "getAccuracyRT"
  2754. }
  2755. } else {
  2756. if status == "0" {
  2757. sqlnamestr = "getAccuracySCCJSY"
  2758. } else if status == "1" {
  2759. sqlnamestr = "getAccuracySFT"
  2760. } else if status == "2" {
  2761. sqlnamestr = "getAccuracySNS"
  2762. } else if status == "3" {
  2763. sqlnamestr = "getAccuracySSC"
  2764. } else if status == "4" {
  2765. sqlnamestr = "getAccuracySCC"
  2766. } else if status == "5" {
  2767. sqlnamestr = "getAccuracySLCL"
  2768. } else if status == "7" {
  2769. sqlnamestr = "getAccuracySCCRT"
  2770. }
  2771. }
  2772. if isDate == "1" {
  2773. sqlnamestr += "Date"
  2774. }
  2775. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2776. // fmt.Println(sqlnamestr, sql)
  2777. if sql != "" {
  2778. s_params := make([]interface{}, 0)
  2779. // if fsion.HasKey("parammaps") {
  2780. fmt.Println(s_params, "222", p)
  2781. paramslist := strings.Split(p, ",")
  2782. if len(paramslist) > 0 && p != "" {
  2783. for _, value := range paramslist {
  2784. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2785. if tempv, exists := c.Get("jwt_username"); exists {
  2786. s_params = append(s_params, tempv.(string))
  2787. } else {
  2788. s_params = append(s_params, "")
  2789. }
  2790. } else {
  2791. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2792. }
  2793. }
  2794. }
  2795. if returntype == "xlsx" {
  2796. var xlsxfile *xlsx.File
  2797. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2798. //c.File("c:/dd.xlsx")
  2799. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2800. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2801. c.Header("Content-Transfer-Encoding", "binary")
  2802. _ = xlsxfile.Write(c.Writer)
  2803. } else {
  2804. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2805. if err != nil {
  2806. logging.Error("GetDataByName err: ", err)
  2807. msg := geterrmsg(err.Error())
  2808. appG.Response(http.StatusOK, e.ERROR, msg)
  2809. } else {
  2810. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2811. }
  2812. }
  2813. } else {
  2814. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2815. }
  2816. }
  2817. // type lpplanStruct struct {
  2818. // Id int64 `xorm:"id"`
  2819. // Tmrname string `xorm:"tmrname"`
  2820. // Tmrid int64 `xorm:"tmrid"`
  2821. // Sort int64 `xorm:"sort"`
  2822. // Sel int64 `xorm:"sel"`
  2823. // Times int64 `xorm:"times"`
  2824. // Ftname string `xorm:"ftname"`
  2825. // Ftid int64 `xorm:"ftid"`
  2826. // Maxweight float64 `xorm:"maxweight"`
  2827. // Sumweight float64 `xorm:"sumweight"`
  2828. // Sumcowcount int64 `xorm:"sumcowcount"`
  2829. // Pastureid string `xorm:"pastureid"`
  2830. // Display string `xorm:"display"`
  2831. // Issplit int64 `xorm:"issplit"`
  2832. // BeginTime string `xorm:"begintime"`
  2833. // }
  2834. func UpdateFTdetail(c *gin.Context) {
  2835. appG := app.Gin{C: c}
  2836. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2837. tempval_ := make(map[string]interface{})
  2838. tempCommon := make(map[string]interface{})
  2839. tempval := make([]map[string]interface{}, 0)
  2840. fTChange := make(map[string]interface{}, 0)
  2841. // fpdOldDataList := make([]map[string]interface{}, 0)
  2842. // fpdDataList := make([]map[string]interface{}, 0)
  2843. fsion := gofasion.NewFasion(string(dataByte))
  2844. // parammaps := fsion.Get("parammaps")
  2845. createdate := time.Now().Format("2006-01-02 15:04:05")
  2846. err := json.Unmarshal(dataByte, &tempval_)
  2847. if err != nil {
  2848. appG.Response(http.StatusOK, e.ERROR, false)
  2849. return
  2850. }
  2851. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2852. tx := restful.Engine.NewSession()
  2853. if v, ok := tempval_["data"].([]interface{}); ok {
  2854. for _, Tvalue := range v {
  2855. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2856. if v1["name"] == "updateFPbyFTChange" {
  2857. fTChange = v1
  2858. continue
  2859. }
  2860. tempval = append(tempval, v1)
  2861. }
  2862. }
  2863. }
  2864. parammaps := fTChange["parammaps"].(map[string]interface{})
  2865. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2866. // if err != nil {
  2867. // logs.Error(err)
  2868. // appG.Response(http.StatusOK, e.ERROR, false)
  2869. // return
  2870. // }
  2871. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2872. // if err != nil {
  2873. // logs.Error(err)
  2874. // appG.Response(http.StatusOK, e.ERROR, false)
  2875. // return
  2876. // }
  2877. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2878. // if err != nil {
  2879. // logs.Error(err)
  2880. // appG.Response(http.StatusOK, e.ERROR, false)
  2881. // return
  2882. // }
  2883. err = tx.Begin()
  2884. if err != nil {
  2885. logging.Error("tx.Begin 事务启动失败__error:", err)
  2886. }
  2887. defer func() {
  2888. if err != nil {
  2889. if tx != nil {
  2890. tx.Rollback()
  2891. }
  2892. }
  2893. if tx != nil {
  2894. tx.Close()
  2895. }
  2896. }()
  2897. if err != nil {
  2898. } else {
  2899. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2900. tempCommon = v
  2901. }
  2902. // 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 ,
  2903. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2904. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2905. // UNION
  2906. // 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 ,
  2907. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2908. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2909. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2910. if err == nil {
  2911. if tempv, exists := c.Get("jwt_username"); exists {
  2912. tempCommon["jwt_username"] = tempv.(string)
  2913. }
  2914. for _, paramvalue := range tempval {
  2915. if _, ok := paramvalue["resultname"]; !ok {
  2916. paramvalue["resultname"] = paramvalue["name"]
  2917. }
  2918. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2919. if err != nil {
  2920. logging.Error("ExecDataParam error:", err)
  2921. break
  2922. }
  2923. }
  2924. if err != nil {
  2925. msg := geterrmsg(err.Error())
  2926. appG.Response(http.StatusOK, e.ERROR, msg)
  2927. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2928. }
  2929. }
  2930. }
  2931. tx.Commit()
  2932. // go func() {
  2933. if fTChange != nil {
  2934. parammaps := fTChange["parammaps"].(map[string]interface{})
  2935. if parammaps["type"].(float64) == 1 {
  2936. _, err = tx.SQL(`UPDATE feedp fp
  2937. set
  2938. ccountratio = ccount *(ratio /100 ),
  2939. fp.ftweight= IFNULL(IF(
  2940. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2941. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2942. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2943. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2944. ),0),fp.feedweight = IFNULL(IF(
  2945. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2946. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2947. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2948. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2949. ),0) +ifnull(fp.supplyweight,0)
  2950. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2951. _, err = tx.SQL(`UPDATE fpdetail fpd
  2952. INNER JOIN feedp fp
  2953. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2954. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2955. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2956. } else {
  2957. _, err = tx.SQL(`UPDATE feedp fp
  2958. SET ccountratio = ccount *(ratio /100 ),
  2959. fp.supplyweight= IFNULL(IF(
  2960. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2961. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2962. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2963. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2964. ),0),fp.feedweight = IFNULL(IF(
  2965. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2966. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2967. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2968. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2969. ),0) +ifnull(fp.supplyweight,0)
  2970. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2971. _, err = tx.SQL(`UPDATE fpdetail fpd
  2972. INNER JOIN feedp fp
  2973. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2974. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2975. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2976. }
  2977. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  2978. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  2979. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  2980. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  2981. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  2982. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  2983. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  2984. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  2985. join feedtemplet ft on ft.id = fp.ftid where ft.id = ?`, parammaps["ftid"]).QueryString()
  2986. // fmt.Println(ftId)
  2987. tx.SQL(`update feedp fp set barname = (select bname from bar where id = fp.id ) where pastureid = ?`, parammaps["pastureid"]).Execute()
  2988. // fmt.Println(fsion.Get("userId").ValueStr(),"fsion.Get.ValueStr()")
  2989. FpdBatchEditGrfd(fmt.Sprintf("%v", parammaps["pastureid"]), values1)
  2990. // 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 ,
  2991. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2992. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2993. // UNION
  2994. // 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 ,
  2995. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2996. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2997. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2998. // lpplanList := make([]*lpplanStruct, 0)
  2999. // err = tx.SQL(`select id,times,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpplan.pastureid ) = 0 ,
  3000. // ifnull((select maxstirfeed from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),100000),(select ifnull(volume,0) from tmr where id = lpplan.tmrid ) *
  3001. // (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)
  3002. // if err != nil {
  3003. // logs.Error(err, 1)
  3004. // return
  3005. // }
  3006. // lppidlist := []string{}
  3007. // for _, lpp := range lpplanList {
  3008. // lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  3009. // }
  3010. // if len(lppidlist) <= 0 {
  3011. // appG.Response(http.StatusOK, e.SUCCESS, true)
  3012. // return
  3013. // }
  3014. // lpplandtl1AllList := make([]*lpplandtl1, 0)
  3015. // err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  3016. // order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  3017. // if err != nil {
  3018. // // tx.Rollback()
  3019. // logs.Error(err, 2, parammaps["pastureid"])
  3020. // return
  3021. // }
  3022. // for _, lpp := range lpplandtl1AllList {
  3023. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  3024. // and find_in_set(barid,?) `, parammaps["pastureid"], 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. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3031. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  3032. // if err != nil {
  3033. // logs.Error(err)
  3034. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3035. // return
  3036. // }
  3037. // }
  3038. // var wg sync.WaitGroup
  3039. // for _, old := range fpdOldDataList {
  3040. // for _, fpd := range fpdDataList {
  3041. // wg.Add(1)
  3042. // go func(old, fpd map[string]interface{}) {
  3043. // updateLppandList := make([]*lpplandtl1, 0)
  3044. // defer wg.Done()
  3045. // if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3046. // fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3047. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3048. // oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3049. // // if weight > oldweight {
  3050. // // return
  3051. // // }
  3052. // var w float64
  3053. // var status int
  3054. // if weight < oldweight {
  3055. // if weight >= 0 {
  3056. // return
  3057. // }
  3058. // w = weight
  3059. // status = 0
  3060. // } else {
  3061. // if oldweight > 0 {
  3062. // return
  3063. // }
  3064. // w = weight
  3065. // status = 1
  3066. // }
  3067. // // fweight = w
  3068. // for _, lpp := range lpplanList {
  3069. // var fweight float64
  3070. // var lweight float64
  3071. // lpplandtl1List := make([]*lpplandtl1, 0)
  3072. // fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3073. // for _, lppland := range lpplandtl1AllList {
  3074. // if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3075. // lpplandtl1List = append(lpplandtl1List, lppland)
  3076. // }
  3077. // }
  3078. // if len(lpplandtl1List) == 0 {
  3079. // continue
  3080. // }
  3081. // for _, lppland := range lpplandtl1List {
  3082. // lweight += lppland.Lweight
  3083. // }
  3084. // if status == 0 {
  3085. // if lweight <= 0 {
  3086. // continue
  3087. // }
  3088. // } else {
  3089. // if lpp.Maxweight <= lweight {
  3090. // continue
  3091. // }
  3092. // }
  3093. // for _, lppland := range lpplandtl1List {
  3094. // if fpdid == lppland.Fpdid {
  3095. // if status == 1 {
  3096. // // if w <= lppland.Lweight {
  3097. // if lpp.Maxweight <= lweight {
  3098. // continue
  3099. // }
  3100. // if w+lweight <= lpp.Maxweight {
  3101. // lppland.Lweight += w
  3102. // lweight += w
  3103. // fweight += w
  3104. // w = 0
  3105. // } else {
  3106. // w = w - (lpp.Maxweight - lweight)
  3107. // n := (lpp.Maxweight - lweight)
  3108. // lppland.Lweight = lppland.Lweight + n
  3109. // lweight += n
  3110. // fweight += n
  3111. // }
  3112. // } else {
  3113. // if lppland.Lweight == 0 {
  3114. // continue
  3115. // }
  3116. // if w+lppland.Lweight >= 0 {
  3117. // lppland.Lweight = lppland.Lweight + w
  3118. // lweight = lweight + w
  3119. // fweight = fweight + w
  3120. // w = 0
  3121. // } else {
  3122. // w = w + lppland.Lweight
  3123. // lweight = lweight - lppland.Lweight
  3124. // fweight = fweight - lppland.Lweight
  3125. // lppland.Lweight = 0
  3126. // }
  3127. // }
  3128. // updateLppandList = append(updateLppandList, lppland)
  3129. // break
  3130. // }
  3131. // }
  3132. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3133. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3134. // WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3135. // if err != nil {
  3136. // // tx.Rollback()
  3137. // logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3138. // return
  3139. // }
  3140. // for _, lppland := range updateLppandList {
  3141. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3142. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3143. // if err != nil {
  3144. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3145. // // tx.Rollback()
  3146. // logs.Error(err, 3)
  3147. // return
  3148. // }
  3149. // // defer wg.Done()
  3150. // }
  3151. // updateLppandList = []*lpplandtl1{}
  3152. // if w == 0 {
  3153. // break
  3154. // }
  3155. // }
  3156. // }
  3157. // }(old, fpd)
  3158. // }
  3159. // }
  3160. // wg.Wait()
  3161. }
  3162. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3163. if err != nil {
  3164. logs.Error(err)
  3165. appG.Response(http.StatusOK, e.ERROR, false)
  3166. return
  3167. }
  3168. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3169. if err != nil {
  3170. logs.Error(err)
  3171. appG.Response(http.StatusOK, e.ERROR, false)
  3172. return
  3173. }
  3174. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3175. if err != nil {
  3176. logs.Error(err)
  3177. appG.Response(http.StatusOK, e.ERROR, false)
  3178. return
  3179. }
  3180. now := createdate
  3181. userId:= fsion.Get("userId").ValueStr()
  3182. // for _, oldFpd := range oldFpdDataList {
  3183. for _, newFpd := range newFpdDataList {
  3184. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3185. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3186. // go func() {
  3187. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3188. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3189. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3190. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  3191. if err != nil {
  3192. logs.Error(err)
  3193. appG.Response(http.StatusOK, e.ERROR, false)
  3194. return
  3195. }
  3196. // }()
  3197. }
  3198. // break
  3199. // }
  3200. // }
  3201. // }
  3202. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3203. for _, newLpplandtl1 := range newLpplandtl1List {
  3204. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3205. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3206. // go func() {
  3207. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3208. background,cowcount,ccountradio,lweighthis,userId,createdate)
  3209. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3210. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3211. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3212. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3213. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3214. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], userId,now ).Execute()
  3215. if err != nil {
  3216. logs.Error(err)
  3217. appG.Response(http.StatusOK, e.ERROR, false)
  3218. return
  3219. }
  3220. // }()
  3221. // }
  3222. // break
  3223. // }
  3224. // }
  3225. }
  3226. // for _, oldFeedp := range oldFeedpList {
  3227. for _, newFeedp := range newFeedpList {
  3228. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3229. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3230. // go func() {
  3231. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3232. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3233. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3234. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3235. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3236. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3237. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3238. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  3239. // fmt.Println(userId,"33333333333333333333333333333333333")
  3240. if err != nil {
  3241. logs.Error(err)
  3242. appG.Response(http.StatusOK, e.ERROR, false)
  3243. return
  3244. }
  3245. }
  3246. // ,,parammaps["ftid"])
  3247. // surplus, surplusId, id, pastureId string
  3248. // FtdetailSurplusFt(parammaps["ftid"].)
  3249. ftList1, err := tx.SQL(` SELECT
  3250. f.id,
  3251. f.surplus surplusId,
  3252. f.pastureid,
  3253. s.surplus
  3254. FROM
  3255. feedtemplet f
  3256. JOIN surplus s ON s.id = f.surplus
  3257. WHERE
  3258. f.id = ?`, parammaps["ftid"]).QueryString()
  3259. for _, ft := range ftList1 {
  3260. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3261. }
  3262. appG.Response(http.StatusOK, e.SUCCESS, true)
  3263. }
  3264. type lpplandtlInfo struct {
  3265. Id int64 `xorm:"id"`
  3266. Pastureid int64 `xorm:"pastureid"`
  3267. Lppid int64 `xorm:"lppid"`
  3268. Barid int64 `xorm:"barid"`
  3269. Barname string `xorm:"barname"`
  3270. Fpdid int64 `xorm:"fpdid"`
  3271. Fttype int64 `xorm:"fttype"`
  3272. Lweight float64 `xorm:"lweight"`
  3273. Sort int64 `xorm:"sort"`
  3274. Tmrid int64 `xorm:"tmrid"`
  3275. Tmrname string `xorm:"tmrname"`
  3276. Cowcount int64 `xorm:"cowcount"`
  3277. Ccountradio float64 `xorm:"ccountradio"`
  3278. Background string `xorm:"background"`
  3279. Lweighthis float64 `xorm:"lweighthis"`
  3280. Maxweight float64 `xorm:"maxweight"`
  3281. }
  3282. func UpdateFpdetailBar(c *gin.Context) {
  3283. appG := app.Gin{C: c}
  3284. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3285. fsion := gofasion.NewFasion(string(dataByte))
  3286. pastureid := fsion.Get("pastureid").ValueStr()
  3287. id := fsion.Get("id").ValueStr()
  3288. tx := restful.Engine.NewSession()
  3289. tx.Begin()
  3290. 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 `,
  3291. pastureid, id).Query().List()
  3292. if err != nil {
  3293. logs.Error(err)
  3294. }
  3295. for _, fpd := range fpdList {
  3296. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3297. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3298. pastureid, fpd["id"]).Query().List()
  3299. if err != nil {
  3300. tx.Rollback()
  3301. logs.Error(err)
  3302. appG.Response(http.StatusOK, e.ERROR, false)
  3303. return
  3304. }
  3305. var lweight float64
  3306. for _, lppland := range lpplandList {
  3307. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3308. lweight += lweight1
  3309. }
  3310. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3311. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3312. if fpdweight >= ptuse && lweight == ptuse {
  3313. continue
  3314. } else {
  3315. if lweight <= fpdweight {
  3316. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3317. if err != nil {
  3318. tx.Rollback()
  3319. logs.Error(err)
  3320. appG.Response(http.StatusOK, e.ERROR, false)
  3321. return
  3322. }
  3323. } else {
  3324. weight := fpdweight - lweight
  3325. for _, lppland := range lpplandList {
  3326. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3327. if weight >= lpplandlweight {
  3328. weight = weight - lpplandlweight
  3329. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3330. if err != nil {
  3331. tx.Rollback()
  3332. logs.Error(err)
  3333. appG.Response(http.StatusOK, e.ERROR, false)
  3334. return
  3335. }
  3336. } else {
  3337. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3338. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3339. // if err != nil {
  3340. // tx.Rollback()
  3341. // logs.Error(err)
  3342. // appG.Response(http.StatusOK, e.ERROR, false)
  3343. // return
  3344. // }
  3345. weight = 0
  3346. break
  3347. }
  3348. }
  3349. }
  3350. }
  3351. }
  3352. fsionData := fsion.Get("data").Array()
  3353. for _, list := range fsionData {
  3354. ftmap := make(map[string]interface{})
  3355. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3356. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3357. ftmap["times"] = list.Get("times").ValueInt64()
  3358. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3359. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3360. // fmt.Println(ftmap)
  3361. /*
  3362. count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3363. and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3364. if count == 1 {
  3365. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3366. and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3367. if err != nil {
  3368. tx.Rollback()
  3369. logs.Error(err)
  3370. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3371. return
  3372. }
  3373. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3374. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3375. if err != nil {
  3376. tx.Rollback()
  3377. logs.Error(err)
  3378. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3379. return
  3380. }
  3381. }
  3382. */
  3383. fpdDataList, err := tx.SQL(`
  3384. 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 ,
  3385. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3386. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3387. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3388. if err != nil {
  3389. tx.Rollback()
  3390. logs.Error(err)
  3391. }
  3392. for _, fpd := range fpdDataList {
  3393. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3394. fttype := -1
  3395. if fpd["fttype"].(string) == "1" {
  3396. fttype = 1
  3397. }
  3398. var fweight float64
  3399. var lweight float64
  3400. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3401. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  3402. t.maxstirfeed,(select ifnull(volume,0) from tmr where id = lpp.tmrid ) *
  3403. (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  3404. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3405. join tmr t on t.id = lpp.tmrid
  3406. where lppland.fpdid =?
  3407. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3408. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3409. if err != nil {
  3410. tx.Rollback()
  3411. logs.Error(err)
  3412. }
  3413. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3414. var w float64
  3415. var status int
  3416. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3417. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3418. if weight >= 0 {
  3419. continue
  3420. }
  3421. w = weight
  3422. status = 0
  3423. } else {
  3424. // continue
  3425. if weight <= 0 {
  3426. continue
  3427. }
  3428. w = weight
  3429. status = 1
  3430. }
  3431. // for _, lppland := range lpplandtl1List {
  3432. // lweight += lppland.Lweight
  3433. // }
  3434. for _, lppland := range lpplandtl1List {
  3435. lpplandInfo := new(lpplandtlInfo)
  3436. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3437. lweight = lpplandInfo.Lweight
  3438. if status == 1 {
  3439. // if w <= lppland.Lweight {
  3440. if lppland.Maxweight <= lweight {
  3441. continue
  3442. }
  3443. if w+lweight <= lppland.Maxweight {
  3444. lppland.Lweight += w
  3445. lweight += w
  3446. fweight += w
  3447. w = 0
  3448. } else {
  3449. w = w - (lppland.Maxweight - lweight)
  3450. n := (lppland.Maxweight - lweight)
  3451. lppland.Lweight = lppland.Lweight + n
  3452. lweight += n
  3453. fweight += n
  3454. }
  3455. } else {
  3456. if lppland.Lweight == 0 {
  3457. continue
  3458. }
  3459. if w+lppland.Lweight >= 0 {
  3460. lppland.Lweight = lppland.Lweight + w
  3461. lweight = lweight + w
  3462. fweight = fweight + w
  3463. w = 0
  3464. } else {
  3465. w = w + lppland.Lweight
  3466. lweight = lweight - lppland.Lweight
  3467. fweight = fweight - lppland.Lweight
  3468. lppland.Lweight = 0
  3469. }
  3470. }
  3471. if lppland.Lweight > 0 {
  3472. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3473. if err != nil {
  3474. tx.Rollback()
  3475. logs.Error(err)
  3476. return
  3477. }
  3478. } else {
  3479. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3480. if err != nil {
  3481. tx.Rollback()
  3482. logs.Error(err)
  3483. return
  3484. }
  3485. }
  3486. if w == 0 {
  3487. break
  3488. }
  3489. // break
  3490. }
  3491. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3492. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3493. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3494. if err != nil {
  3495. tx.Rollback()
  3496. logs.Error(err)
  3497. }
  3498. if w == 0 {
  3499. break
  3500. }
  3501. }
  3502. }
  3503. }
  3504. tx.Commit()
  3505. now := time.Now()
  3506. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3507. if err != nil {
  3508. logs.Error(err)
  3509. appG.Response(http.StatusOK, e.ERROR, false)
  3510. return
  3511. }
  3512. for _, newLpplandtl1 := range newLpplandtl1List {
  3513. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3514. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3515. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3516. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3517. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3518. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3519. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3520. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3521. if err != nil {
  3522. logs.Error(err)
  3523. appG.Response(http.StatusOK, e.ERROR, false)
  3524. return
  3525. }
  3526. }
  3527. appG.Response(http.StatusOK, e.SUCCESS, true)
  3528. }
  3529. func GetProcessAnalysis(c *gin.Context) {
  3530. appG := app.Gin{C: c}
  3531. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3532. fsion := gofasion.NewFasion(string(dataByte))
  3533. sqlnamestr := fsion.Get("name").ValueStr()
  3534. offset := fsion.Get("offset").ValueDefaultInt(0)
  3535. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3536. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3537. parammaps := fsion.Get("parammaps")
  3538. tx := restful.Engine.NewSession()
  3539. err := tx.Begin()
  3540. defer func() {
  3541. switch {
  3542. case err != nil:
  3543. logging.Error("tx.Begin 事务启动失败__error:", err)
  3544. if tx != nil {
  3545. tx.Rollback()
  3546. }
  3547. default:
  3548. if tx != nil {
  3549. err = tx.Commit()
  3550. }
  3551. }
  3552. if tx != nil {
  3553. tx.Close()
  3554. }
  3555. }()
  3556. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3557. s_params := make([]interface{}, 0)
  3558. paramslist := strings.Split(p, ",")
  3559. if len(paramslist) > 0 && p != "" {
  3560. for _, value := range paramslist {
  3561. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3562. if tempv, exists := c.Get("jwt_username"); exists {
  3563. s_params = append(s_params, tempv.(string))
  3564. } else {
  3565. s_params = append(s_params, "")
  3566. }
  3567. } else {
  3568. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3569. }
  3570. }
  3571. }
  3572. tmrtnameStr := ""
  3573. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3574. if len(tmrtnameStr) == 0 {
  3575. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3576. } else {
  3577. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3578. }
  3579. }
  3580. if len(tmrtnameStr) > 0 {
  3581. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3582. }
  3583. sql += " ORDER BY d.intime"
  3584. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3585. if err != nil {
  3586. logging.Error("GetDataByName err: ", err)
  3587. msg := geterrmsg(err.Error())
  3588. appG.Response(http.StatusOK, e.ERROR, msg)
  3589. } else {
  3590. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3591. }
  3592. }
  3593. func UpdateFeedtempletStatus(c *gin.Context) {
  3594. appG := app.Gin{C: c}
  3595. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3596. fsion := gofasion.NewFasion(string(dataByte))
  3597. parammaps := fsion.Get("parammaps")
  3598. tx := restful.Engine.NewSession()
  3599. tx.Begin()
  3600. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3601. if err != nil {
  3602. tx.Rollback()
  3603. logs.Error(err)
  3604. appG.Response(http.StatusOK, e.ERROR, err)
  3605. return
  3606. }
  3607. tx.Commit()
  3608. appG.Response(http.StatusOK, e.SUCCESS, true)
  3609. }
  3610. func AddFtdry(c *gin.Context) {
  3611. appG := app.Gin{C: c}
  3612. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3613. fsion := gofasion.NewFasion(string(dataByte))
  3614. sqlnamestr := fsion.Get("name").ValueStr()
  3615. s_params := make([]interface{}, 0)
  3616. tx := restful.Engine.NewSession()
  3617. err := tx.Begin()
  3618. defer func() {
  3619. switch {
  3620. case err != nil:
  3621. if tx != nil {
  3622. tx.Rollback()
  3623. }
  3624. default:
  3625. if tx != nil {
  3626. err = tx.Commit()
  3627. }
  3628. }
  3629. if tx != nil {
  3630. tx.Close()
  3631. }
  3632. }()
  3633. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3634. if sql != "" {
  3635. parammaps := fsion.Get("parammaps")
  3636. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3637. paramslist := strings.Split(p, ",")
  3638. if len(paramslist) > 0 && p != "" {
  3639. for _, value := range paramslist {
  3640. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3641. if tempv, exists := c.Get("jwt_username"); exists {
  3642. s_params = append(s_params, tempv.(string))
  3643. } else {
  3644. s_params = append(s_params, "")
  3645. }
  3646. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3647. ids, err := setting.SnowIds.NextId()
  3648. if err != nil {
  3649. ids = time.Now().UnixNano()
  3650. logging.Info("create SnowIds err", err)
  3651. }
  3652. s_params = append(s_params, ids)
  3653. } else {
  3654. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3655. }
  3656. }
  3657. }
  3658. var actweight float64
  3659. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3660. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3661. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3662. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3663. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3664. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3665. 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()
  3666. if err != nil {
  3667. logging.Error("AddFtdry err: ", err)
  3668. msg := geterrmsg(err.Error())
  3669. appG.Response(http.StatusOK, e.ERROR, msg)
  3670. }
  3671. if len(actweightList) > 0 {
  3672. for _, item := range actweightList {
  3673. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3674. if err != nil {
  3675. logging.Error("AddFtdry err: ", err)
  3676. msg := geterrmsg(err.Error())
  3677. appG.Response(http.StatusOK, e.ERROR, msg)
  3678. }
  3679. actweight = fl
  3680. }
  3681. } else {
  3682. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3683. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3684. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  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. for _, item := range dryList {
  3691. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3692. if err != nil {
  3693. logging.Error("AddFtdry err: ", err)
  3694. msg := geterrmsg(err.Error())
  3695. appG.Response(http.StatusOK, e.ERROR, msg)
  3696. }
  3697. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3698. }
  3699. }
  3700. if sqlnamestr == "insertFtdry" {
  3701. s_params = append(s_params, actweight)
  3702. } else if sqlnamestr == "updateFtdry" {
  3703. sql = fmt.Sprintf(sql, actweight)
  3704. }
  3705. queryData, err := execDataBySqlT(sql, s_params, tx)
  3706. if err != nil {
  3707. logging.Error("AddFtdry err: ", err)
  3708. msg := geterrmsg(err.Error())
  3709. appG.Response(http.StatusOK, e.ERROR, msg)
  3710. } else {
  3711. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3712. }
  3713. } else {
  3714. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3715. }
  3716. }
  3717. func CheckDates(c *gin.Context) {
  3718. tx := restful.Engine.NewSession()
  3719. defer tx.Close()
  3720. appG := app.Gin{C: c}
  3721. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3722. tempval_ := make(map[string]interface{})
  3723. tempCommon := make(map[string]interface{})
  3724. tempval := make([]map[string]interface{}, 0)
  3725. err := json.Unmarshal(dataByte, &tempval_)
  3726. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3727. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3728. if err != nil {
  3729. } else {
  3730. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3731. tempCommon = v
  3732. }
  3733. if v, ok := tempval_["data"].([]interface{}); ok {
  3734. for _, Tvalue := range v {
  3735. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3736. tempval = append(tempval, v1)
  3737. }
  3738. }
  3739. }
  3740. if err == nil {
  3741. if tempv, exists := c.Get("jwt_username"); exists {
  3742. tempCommon["jwt_username"] = tempv.(string)
  3743. }
  3744. for _, paramvalue := range tempval {
  3745. if _, ok := paramvalue["resultname"]; !ok {
  3746. paramvalue["resultname"] = paramvalue["name"]
  3747. }
  3748. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3749. if err != nil {
  3750. logging.Error("ExecDataParam error:", err)
  3751. }
  3752. }
  3753. if err == nil {
  3754. vmsg := ""
  3755. for _, item := range tempval {
  3756. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3757. for _, childrenList := range list.([]interface{}) {
  3758. for k, children := range childrenList.(map[string]interface{}) {
  3759. if k != "children" {
  3760. continue
  3761. }
  3762. for _, v := range children.([]map[string]interface{}) {
  3763. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3764. if k1 == "list" {
  3765. for _, v2 := range v1.([]map[string]interface{}) {
  3766. if v2["vmsg"].(string) != "1" {
  3767. if len(vmsg) == 0 {
  3768. vmsg = v2["vmsg"].(string)
  3769. } else {
  3770. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3771. }
  3772. }
  3773. }
  3774. }
  3775. }
  3776. }
  3777. }
  3778. }
  3779. }
  3780. }
  3781. if len(vmsg) > 0 {
  3782. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3783. } else {
  3784. appG.Response(http.StatusOK, e.SUCCESS, true)
  3785. }
  3786. } else {
  3787. msg := geterrmsg(err.Error())
  3788. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3789. }
  3790. }
  3791. }
  3792. if err != nil {
  3793. msg := geterrmsg(err.Error())
  3794. appG.Response(http.StatusOK, e.ERROR, msg)
  3795. }
  3796. }
  3797. 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) {
  3798. sqlname := fasion["name"].(string)
  3799. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3800. if v, ok := fasion["type"]; ok {
  3801. sqltype = v.(string)
  3802. }
  3803. sql := ""
  3804. p := ""
  3805. s_params := make([]interface{}, 0)
  3806. if sqltype != "" {
  3807. sql, p = restful.GetSqlByName(sqlname, tx)
  3808. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3809. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3810. paramslist := strings.Split(p, ",")
  3811. if len(paramslist) > 0 && p != "" {
  3812. for _, value := range paramslist {
  3813. ss := ""
  3814. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3815. ids, err := setting.SnowIds.NextId()
  3816. if err != nil {
  3817. ids = time.Now().UnixNano()
  3818. logging.Info("create SnowIds err", err)
  3819. }
  3820. s_params = append(s_params, ids)
  3821. } else {
  3822. if ss == "" && CommonParamMap != nil {
  3823. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3824. ss = valuestring
  3825. tempstrb := strings.IndexAny(valuestring, "@")
  3826. tempstre := strings.IndexAny(valuestring, ".")
  3827. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3828. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3829. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3830. }
  3831. } else {
  3832. ss = ""
  3833. }
  3834. }
  3835. }
  3836. if ss == "" && ParentParamMap != nil {
  3837. ss = getParamValue_(v, value, ParentParamMap)
  3838. }
  3839. if ss == "" && sameParamMap != nil {
  3840. ss = getParamValue(v, value, sameParamMap)
  3841. }
  3842. if ss == "" && ParamMap != nil {
  3843. ss = getParamValue(v, value, ParamMap)
  3844. }
  3845. s_params = append(s_params, ss)
  3846. }
  3847. }
  3848. }
  3849. }
  3850. }
  3851. if sql == "" {
  3852. sqltype = ""
  3853. }
  3854. if sql != "" {
  3855. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3856. if err != nil {
  3857. return nil, err
  3858. }
  3859. // fmt.Println(tempValParam)
  3860. return tempValParam.(map[string]interface{}), nil
  3861. } else {
  3862. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3863. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3864. if err != nil {
  3865. return nil, err
  3866. }
  3867. return nil, err
  3868. }
  3869. }
  3870. return nil, nil
  3871. }
  3872. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3873. var err error
  3874. subarray, ok := fasion["children"]
  3875. if ok {
  3876. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3877. tempVal_arrary := make([]map[string]interface{}, 0)
  3878. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3879. tempVal_ := make(map[string]interface{})
  3880. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3881. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3882. } else {
  3883. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3884. }
  3885. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3886. if err != nil {
  3887. return err
  3888. }
  3889. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3890. }
  3891. v.(map[string]interface{})["children"] = tempVal_arrary
  3892. }
  3893. }
  3894. return nil
  3895. }
  3896. func FpdImportExcel(c *gin.Context) {
  3897. appG := app.Gin{C: c}
  3898. inputdata := ""
  3899. c.Request.ParseForm()
  3900. params := c.Request.Form
  3901. file, _, err := c.Request.FormFile("file")
  3902. if err != nil {
  3903. appG.Response(http.StatusOK, e.ERROR, err)
  3904. return
  3905. }
  3906. sqlnamestrs := params.Get("name")
  3907. sheetname := params.Get("sheetname")
  3908. pastureid := params.Get("pastureid")
  3909. // importParams := params.Get("importParams")
  3910. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3911. // 必输项参数 (字符串格式 "field1,field2,field3")
  3912. requiredParams := params.Get("requiredParams")
  3913. // 日期参数
  3914. dateParams := params.Get("dateParams")
  3915. // 数字参数
  3916. numParams := params.Get("numParams")
  3917. //将字符串分割开
  3918. dateParamslist := strings.Split(dateParams, ",")
  3919. requiredParamslist := strings.Split(requiredParams, ",")
  3920. numParamslist := strings.Split(numParams, ",")
  3921. queryData := make([]interface{}, 0)
  3922. sqlslist := strings.Split(sqlnamestrs, ",")
  3923. xlsx1, err := excelize.OpenReader(file)
  3924. if err != nil {
  3925. fmt.Println(err)
  3926. return
  3927. }
  3928. ok := 0
  3929. error := 0
  3930. isdone := true
  3931. tx := restful.Engine.NewSession()
  3932. defer tx.Close()
  3933. languageStatus := GetLanguageStatus()
  3934. if languageStatus == "0" {
  3935. 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
  3936. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3937. if err != nil {
  3938. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3939. return
  3940. }
  3941. rows := xlsx1.GetRows(sheetname)
  3942. // 限制10000条,多余的截取掉
  3943. if len(rows) > 10000 {
  3944. rows = rows[:10000]
  3945. }
  3946. dataList := make(map[string][]*upFpdetail, 0)
  3947. for i, row := range rows {
  3948. if i > 0 {
  3949. entry := make(map[string]interface{})
  3950. outentry := make(map[string]interface{})
  3951. for j, colCell := range rows[0] {
  3952. for k, colCell1 := range row {
  3953. if j == k {
  3954. outentry[colCell] = colCell1
  3955. entry[colCell] = colCell1
  3956. }
  3957. }
  3958. }
  3959. inputdata = ""
  3960. a := ""
  3961. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3962. //校验日期格式
  3963. for _, v := range dateParamslist {
  3964. if v == "" {
  3965. continue
  3966. }
  3967. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3968. dtime, err := TransfTime(d.(string))
  3969. if err != nil {
  3970. a = strings.Trim(v, " ")
  3971. break
  3972. }
  3973. outentry[strings.Trim(v, " ")] = dtime
  3974. }
  3975. }
  3976. if a != "" {
  3977. outentry["error_msg"] = a + " 格式错误"
  3978. error++
  3979. queryData = append(queryData, outentry)
  3980. continue
  3981. }
  3982. a = ""
  3983. //校验必填格式
  3984. for _, v := range requiredParamslist {
  3985. if v == "" {
  3986. continue
  3987. }
  3988. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3989. a = strings.Trim(v, " ")
  3990. break
  3991. }
  3992. }
  3993. if a != "" {
  3994. outentry["error_msg"] = a + " 未填或格式错误"
  3995. error++
  3996. queryData = append(queryData, outentry)
  3997. continue
  3998. }
  3999. a = ""
  4000. //校验数字格式
  4001. for _, v := range numParamslist {
  4002. if v == "" {
  4003. continue
  4004. }
  4005. d, ok := outentry[strings.Trim(v, " ")]
  4006. if !ok || d == "" {
  4007. outentry[strings.Trim(v, " ")] = 0
  4008. } else {
  4009. var fl float64
  4010. switch d.(type) {
  4011. case string:
  4012. fl, err = strconv.ParseFloat(d.(string), 64)
  4013. }
  4014. if err != nil || fl < 0 {
  4015. a = strings.Trim(v, " ")
  4016. break
  4017. }
  4018. }
  4019. }
  4020. if a != "" {
  4021. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  4022. error++
  4023. queryData = append(queryData, outentry)
  4024. continue
  4025. }
  4026. errExist := false
  4027. for _, sqlnamestr := range sqlslist {
  4028. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4029. paramslist := strings.Split(paramslists, ",")
  4030. if len(paramslist) > 0 {
  4031. s_params := make([]interface{}, 0)
  4032. for _, value := range paramslist {
  4033. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4034. if tempv, exists := c.Get("jwt_username"); exists {
  4035. s_params = append(s_params, tempv.(string))
  4036. } else {
  4037. s_params = append(s_params, "")
  4038. }
  4039. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4040. s_params = append(s_params, pastureid)
  4041. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4042. ids, err := setting.SnowIds.NextId()
  4043. if err != nil {
  4044. ids = time.Now().UnixNano()
  4045. logging.Info("create SnowIds err", err)
  4046. }
  4047. s_params = append(s_params, ids)
  4048. } else {
  4049. if outentry[strings.Trim(value, " ")] == nil {
  4050. s_params = append(s_params, "")
  4051. } else {
  4052. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4053. }
  4054. }
  4055. }
  4056. outentry["input"] = inputdata
  4057. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4058. if err != nil {
  4059. errExist = true
  4060. // if tx != nil {
  4061. // tx.Rollback()
  4062. // }
  4063. // if tx != nil {
  4064. // tx.Close()
  4065. // }
  4066. msg := geterrmsg(err.Error())
  4067. outentry["error_msg"] = msg
  4068. error++
  4069. queryData = append(queryData, outentry)
  4070. isdone = true
  4071. break
  4072. } else {
  4073. if len(returnmsgmap1) > 0 {
  4074. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4075. // if tx != nil {
  4076. // tx.Rollback()
  4077. // }
  4078. // if tx != nil {
  4079. // tx.Close()
  4080. // }
  4081. msg := geterrmsg(va.(string))
  4082. outentry["error_msg"] = msg
  4083. error++
  4084. queryData = append(queryData, outentry)
  4085. isdone = true
  4086. break
  4087. }
  4088. }
  4089. isdone = false
  4090. }
  4091. }
  4092. }
  4093. fmt.Println(outentry["栏舍名称"])
  4094. if !errExist {
  4095. dataexcel := make(map[string]interface{}, 0)
  4096. if _, ok := outentry["栏舍名称"]; ok {
  4097. dataexcel["barname"] = outentry["栏舍名称"]
  4098. }
  4099. // if _, ok := outentry["实际牛头数"]; ok {
  4100. // dataexcel["ccount"] = outentry["实际牛头数"]
  4101. // }
  4102. if _, ok := outentry["实际羊只数"]; ok {
  4103. dataexcel["ccount"] = outentry["实际羊只数"]
  4104. }
  4105. if _, ok := outentry["系数(%)"]; ok {
  4106. dataexcel["ratio"] = outentry["系数(%)"]
  4107. }
  4108. if _, ok := outentry["配方模板"]; ok {
  4109. dataexcel["ftname"] = outentry["配方模板"]
  4110. }
  4111. if _, ok := outentry["补料配方"]; ok {
  4112. dataexcel["ptsfname"] = outentry["补料配方"]
  4113. }
  4114. if _, ok := outentry["第一班比例(%)"]; ok {
  4115. dataexcel["1"] = outentry["第一班比例(%)"]
  4116. if fmt.Sprintf("%v", dataexcel["1"]) == "" {
  4117. dataexcel["1"] = 0
  4118. }
  4119. } else {
  4120. dataexcel["1"] = 0
  4121. }
  4122. if _, ok := outentry["第二班比例(%)"]; ok {
  4123. dataexcel["2"] = outentry["第二班比例(%)"]
  4124. if fmt.Sprintf("%v", dataexcel["2"]) == "" {
  4125. dataexcel["2"] = 0
  4126. }
  4127. } else {
  4128. dataexcel["2"] = 0
  4129. }
  4130. if _, ok := outentry["第三班比例(%)"]; ok {
  4131. dataexcel["3"] = outentry["第三班比例(%)"]
  4132. if fmt.Sprintf("%v", dataexcel["3"]) == "" {
  4133. dataexcel["3"] = 0
  4134. }
  4135. } else {
  4136. dataexcel["3"] = 0
  4137. }
  4138. if _, ok := outentry["第四班比例(%)"]; ok {
  4139. dataexcel["4"] = outentry["第四班比例(%)"]
  4140. if fmt.Sprintf("%v", dataexcel["4"]) == "" {
  4141. dataexcel["4"] = 0
  4142. }
  4143. } else {
  4144. dataexcel["4"] = 0
  4145. }
  4146. if _, ok := outentry["第五班比例(%)"]; ok {
  4147. dataexcel["5"] = outentry["第五班比例(%)"]
  4148. if fmt.Sprintf("%v", dataexcel["5"]) == "" {
  4149. dataexcel["5"] = 0
  4150. }
  4151. } else {
  4152. dataexcel["5"] = 0
  4153. }
  4154. if _, ok := outentry["第六班比例(%)"]; ok {
  4155. dataexcel["6"] = outentry["第六班比例(%)"]
  4156. if fmt.Sprintf("%v", dataexcel["6"]) == "" {
  4157. dataexcel["6"] = 0
  4158. }
  4159. } else {
  4160. dataexcel["6"] = 0
  4161. }
  4162. dataWeight := new(models.FpdetailEdit)
  4163. // dataWeightMap := make(map[string]interface{}, 0)
  4164. if _, ok := outentry["第一班重量"]; ok {
  4165. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4166. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4167. }
  4168. if _, ok := outentry["第二班重量"]; ok {
  4169. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4170. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4171. }
  4172. if _, ok := outentry["第三班重量"]; ok {
  4173. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4174. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4175. }
  4176. if _, ok := outentry["第四班重量"]; ok {
  4177. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4178. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4179. }
  4180. if _, ok := outentry["第五班重量"]; ok {
  4181. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4182. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4183. }
  4184. if _, ok := outentry["第六班重量"]; ok {
  4185. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4186. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4187. }
  4188. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4189. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4190. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4191. // fmt.Println(err)
  4192. if fmt.Sprintf("%v", dataexcel["ccount"]) == "0" {
  4193. dataWeight.Weight1 = 0
  4194. dataWeight.Weight2 = 0
  4195. dataWeight.Weight3 = 0
  4196. dataWeight.Weight4 = 0
  4197. dataWeight.Weight5 = 0
  4198. dataWeight.Weight6 = 0
  4199. }
  4200. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4201. if weight > 0 {
  4202. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4203. if err != nil {
  4204. logs.Error(err)
  4205. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4206. return
  4207. }
  4208. if !existbar {
  4209. continue
  4210. }
  4211. _, 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()
  4212. if err != nil {
  4213. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4214. return
  4215. }
  4216. _, 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()
  4217. if err != nil {
  4218. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4219. return
  4220. }
  4221. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4222. if err != nil {
  4223. logs.Error(err)
  4224. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4225. return
  4226. }
  4227. if !existft {
  4228. continue
  4229. }
  4230. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4231. if err != nil {
  4232. logs.Error(err)
  4233. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4234. return
  4235. }
  4236. if !ftexist {
  4237. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4238. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4239. if err != nil {
  4240. logs.Error(err)
  4241. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4242. return
  4243. }
  4244. tx.SQL(` update fpdetail set ptuse = 0 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. }
  4251. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4252. if err != nil {
  4253. logs.Error(err)
  4254. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4255. return
  4256. }
  4257. if !exist {
  4258. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4259. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4260. if err != nil {
  4261. logs.Error(err)
  4262. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4263. return
  4264. }
  4265. }
  4266. var feedpargs []interface{}
  4267. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4268. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4269. if _, ok := dataexcel["ftname"]; ok {
  4270. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4271. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4272. // upFeedpSql += `,ftweight = ? `
  4273. // feedpargs = append(feedpargs, weight)
  4274. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4275. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4276. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4277. } else {
  4278. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4279. }
  4280. if _, ok := dataexcel["ptsfname"]; ok {
  4281. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4282. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4283. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4284. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4285. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4286. } else {
  4287. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4288. }
  4289. upFeedpSql += " where barname = ? and pastureid = ? "
  4290. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4291. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4292. if err != nil {
  4293. logs.Error(err)
  4294. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4295. return
  4296. }
  4297. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4298. if err != nil {
  4299. logs.Error(err)
  4300. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4301. return
  4302. }
  4303. if !exist1 {
  4304. _, 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) `,
  4305. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4306. if err != nil {
  4307. logs.Error(err)
  4308. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4309. return
  4310. }
  4311. }
  4312. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4313. if err != nil {
  4314. logs.Error(err)
  4315. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4316. return
  4317. }
  4318. if !exist2 {
  4319. _, 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) `,
  4320. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4321. if err != nil {
  4322. logs.Error(err)
  4323. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4324. return
  4325. }
  4326. }
  4327. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4328. if err != nil {
  4329. logs.Error(err)
  4330. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4331. return
  4332. }
  4333. if !exist3 {
  4334. _, 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) `,
  4335. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4336. if err != nil {
  4337. logs.Error(err)
  4338. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4339. return
  4340. }
  4341. }
  4342. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4343. if err != nil {
  4344. logs.Error(err)
  4345. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4346. return
  4347. }
  4348. if !exist4 {
  4349. _, 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) `,
  4350. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4351. if err != nil {
  4352. logs.Error(err)
  4353. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4354. return
  4355. }
  4356. }
  4357. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4358. if err != nil {
  4359. logs.Error(err)
  4360. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4361. return
  4362. }
  4363. if !exist5 {
  4364. _, 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) `,
  4365. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4366. if err != nil {
  4367. logs.Error(err)
  4368. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4369. return
  4370. }
  4371. }
  4372. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4373. if err != nil {
  4374. logs.Error(err)
  4375. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4376. return
  4377. }
  4378. if !exist6 {
  4379. _, 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) `,
  4380. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4381. if err != nil {
  4382. logs.Error(err)
  4383. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4384. return
  4385. }
  4386. }
  4387. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4388. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4389. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4390. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4391. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4392. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4393. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4394. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4395. and pastureid = ? and times = ?`
  4396. var fpdargs1 []interface{}
  4397. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4398. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4399. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4400. if err != nil {
  4401. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4402. return
  4403. }
  4404. var fpdargs2 []interface{}
  4405. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4406. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4407. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4408. if err != nil {
  4409. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4410. return
  4411. }
  4412. var fpdargs3 []interface{}
  4413. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4414. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4415. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4416. if err != nil {
  4417. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4418. return
  4419. }
  4420. var fpdargs4 []interface{}
  4421. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4422. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4423. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4424. if err != nil {
  4425. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4426. return
  4427. }
  4428. var fpdargs5 []interface{}
  4429. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4430. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4431. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4432. if err != nil {
  4433. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4434. return
  4435. }
  4436. var fpdargs6 []interface{}
  4437. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4438. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4439. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4440. if err != nil {
  4441. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4442. return
  4443. }
  4444. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4445. 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()
  4446. if err != nil {
  4447. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4448. return
  4449. }
  4450. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4451. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4452. upFpdetailList := make([]*upFpdetail, 0)
  4453. for _, newfpd := range newList {
  4454. for _, oldfpd := range oldFpdList {
  4455. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4456. var oldweight, newweight float64
  4457. if oldfpd["weight"] != nil {
  4458. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4459. }
  4460. if newfpd["weight"] != nil {
  4461. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4462. }
  4463. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4464. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4465. Old: oldweight,
  4466. New: newweight,
  4467. Times: newfpd["times"].(int64),
  4468. Ptid: newfpd["ptid"].(int64),
  4469. Fweight: fweight,
  4470. Id: oldfpd["id"].(int64),
  4471. })
  4472. break
  4473. }
  4474. }
  4475. }
  4476. // fmt.Println(dataexcel["barname"])
  4477. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4478. } else {
  4479. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4480. if err != nil {
  4481. logs.Error(err)
  4482. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4483. return
  4484. }
  4485. if !existbar {
  4486. continue
  4487. }
  4488. _, 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()
  4489. if err != nil {
  4490. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4491. return
  4492. }
  4493. _, 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()
  4494. if err != nil {
  4495. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4496. return
  4497. }
  4498. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4499. if err != nil {
  4500. logs.Error(err)
  4501. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4502. return
  4503. }
  4504. if !existft {
  4505. continue
  4506. }
  4507. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4508. if err != nil {
  4509. logs.Error(err)
  4510. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4511. return
  4512. }
  4513. if !ftexist {
  4514. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4515. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4516. if err != nil {
  4517. logs.Error(err)
  4518. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4519. return
  4520. }
  4521. tx.SQL(` update fpdetail set ptuse = 0 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. }
  4528. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4529. if err != nil {
  4530. logs.Error(err)
  4531. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4532. return
  4533. }
  4534. if !exist {
  4535. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4536. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4537. if err != nil {
  4538. logs.Error(err)
  4539. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4540. return
  4541. }
  4542. }
  4543. var feedpargs []interface{}
  4544. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4545. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4546. if _, ok := dataexcel["ftname"]; ok {
  4547. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4548. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4549. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4550. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4551. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4552. } else {
  4553. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4554. }
  4555. if _, ok := dataexcel["ptsfname"]; ok {
  4556. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4557. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4558. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4559. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4560. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4561. } else {
  4562. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4563. }
  4564. upFeedpSql += " where barname = ? and pastureid = ? "
  4565. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4566. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4567. if err != nil {
  4568. logs.Error(err)
  4569. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4570. return
  4571. }
  4572. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4573. if err != nil {
  4574. logs.Error(err)
  4575. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4576. return
  4577. }
  4578. if !exist1 {
  4579. _, 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) `,
  4580. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4581. if err != nil {
  4582. logs.Error(err)
  4583. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4584. return
  4585. }
  4586. }
  4587. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4588. if err != nil {
  4589. logs.Error(err)
  4590. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4591. return
  4592. }
  4593. if !exist2 {
  4594. _, 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) `,
  4595. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4596. if err != nil {
  4597. logs.Error(err)
  4598. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4599. return
  4600. }
  4601. }
  4602. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4603. if err != nil {
  4604. logs.Error(err)
  4605. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4606. return
  4607. }
  4608. if !exist3 {
  4609. _, 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) `,
  4610. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4611. if err != nil {
  4612. logs.Error(err)
  4613. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4614. return
  4615. }
  4616. }
  4617. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4618. if err != nil {
  4619. logs.Error(err)
  4620. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4621. return
  4622. }
  4623. if !exist4 {
  4624. _, 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) `,
  4625. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4626. if err != nil {
  4627. logs.Error(err)
  4628. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4629. return
  4630. }
  4631. }
  4632. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4633. if err != nil {
  4634. logs.Error(err)
  4635. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4636. return
  4637. }
  4638. if !exist5 {
  4639. _, 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) `,
  4640. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4641. if err != nil {
  4642. logs.Error(err)
  4643. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4644. return
  4645. }
  4646. }
  4647. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4648. if err != nil {
  4649. logs.Error(err)
  4650. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4651. return
  4652. }
  4653. if !exist6 {
  4654. _, 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) `,
  4655. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4656. if err != nil {
  4657. logs.Error(err)
  4658. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4659. return
  4660. }
  4661. }
  4662. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4663. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4664. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4665. and pastureid = ? and times = ?`
  4666. var fpdargs1 []interface{}
  4667. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4668. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4669. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4670. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4671. if err != nil {
  4672. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4673. return
  4674. }
  4675. var fpdargs2 []interface{}
  4676. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4677. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4678. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4679. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4680. if err != nil {
  4681. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4682. return
  4683. }
  4684. var fpdargs3 []interface{}
  4685. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4686. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4687. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4688. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4689. if err != nil {
  4690. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4691. return
  4692. }
  4693. var fpdargs4 []interface{}
  4694. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4695. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4696. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4697. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4698. if err != nil {
  4699. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4700. return
  4701. }
  4702. var fpdargs5 []interface{}
  4703. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4704. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4705. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4706. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4707. if err != nil {
  4708. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4709. return
  4710. }
  4711. var fpdargs6 []interface{}
  4712. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4713. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4714. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4715. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4716. if err != nil {
  4717. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4718. return
  4719. }
  4720. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4721. 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()
  4722. if err != nil {
  4723. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4724. return
  4725. }
  4726. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4727. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4728. upFpdetailList := make([]*upFpdetail, 0)
  4729. for _, newfpd := range newList {
  4730. for _, oldfpd := range oldFpdList {
  4731. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4732. var oldweight, newweight float64
  4733. if oldfpd["weight"] != nil {
  4734. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4735. }
  4736. if newfpd["weight"] != nil {
  4737. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4738. }
  4739. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4740. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4741. Old: oldweight,
  4742. New: newweight,
  4743. Times: newfpd["times"].(int64),
  4744. Ptid: newfpd["ptid"].(int64),
  4745. Fweight: fweight,
  4746. Id: oldfpd["id"].(int64),
  4747. })
  4748. break
  4749. }
  4750. }
  4751. }
  4752. // fmt.Println(dataexcel["barname"])
  4753. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4754. }
  4755. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4756. }
  4757. }
  4758. if !isdone {
  4759. ok++
  4760. isdone = true
  4761. }
  4762. }
  4763. for barname, v := range dataList {
  4764. // for _, v1 := range v {
  4765. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4766. // and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4767. // if count == 1 {
  4768. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4769. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4770. // if err != nil {
  4771. // logs.Error(err)
  4772. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4773. // return
  4774. // }
  4775. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4776. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4777. // if err != nil {
  4778. // logs.Error(err)
  4779. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4780. // return
  4781. // }
  4782. // }
  4783. // }
  4784. // /*
  4785. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  4786. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  4787. if err != nil {
  4788. logs.Error(err)
  4789. return
  4790. }
  4791. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4792. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  4793. if err != nil {
  4794. logs.Error(err)
  4795. return
  4796. }
  4797. // */
  4798. updateFpdetailByBar(pastureid, barname, v)
  4799. }
  4800. } else {
  4801. 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
  4802. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4803. if err != nil {
  4804. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4805. return
  4806. }
  4807. rows := xlsx1.GetRows(sheetname)
  4808. // 限制10000条,多余的截取掉
  4809. if len(rows) > 10000 {
  4810. rows = rows[:10000]
  4811. }
  4812. dataList := make(map[string][]*upFpdetail, 0)
  4813. for i, row := range rows {
  4814. if i > 0 {
  4815. entry := make(map[string]interface{})
  4816. outentry := make(map[string]interface{})
  4817. for j, colCell := range rows[0] {
  4818. for k, colCell1 := range row {
  4819. if j == k {
  4820. outentry[colCell] = colCell1
  4821. entry[colCell] = colCell1
  4822. }
  4823. }
  4824. }
  4825. inputdata = ""
  4826. a := ""
  4827. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4828. //校验日期格式
  4829. for _, v := range dateParamslist {
  4830. if v == "" {
  4831. continue
  4832. }
  4833. if d, ok := outentry[v]; ok {
  4834. dtime, err := TransfTime(d.(string))
  4835. if err != nil {
  4836. a = v
  4837. break
  4838. }
  4839. outentry[v] = dtime
  4840. }
  4841. }
  4842. if a != "" {
  4843. outentry["error_msg"] = a + " format error"
  4844. error++
  4845. queryData = append(queryData, outentry)
  4846. continue
  4847. }
  4848. a = ""
  4849. //校验必填格式
  4850. for _, v := range requiredParamslist {
  4851. if v == "" {
  4852. continue
  4853. }
  4854. if d, ok := outentry[v]; !ok || d == "" {
  4855. a = v
  4856. break
  4857. }
  4858. }
  4859. if a != "" {
  4860. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4861. error++
  4862. queryData = append(queryData, outentry)
  4863. continue
  4864. }
  4865. a = ""
  4866. //校验数字格式
  4867. for _, v := range numParamslist {
  4868. if v == "" {
  4869. continue
  4870. }
  4871. d, ok := outentry[v]
  4872. if !ok || d == "" {
  4873. outentry[v] = 0
  4874. } else {
  4875. var fl float64
  4876. switch d.(type) {
  4877. case string:
  4878. fl, err = strconv.ParseFloat(d.(string), 64)
  4879. }
  4880. if err != nil || fl < 0 {
  4881. a = v
  4882. break
  4883. }
  4884. }
  4885. }
  4886. if a != "" {
  4887. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4888. error++
  4889. queryData = append(queryData, outentry)
  4890. continue
  4891. }
  4892. errExist := false
  4893. for _, sqlnamestr := range sqlslist {
  4894. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4895. paramslist := strings.Split(paramslists, ",")
  4896. if len(paramslist) > 0 {
  4897. s_params := make([]interface{}, 0)
  4898. for _, value := range paramslist {
  4899. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4900. if tempv, exists := c.Get("jwt_username"); exists {
  4901. s_params = append(s_params, tempv.(string))
  4902. } else {
  4903. s_params = append(s_params, "")
  4904. }
  4905. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4906. s_params = append(s_params, pastureid)
  4907. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4908. ids, err := setting.SnowIds.NextId()
  4909. if err != nil {
  4910. ids = time.Now().UnixNano()
  4911. logging.Info("create SnowIds err", err)
  4912. }
  4913. s_params = append(s_params, ids)
  4914. } else {
  4915. if outentry[strings.Trim(value, " ")] == nil {
  4916. s_params = append(s_params, "")
  4917. } else {
  4918. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4919. }
  4920. }
  4921. }
  4922. outentry["input"] = inputdata
  4923. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4924. if err != nil {
  4925. errExist = true
  4926. // if tx != nil {
  4927. // tx.Rollback()
  4928. // }
  4929. // if tx != nil {
  4930. // tx.Close()
  4931. // }
  4932. msg := geterrmsg(err.Error())
  4933. outentry["error_msg"] = msg
  4934. error++
  4935. queryData = append(queryData, outentry)
  4936. isdone = true
  4937. break
  4938. } else {
  4939. if len(returnmsgmap1) > 0 {
  4940. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4941. // if tx != nil {
  4942. // tx.Rollback()
  4943. // }
  4944. // if tx != nil {
  4945. // tx.Close()
  4946. // }
  4947. msg := geterrmsg(va.(string))
  4948. outentry["error_msg"] = msg
  4949. error++
  4950. queryData = append(queryData, outentry)
  4951. isdone = true
  4952. break
  4953. }
  4954. }
  4955. isdone = false
  4956. }
  4957. }
  4958. }
  4959. if !errExist {
  4960. dataexcel := make(map[string]interface{}, 0)
  4961. if _, ok := outentry["Pen Name"]; ok {
  4962. dataexcel["barname"] = outentry["Pen Name"]
  4963. }
  4964. if _, ok := outentry["Actual Cattle Number"]; ok {
  4965. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4966. }
  4967. if _, ok := outentry["Coefficient(%)"]; ok {
  4968. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4969. }
  4970. if _, ok := outentry["Formula Template"]; ok {
  4971. dataexcel["ftname"] = outentry["Formula Template"]
  4972. }
  4973. if _, ok := outentry["Supplement Formula"]; ok {
  4974. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4975. }
  4976. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4977. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4978. }
  4979. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4980. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4981. }
  4982. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4983. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4984. }
  4985. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4986. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4987. }
  4988. if _, ok := outentry["Fifth Shift Ratio(%)"]; ok {
  4989. dataexcel["5"] = outentry["Fifth Shift Ratio(%)"]
  4990. }
  4991. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4992. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4993. }
  4994. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4995. if err != nil {
  4996. logs.Error(err)
  4997. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4998. return
  4999. }
  5000. if !existbar {
  5001. continue
  5002. }
  5003. _, 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()
  5004. if err != nil {
  5005. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5006. return
  5007. }
  5008. _, 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()
  5009. if err != nil {
  5010. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5011. return
  5012. }
  5013. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  5014. if err != nil {
  5015. logs.Error(err)
  5016. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  5017. return
  5018. }
  5019. if !existft {
  5020. continue
  5021. }
  5022. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  5023. if err != nil {
  5024. logs.Error(err)
  5025. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5026. return
  5027. }
  5028. if !ftexist {
  5029. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  5030. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5031. if err != nil {
  5032. logs.Error(err)
  5033. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5034. return
  5035. }
  5036. tx.SQL(` update fpdetail set ptuse = 0 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. }
  5043. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5044. if err != nil {
  5045. logs.Error(err)
  5046. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5047. return
  5048. }
  5049. if !exist {
  5050. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  5051. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  5052. if err != nil {
  5053. logs.Error(err)
  5054. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5055. return
  5056. }
  5057. }
  5058. var feedpargs []interface{}
  5059. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  5060. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  5061. if _, ok := dataexcel["ftname"]; ok {
  5062. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  5063. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  5064. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  5065. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  5066. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5067. } else {
  5068. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  5069. }
  5070. if _, ok := dataexcel["ptsfname"]; ok {
  5071. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  5072. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  5073. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  5074. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  5075. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5076. } else {
  5077. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  5078. }
  5079. upFeedpSql += " where barname = ? and pastureid = ? "
  5080. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  5081. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  5082. if err != nil {
  5083. logs.Error(err)
  5084. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5085. return
  5086. }
  5087. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  5088. if err != nil {
  5089. logs.Error(err)
  5090. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5091. return
  5092. }
  5093. if !exist1 {
  5094. _, 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) `,
  5095. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5096. if err != nil {
  5097. logs.Error(err)
  5098. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5099. return
  5100. }
  5101. }
  5102. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5103. if err != nil {
  5104. logs.Error(err)
  5105. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5106. return
  5107. }
  5108. if !exist2 {
  5109. _, 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) `,
  5110. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5111. if err != nil {
  5112. logs.Error(err)
  5113. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5114. return
  5115. }
  5116. }
  5117. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5118. if err != nil {
  5119. logs.Error(err)
  5120. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5121. return
  5122. }
  5123. if !exist3 {
  5124. _, 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) `,
  5125. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5126. if err != nil {
  5127. logs.Error(err)
  5128. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5129. return
  5130. }
  5131. }
  5132. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5133. if err != nil {
  5134. logs.Error(err)
  5135. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5136. return
  5137. }
  5138. if !exist4 {
  5139. _, 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) `,
  5140. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5141. if err != nil {
  5142. logs.Error(err)
  5143. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5144. return
  5145. }
  5146. }
  5147. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5148. if err != nil {
  5149. logs.Error(err)
  5150. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5151. return
  5152. }
  5153. if !exist5 {
  5154. _, 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) `,
  5155. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5156. if err != nil {
  5157. logs.Error(err)
  5158. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5159. return
  5160. }
  5161. }
  5162. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5163. if err != nil {
  5164. logs.Error(err)
  5165. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5166. return
  5167. }
  5168. if !exist6 {
  5169. _, 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) `,
  5170. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5171. if err != nil {
  5172. logs.Error(err)
  5173. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5174. return
  5175. }
  5176. }
  5177. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5178. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5179. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5180. and pastureid = ? and times = ?`
  5181. var fpdargs1 []interface{}
  5182. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5183. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5184. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5185. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5186. if err != nil {
  5187. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5188. return
  5189. }
  5190. var fpdargs2 []interface{}
  5191. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5192. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5193. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5194. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5195. if err != nil {
  5196. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5197. return
  5198. }
  5199. var fpdargs3 []interface{}
  5200. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5201. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5202. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5203. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5204. if err != nil {
  5205. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5206. return
  5207. }
  5208. var fpdargs4 []interface{}
  5209. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5210. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5211. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5212. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5213. if err != nil {
  5214. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5215. return
  5216. }
  5217. var fpdargs5 []interface{}
  5218. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5219. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5220. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5221. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5222. if err != nil {
  5223. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5224. return
  5225. }
  5226. var fpdargs6 []interface{}
  5227. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5228. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5229. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5230. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5231. if err != nil {
  5232. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5233. return
  5234. }
  5235. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5236. 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()
  5237. if err != nil {
  5238. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5239. return
  5240. }
  5241. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5242. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5243. upFpdetailList := make([]*upFpdetail, 0)
  5244. for _, newfpd := range newList {
  5245. for _, oldfpd := range oldFpdList {
  5246. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5247. var oldweight, newweight float64
  5248. if oldfpd["weight"] != nil {
  5249. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5250. }
  5251. if newfpd["weight"] != nil {
  5252. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5253. }
  5254. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5255. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5256. Old: oldweight,
  5257. New: newweight,
  5258. Times: newfpd["times"].(int64),
  5259. Ptid: newfpd["ptid"].(int64),
  5260. Fweight: fweight,
  5261. Id: oldfpd["id"].(int64),
  5262. })
  5263. break
  5264. }
  5265. }
  5266. }
  5267. // fmt.Println(dataexcel["barname"])
  5268. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5269. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5270. }
  5271. }
  5272. if !isdone {
  5273. ok++
  5274. isdone = true
  5275. }
  5276. }
  5277. for barname, v := range dataList {
  5278. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5279. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5280. if err != nil {
  5281. logs.Error(err)
  5282. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5283. return
  5284. }
  5285. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5286. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5287. if err != nil {
  5288. logs.Error(err)
  5289. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5290. return
  5291. }
  5292. updateFpdetailByBar(pastureid, barname, v)
  5293. }
  5294. }
  5295. data := make(map[string]interface{})
  5296. data["result"] = queryData
  5297. data["success"] = ok
  5298. data["err_count"] = error
  5299. appG.Response(http.StatusOK, e.SUCCESS, data)
  5300. }
  5301. type upFpdetail struct {
  5302. Old float64
  5303. New float64
  5304. Times int64
  5305. Ptid int64
  5306. Fweight float64
  5307. Id int64
  5308. // Ptsid string
  5309. }
  5310. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5311. tx := restful.Engine.NewSession()
  5312. defer tx.Close()
  5313. tx.Begin()
  5314. 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 `,
  5315. pastureid, barname).Query().List()
  5316. if err != nil {
  5317. logs.Error(err)
  5318. }
  5319. for _, fpd := range fpdList {
  5320. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5321. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5322. pastureid, fpd["id"], fpd["times"]).Query().List()
  5323. if err != nil {
  5324. tx.Rollback()
  5325. logs.Error(err)
  5326. return err
  5327. }
  5328. var lweight float64
  5329. for _, lppland := range lpplandList {
  5330. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5331. lweight += lweight1
  5332. }
  5333. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5334. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5335. if fpdweight >= ptuse && lweight == ptuse {
  5336. continue
  5337. } else {
  5338. if lweight <= fpdweight {
  5339. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5340. if err != nil {
  5341. tx.Rollback()
  5342. logs.Error(err)
  5343. return err
  5344. }
  5345. } else {
  5346. weight := lweight - fpdweight
  5347. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5348. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5349. if err != nil {
  5350. tx.Rollback()
  5351. logs.Error(err)
  5352. return err
  5353. }
  5354. for _, lppland := range lpplandList {
  5355. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5356. if weight >= lpplandlweight {
  5357. weight = weight - lpplandlweight
  5358. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5359. if err != nil {
  5360. tx.Rollback()
  5361. logs.Error(err)
  5362. return err
  5363. }
  5364. } else {
  5365. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5366. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5367. if err != nil {
  5368. tx.Rollback()
  5369. logs.Error(err)
  5370. return err
  5371. }
  5372. weight = 0
  5373. break
  5374. }
  5375. }
  5376. }
  5377. }
  5378. }
  5379. for _, list := range dataList {
  5380. ftmap := make(map[string]interface{})
  5381. ftmap["old"] = list.Old
  5382. ftmap["new"] = list.New
  5383. ftmap["times"] = list.Times
  5384. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5385. ftmap["ptsid"] = ""
  5386. // fmt.Println(ftmap)
  5387. // 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 ,
  5388. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5389. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5390. // UNION
  5391. fpdDataList, err := tx.SQL(`
  5392. 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 ,
  5393. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5394. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5395. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5396. if err != nil {
  5397. tx.Rollback()
  5398. logs.Error(err)
  5399. }
  5400. for _, fpd := range fpdDataList {
  5401. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5402. // fttype := -1
  5403. // if fpd["fttype"].(string) == "1" {
  5404. fttype := 1
  5405. // }
  5406. var fweight float64
  5407. var lweight float64
  5408. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5409. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  5410. t.maxstirfeed,t.volume * (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  5411. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5412. join tmr t on t.id = lpp.tmrid
  5413. where lppland.fpdid =?
  5414. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5415. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5416. if err != nil {
  5417. tx.Rollback()
  5418. logs.Error(err)
  5419. }
  5420. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5421. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5422. // 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
  5423. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5424. var w float64
  5425. var status int
  5426. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5427. if weight >= 0 {
  5428. continue
  5429. }
  5430. w = weight
  5431. status = 0
  5432. } else {
  5433. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5434. // continue
  5435. // }
  5436. w = weight
  5437. status = 1
  5438. }
  5439. // for _, lppland := range lpplandtl1List {
  5440. // lweight += lppland.Lweight
  5441. // }
  5442. for _, lppland := range lpplandtl1List {
  5443. lpplandInfo := new(lpplandtlInfo)
  5444. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5445. lweight = lpplandInfo.Lweight
  5446. if status == 1 {
  5447. // if w <= lppland.Lweight {
  5448. if lppland.Maxweight <= lweight {
  5449. continue
  5450. }
  5451. if w+lweight <= lppland.Maxweight {
  5452. lppland.Lweight += w
  5453. lweight += w
  5454. fweight += w
  5455. w = 0
  5456. } else {
  5457. w = w - (lppland.Maxweight - lweight)
  5458. n := (lppland.Maxweight - lweight)
  5459. lppland.Lweight = lppland.Lweight + n
  5460. lweight += n
  5461. fweight += n
  5462. }
  5463. } else {
  5464. if lppland.Lweight == 0 {
  5465. continue
  5466. }
  5467. if w+lppland.Lweight >= 0 {
  5468. lppland.Lweight = lppland.Lweight + w
  5469. lweight = lweight + w
  5470. fweight = fweight + w
  5471. w = 0
  5472. } else {
  5473. w = w + lppland.Lweight
  5474. lweight = lweight - lppland.Lweight
  5475. fweight = fweight - lppland.Lweight
  5476. lppland.Lweight = 0
  5477. }
  5478. }
  5479. if lppland.Lweight > 0 {
  5480. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5481. if err != nil {
  5482. tx.Rollback()
  5483. logs.Error(err)
  5484. return err
  5485. }
  5486. } else {
  5487. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5488. if err != nil {
  5489. tx.Rollback()
  5490. logs.Error(err)
  5491. return err
  5492. }
  5493. }
  5494. if w == 0 {
  5495. break
  5496. }
  5497. }
  5498. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5499. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5500. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5501. if err != nil {
  5502. tx.Rollback()
  5503. logs.Error(err)
  5504. }
  5505. if w == 0 {
  5506. break
  5507. }
  5508. }
  5509. }
  5510. }
  5511. err = tx.Commit()
  5512. if err != nil {
  5513. logs.Error(err)
  5514. tx.Rollback()
  5515. return err
  5516. }
  5517. now := time.Now()
  5518. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5519. if err != nil {
  5520. logs.Error(err)
  5521. return nil
  5522. }
  5523. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5524. if err != nil {
  5525. logs.Error(err)
  5526. return nil
  5527. }
  5528. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5529. if err != nil {
  5530. logs.Error(err)
  5531. return nil
  5532. }
  5533. for _, newLpplandtl1 := range newLpplandtl1List {
  5534. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5535. background,cowcount,ccountradio,lweighthis,createdate)
  5536. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5537. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5538. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5539. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5540. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5541. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5542. if err != nil {
  5543. logs.Error(err)
  5544. // appG.Response(http.StatusOK, e.ERROR, false)
  5545. return err
  5546. }
  5547. }
  5548. for _, newFpd := range newFpdDataList {
  5549. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5550. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5551. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5552. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5553. if err != nil {
  5554. logs.Error(err)
  5555. // appG.Response(http.StatusOK, e.ERROR, false)
  5556. return err
  5557. }
  5558. }
  5559. for _, newFeedp := range newFeedpList {
  5560. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5561. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5562. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5563. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5564. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5565. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5566. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5567. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5568. if err != nil {
  5569. logs.Error(err)
  5570. // appG.Response(http.StatusOK, e.ERROR, false)
  5571. return err
  5572. }
  5573. }
  5574. return nil
  5575. }
  5576. func DeleteFTdetail(c *gin.Context) {
  5577. appG := app.Gin{C: c}
  5578. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5579. fsion := gofasion.NewFasion(string(dataByte))
  5580. parammaps := fsion.Get("parammaps")
  5581. pastureid := parammaps.Get("pastureid").ValueStr()
  5582. ftid := parammaps.Get("ftid").ValueStr()
  5583. tx := restful.Engine.NewSession()
  5584. defer tx.Close()
  5585. tx.Begin()
  5586. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5587. if err != nil {
  5588. tx.Rollback()
  5589. logs.Error(err)
  5590. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5591. return
  5592. }
  5593. if parammaps.Get("type").ValueStr() == "1" {
  5594. _, err := tx.SQL(`UPDATE feedp fp
  5595. set
  5596. fp.ftweight= IFNULL(IF(
  5597. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5598. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5599. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5600. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5601. ),0),fp.feedweight = IFNULL(IF(
  5602. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5603. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5604. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5605. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5606. ),0) +ifnull(fp.supplyweight,0)
  5607. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5608. if err != nil {
  5609. tx.Rollback()
  5610. logs.Error(err)
  5611. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5612. return
  5613. }
  5614. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5615. _, err = tx.SQL(`
  5616. UPDATE fpdetail fpd
  5617. INNER JOIN feedp fp
  5618. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5619. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5620. ptuse= 0
  5621. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5622. if err != nil {
  5623. tx.Rollback()
  5624. logs.Error(err)
  5625. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5626. return
  5627. }
  5628. } else {
  5629. _, err := tx.SQL(`UPDATE feedp fp
  5630. SET
  5631. fp.supplyweight= IFNULL(IF(
  5632. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5633. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5634. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5635. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5636. ),0),fp.feedweight = IFNULL(IF(
  5637. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5638. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5639. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5640. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5641. ),0) + ifnull(fp.supplyweight,0)
  5642. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5643. if err != nil {
  5644. tx.Rollback()
  5645. logs.Error(err)
  5646. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5647. return
  5648. }
  5649. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5650. _, err = tx.SQL(`
  5651. UPDATE fpdetail fpd
  5652. INNER JOIN feedp fp
  5653. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5654. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5655. ptsrate = 0
  5656. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5657. if err != nil {
  5658. tx.Rollback()
  5659. logs.Error(err)
  5660. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5661. return
  5662. }
  5663. }
  5664. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5665. if err != nil {
  5666. tx.Rollback()
  5667. logs.Error(err)
  5668. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5669. return
  5670. }
  5671. err = tx.Commit()
  5672. if err != nil {
  5673. tx.Rollback()
  5674. logs.Error(err)
  5675. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5676. return
  5677. }
  5678. appG.Response(http.StatusOK, e.SUCCESS, true)
  5679. }
  5680. func DeleteSpillageAll(c *gin.Context) {
  5681. appG := app.Gin{C: c}
  5682. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5683. fsion := gofasion.NewFasion(string(dataByte))
  5684. parammaps := fsion.Get("parammaps")
  5685. pastureid := parammaps.Get("pastureid").ValueStr()
  5686. times := parammaps.Get("times").ValueStr()
  5687. barid := parammaps.Get("barid").ValueStr()
  5688. tx := restful.Engine.NewSession()
  5689. defer tx.Close()
  5690. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5691. if err != nil {
  5692. logs.Error(err)
  5693. appG.Response(http.StatusOK, e.ERROR, false)
  5694. return
  5695. }
  5696. now := time.Now()
  5697. for _, item := range lpplandtl1List {
  5698. go func(item map[string]interface{}) {
  5699. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5700. background,cowcount,ccountradio,lweighthis,createdate)
  5701. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5702. item["pastureid"], item["lppid"], item["barid"],
  5703. item["barname"], item["fpdid"], item["fttype"],
  5704. item["lweight"], item["sort"], item["tmrid"],
  5705. item["tmrname"], item["background"], item["cowcount"],
  5706. item["ccountradio"], item["lweighthis"], now).Execute()
  5707. if err != nil {
  5708. logs.Error(err)
  5709. appG.Response(http.StatusOK, e.ERROR, false)
  5710. return
  5711. }
  5712. }(item)
  5713. }
  5714. tx.Begin()
  5715. _, 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()
  5716. if err != nil {
  5717. tx.Rollback()
  5718. logs.Error(err)
  5719. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5720. return
  5721. }
  5722. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5723. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5724. if err != nil {
  5725. tx.Rollback()
  5726. logs.Error(err)
  5727. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5728. return
  5729. }
  5730. err = tx.Commit()
  5731. if err != nil {
  5732. tx.Rollback()
  5733. logs.Error(err)
  5734. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5735. return
  5736. }
  5737. appG.Response(http.StatusOK, e.SUCCESS, true)
  5738. }
  5739. func GetTMRListEnableTypeAll(c *gin.Context) {
  5740. appG := app.Gin{C: c}
  5741. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5742. fsion := gofasion.NewFasion(string(dataByte))
  5743. parammaps := fsion.Get("parammaps")
  5744. pastureid := parammaps.Get("pastureid").ValueStr()
  5745. tx := restful.Engine.NewSession()
  5746. defer tx.Close()
  5747. dataList, err := tx.SQL(`SELECT
  5748. eqcode,
  5749. tname,
  5750. datacaptureno,
  5751. trim(tclassid) tclassid,
  5752. concat(tname,' / ',eqcode) tmrmix,
  5753. d.label tclassname,
  5754. maxstirfeed,
  5755. remark,
  5756. tmr.enable,
  5757. TRIM(tmr.id) id,
  5758. TRIM(tmr.pastureid)pastureid
  5759. FROM
  5760. tmr
  5761. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5762. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5763. ORDER BY id DESC`, pastureid).Query().List()
  5764. if err != nil {
  5765. logs.Error(err)
  5766. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5767. return
  5768. }
  5769. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5770. if err != nil {
  5771. logs.Error(err)
  5772. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5773. return
  5774. }
  5775. var carNum int64
  5776. for _, sysopt := range sysoptData {
  5777. if sysopt["inforvalue"] == nil {
  5778. carNum = 1
  5779. } else {
  5780. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5781. }
  5782. }
  5783. id := 200
  5784. n := 0
  5785. for i := carNum; i > 0; i-- {
  5786. id++
  5787. n++
  5788. data := make(map[string]interface{}, 0)
  5789. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5790. data["tname"] = fmt.Sprintf("任意车%d", n)
  5791. data["datacaptureno"] = -2
  5792. data["tclassid"] = -2
  5793. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5794. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5795. data["maxstirfeed"] = 100000
  5796. data["remark"] = fmt.Sprintf("任意车%d", n)
  5797. data["enable"] = 1
  5798. data["id"] = fmt.Sprintf("%d", id)
  5799. data["pastureid"] = pastureid
  5800. // data := make(map[string]interface{}, 0)
  5801. // data["eqcode"] = fmt.Sprintf("AnyCar%d", n)
  5802. // data["tname"] = fmt.Sprintf("AnyCar%d", n)
  5803. // data["datacaptureno"] = -2
  5804. // data["tclassid"] = -2
  5805. // data["tmrmix"] = fmt.Sprintf("AnyCar%d", n)
  5806. // data["tclassname"] = fmt.Sprintf("AnyCar%d", n)
  5807. // data["maxstirfeed"] = 100000
  5808. // data["remark"] = fmt.Sprintf("AnyCar%d", n)
  5809. // data["enable"] = 1
  5810. // data["id"] = fmt.Sprintf("%d", id)
  5811. // data["pastureid"] = pastureid
  5812. dataList = append(dataList, data)
  5813. }
  5814. // UNION ALL
  5815. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5816. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5817. }
  5818. func GetFeedpHistory(c *gin.Context) {
  5819. appG := app.Gin{C: c}
  5820. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5821. fsion := gofasion.NewFasion(string(dataByte))
  5822. // parammaps := fsion.Get("parammaps")
  5823. bar := fsion.Get("barname").ValueStr()
  5824. startDate := fsion.Get("startDate").ValueStr()
  5825. endDate := fsion.Get("endDate").ValueStr()
  5826. tx := restful.Engine.NewSession()
  5827. defer tx.Close()
  5828. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5829. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5830. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5831. if err != nil {
  5832. logs.Error(err)
  5833. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5834. return
  5835. }
  5836. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5837. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5838. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5839. if err != nil {
  5840. logs.Error(err)
  5841. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5842. return
  5843. }
  5844. for _, feedp := range feedpList {
  5845. // LastftList, err := tx.SQL(` select tname ,id
  5846. // from feedtemplethistory where id = ?
  5847. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5848. // if err != nil {
  5849. // logs.Error(err)
  5850. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5851. // return
  5852. // }
  5853. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5854. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5855. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5856. if err != nil {
  5857. logs.Error(err)
  5858. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5859. return
  5860. }
  5861. var ftname interface{}
  5862. ftnamestatus := 0
  5863. ftname = feedp["ftname"]
  5864. var lastftid int64
  5865. if len(nextfeedpList) > 0 {
  5866. for _, ft := range nextfeedpList {
  5867. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5868. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5869. lastftid = ft["ftid"].(int64)
  5870. ftnamestatus = 1
  5871. break
  5872. }
  5873. }
  5874. }
  5875. for i, fpd := range fpdList {
  5876. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5877. fpd["weightstatus"] = 0
  5878. fpd["tratiostatus"] = 0
  5879. fpd["ftnamestatus"] = ftnamestatus
  5880. for k, fpd2 := range fpdList {
  5881. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5882. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5883. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5884. fpd["weightstatus"] = 1
  5885. }
  5886. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5887. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5888. fpd["tratiostatus"] = 1
  5889. }
  5890. break
  5891. }
  5892. }
  5893. fpd["barid"] = feedp["barid"]
  5894. fpd["barname"] = feedp["barname"]
  5895. fpd["ccount"] = feedp["ccount"]
  5896. fpd["ratio"] = feedp["ratio"]
  5897. fpd["ccountratio"] = feedp["ccountratio"]
  5898. fpd["ftid"] = feedp["ftid"]
  5899. fpd["ftname"] = ftname
  5900. fpd["ccountstatus"] = 0
  5901. fpd["ccountratiostatus"] = 0
  5902. fpd["ratiostatus"] = 0
  5903. fpd["ftnamestatus"] = 0
  5904. fpd["lastftid"] = lastftid
  5905. for _, next := range nextfeedpList {
  5906. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5907. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5908. fpd["ccountstatus"] = 1
  5909. }
  5910. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5911. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5912. fpd["ccountratiostatus"] = 1
  5913. }
  5914. if next["ratio"].(string) != fpd["ratio"].(string) {
  5915. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5916. fpd["ratiostatus"] = 1
  5917. }
  5918. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5919. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5920. // fpd["ftnamestatus"] = 1
  5921. // }
  5922. }
  5923. }
  5924. }
  5925. }
  5926. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5927. }
  5928. // func GetLpplandtl1History(c *gin.Context) {
  5929. // appG := app.Gin{C: c}
  5930. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5931. // fsion := gofasion.NewFasion(string(dataByte))
  5932. // // parammaps := fsion.Get("parammaps")
  5933. // barid := fsion.Get("barid").ValueStr()
  5934. // startDate := fsion.Get("startDate").ValueStr()
  5935. // endDate := fsion.Get("endDate").ValueStr()
  5936. // tx := restful.Engine.NewSession()
  5937. // defer tx.Close()
  5938. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5939. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5940. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5941. // // if err != nil {
  5942. // // logs.Error(err)
  5943. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5944. // // return
  5945. // // }
  5946. // // for _, feedp := range feedpList {
  5947. // // fmt.Println(feedp)
  5948. // // for i, fpd := range fpdList {
  5949. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5950. // // for k, fpd2 := range fpdList {
  5951. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5952. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5953. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5954. // // }
  5955. // // break
  5956. // // }
  5957. // // }
  5958. // // fpd["barid"] = feedp["barid"]
  5959. // // fpd["barname"] = feedp["barname"]
  5960. // // fpd["ccount"] = feedp["ccount"]
  5961. // // fpd["ratio"] = feedp["ratio"]
  5962. // // fpd["ccountratio"] = feedp["ccountratio"]
  5963. // // fpd["ftid"] = feedp["ftid"]
  5964. // // fpd["ftname"] = feedp["ftname"]
  5965. // // }
  5966. // // }
  5967. // // }
  5968. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5969. // }
  5970. func GetRemind(c *gin.Context) {
  5971. appG := app.Gin{C: c}
  5972. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5973. fsion := gofasion.NewFasion(string(dataByte))
  5974. parammaps := fsion.Get("parammaps")
  5975. pastureid := parammaps.Get("pastureid").ValueStr()
  5976. tx := restful.Engine.NewSession()
  5977. defer tx.Close()
  5978. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5979. if err != nil {
  5980. logs.Error(err)
  5981. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5982. return
  5983. }
  5984. // pastureid = "3"
  5985. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5986. if err != nil {
  5987. logs.Error(err)
  5988. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5989. return
  5990. }
  5991. defer resp.Body.Close()
  5992. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5993. buf.ReadFrom(resp.Body)
  5994. fmt.Println(string(buf.Bytes()))
  5995. respMap := make(map[string]interface{}, 0)
  5996. err = json.Unmarshal(buf.Bytes(), &respMap)
  5997. if err != nil {
  5998. logs.Error(err)
  5999. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6000. return
  6001. }
  6002. for _, data := range dataList {
  6003. r := make(map[string]interface{}, 0)
  6004. r["sys_name"] = ""
  6005. r["service_id"] = ""
  6006. r["pasture_id"] = ""
  6007. r["type_name"] = ""
  6008. r["remind_type_id"] = ""
  6009. r["remind_type"] = ""
  6010. r["push_date"] = ""
  6011. r["push_time"] = ""
  6012. r["interval_time"] = ""
  6013. r["push_limit"] = ""
  6014. r["template_id"] = ""
  6015. r["roles_id"] = ""
  6016. r["users_id"] = ""
  6017. r["date_type"] = ""
  6018. r["cycle_type"] = ""
  6019. data["data"] = r
  6020. for _, resp := range respMap["data"].([]interface{}) {
  6021. resp1 := resp.(map[string]interface{})
  6022. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  6023. if resp1["push_time"] == nil {
  6024. resp1["push_time"] = ""
  6025. }
  6026. data["data"] = resp1
  6027. break
  6028. }
  6029. }
  6030. }
  6031. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  6032. }
  6033. type NoticeMsgtype struct {
  6034. SysName string `json:"sys_name"`
  6035. PastureId int64 `json:"pasture_id"`
  6036. ServiceId int64 `json:"service_id"`
  6037. TypeName string `json:"type_name"`
  6038. RemindType int64 `json:"remind_type"`
  6039. PushDate int64 `json:"push_date"`
  6040. PushTime string `json:"push_time"`
  6041. IntervalTime int64 `json:"interval_time"`
  6042. PushLimit int64 `json:"push_limit"`
  6043. TemplateId string `json:"template_id"`
  6044. UsersId string `json:"users_id"`
  6045. DateType int64 `json:"date_type"`
  6046. CycleType int64 `json:"cycle_type"`
  6047. DelayTime int64 `json:"delay_time"`
  6048. Status int64 `json:"status"`
  6049. }
  6050. func UpdateRemind(c *gin.Context) {
  6051. appG := app.Gin{C: c}
  6052. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6053. parammaps := gofasion.NewFasion(string(dataByte))
  6054. // parammaps := fsion.Get("parammaps")
  6055. // user := parammaps.Get("user").ValueStr()
  6056. id := parammaps.Get("id").ValueInt64()
  6057. noticeMsgtype := new(NoticeMsgtype)
  6058. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  6059. noticeMsgtype.ServiceId = id
  6060. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  6061. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  6062. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  6063. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  6064. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  6065. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  6066. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  6067. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  6068. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  6069. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  6070. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  6071. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  6072. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  6073. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  6074. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  6075. //TODO
  6076. noticeMsgtype.SysName = "tmrWatch"
  6077. userList := parammaps.Get("user").Array()
  6078. var userstr []string
  6079. for _, user := range userList {
  6080. userstr = append(userstr, user.ValueStr())
  6081. }
  6082. tx := restful.Engine.NewSession()
  6083. defer tx.Close()
  6084. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  6085. if err != nil {
  6086. logs.Error(err)
  6087. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6088. return
  6089. }
  6090. // var jsonStr = []byte(noticeMsgtype
  6091. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  6092. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  6093. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  6094. req.Header.Set("Content-Type", "application/json")
  6095. client := &http.Client{}
  6096. resp, err := client.Do(req)
  6097. if err != nil {
  6098. logs.Error(err)
  6099. }
  6100. defer resp.Body.Close()
  6101. body, _ := ioutil.ReadAll(resp.Body)
  6102. fmt.Println("response Body:", string(body))
  6103. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  6104. if err != nil {
  6105. logs.Error(err)
  6106. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6107. return
  6108. }
  6109. defer getresp.Body.Close()
  6110. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6111. buf.ReadFrom(getresp.Body)
  6112. // fmt.Println(string(buf.Bytes()))
  6113. respMap := make(map[string]interface{}, 0)
  6114. err = json.Unmarshal(buf.Bytes(), &respMap)
  6115. if err != nil {
  6116. logs.Error(err)
  6117. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6118. return
  6119. }
  6120. for _, resp := range respMap["data"].([]interface{}) {
  6121. resp1 := resp.(map[string]interface{})
  6122. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6123. if err != nil {
  6124. logs.Error(err)
  6125. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6126. return
  6127. }
  6128. }
  6129. appG.Response(http.StatusOK, e.SUCCESS, true)
  6130. }
  6131. func GetSpillageallHistory(c *gin.Context) {
  6132. appG := app.Gin{C: c}
  6133. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6134. parammaps := gofasion.NewFasion(string(dataByte))
  6135. barname := parammaps.Get("barname").ValueStr()
  6136. pastureid := parammaps.Get("pastureid").ValueStr()
  6137. startdate := parammaps.Get("startDate").ValueStr()
  6138. enddate := parammaps.Get("endDate").ValueStr()
  6139. tx := restful.Engine.NewSession()
  6140. defer tx.Close()
  6141. historyList, err := tx.SQL(` select lpp.id,lpp.times,lppland.lweight,lppland.tmrid,lppland.tmrname,lpp.sort,
  6142. DATE_FORMAT(lppland.createdate,'%Y-%m-%d %H:%i:%s') as createdate ,u.username
  6143. from lpplandtl1history lppland
  6144. join lpplan lpp on lpp.id = lppland.lppid
  6145. left join user u on u.id = lppland.userId
  6146. where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6147. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6148. if err != nil {
  6149. logs.Error(err)
  6150. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6151. return
  6152. }
  6153. respMap := make([]map[string]interface{}, 0)
  6154. data := make(map[interface{}]interface{})
  6155. for _, history := range historyList {
  6156. data[history["createdate"]] = history["createdate"]
  6157. }
  6158. createList := []string{}
  6159. for _, v := range data {
  6160. createList = append(createList, v.(string))
  6161. }
  6162. // sort.Sort()
  6163. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6164. sort.Slice(createList, func(i, j int) bool {
  6165. return createList[i] > createList[j]
  6166. })
  6167. for _, v := range createList {
  6168. a := make(map[string]interface{})
  6169. a["createdate"] = data[v]
  6170. // createList = append(createList, v.(string))
  6171. respMap = append(respMap, a)
  6172. }
  6173. number := 0
  6174. dataMap := make([]interface{}, 0)
  6175. for k, resp := range respMap {
  6176. createdate := resp["createdate"].(string)
  6177. var nextcreatedate string
  6178. if len(respMap) > k+1 {
  6179. nextcreatedate = respMap[k+1]["createdate"].(string)
  6180. }
  6181. // dataList := make(map[string][]interface{})
  6182. // list := make(map[string]interface{})
  6183. times := make(map[interface{}]int)
  6184. for _, history := range historyList {
  6185. // List := make(map[interface{}][]interface{})
  6186. i := 0
  6187. if history["createdate"].(string) == createdate {
  6188. times[history["times"]]++
  6189. data := make(map[string]interface{})
  6190. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6191. // exist := false
  6192. if nextcreatedate != "" {
  6193. for _, history1 := range historyList {
  6194. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6195. history1["times"].(int64) == history["times"].(int64) {
  6196. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6197. break
  6198. // exist = true
  6199. }
  6200. }
  6201. }
  6202. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6203. i++
  6204. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6205. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6206. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6207. // resp["times"] = history["times"]
  6208. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6209. data1 := make(map[string]interface{})
  6210. data1["times"] = history["times"]
  6211. data1["empname"] = history["username"]
  6212. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6213. data1["createdate"] = resp["createdate"]
  6214. // fmt.Println(dataList)
  6215. dataMap = append(dataMap, data1)
  6216. }
  6217. if i > number {
  6218. number = i
  6219. }
  6220. // respMap = append(respMap, dataList)
  6221. }
  6222. // for k, data := range dataList {
  6223. // resp[k] = data
  6224. // }
  6225. // resp["data"] = dataList
  6226. }
  6227. // resp := make(map[string]interface{})
  6228. // sort.Strings(createList)
  6229. //
  6230. // for _, create := range createList {
  6231. // for _, r := range respMap {
  6232. // if create == r["createdate"].(string) {
  6233. // resp[create] = r
  6234. // break
  6235. // }
  6236. // }
  6237. // }
  6238. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6239. var trainsList []interface{}
  6240. for i := 0; i < number; i++ {
  6241. trains := make(map[string]interface{})
  6242. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6243. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6244. trainsList = append(trainsList, trains)
  6245. }
  6246. respdata := make(map[string]interface{})
  6247. respdata["data"] = dataMap
  6248. respdata["trains"] = trainsList
  6249. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6250. }
  6251. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6252. appG := app.Gin{C: c}
  6253. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6254. parammaps := gofasion.NewFasion(string(dataByte))
  6255. ftid := parammaps.Get("ftid").ValueInt64()
  6256. lastftid := parammaps.Get("lastftid").ValueInt64()
  6257. pastureid := parammaps.Get("pastureid").ValueInt64()
  6258. // createdate := parammaps.Get("createdate").ValueStr()
  6259. tx := restful.Engine.NewSession()
  6260. defer tx.Close()
  6261. data := make(map[string]interface{})
  6262. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6263. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6264. if err != nil {
  6265. logs.Error(err)
  6266. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6267. return
  6268. }
  6269. feedtemplet := make(map[string]interface{})
  6270. for _, f := range feedtempletList {
  6271. feedtemplet = f
  6272. }
  6273. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  6274. if err != nil {
  6275. logs.Error(err)
  6276. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6277. return
  6278. }
  6279. feedtemplet["fit"] = fitList
  6280. data["current"] = feedtemplet
  6281. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6282. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6283. if err != nil {
  6284. logs.Error(err)
  6285. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6286. return
  6287. }
  6288. lastfeedtemplet := make(map[string]interface{})
  6289. for _, f := range lastfeedtempletList {
  6290. lastfeedtemplet = f
  6291. }
  6292. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  6293. if err != nil {
  6294. logs.Error(err)
  6295. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6296. return
  6297. }
  6298. lastfeedtemplet["fit"] = lastfitList
  6299. data["last"] = lastfeedtemplet
  6300. appG.Response(http.StatusOK, e.SUCCESS, data)
  6301. }
  6302. func GetFeedtempletHistory(c *gin.Context) {
  6303. appG := app.Gin{C: c}
  6304. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6305. parammaps := gofasion.NewFasion(string(dataByte))
  6306. ftid := parammaps.Get("ftid").ValueStr()
  6307. pastureid := parammaps.Get("pastureid").ValueInt64()
  6308. start := parammaps.Get("startdate").ValueStr()
  6309. end := parammaps.Get("enddate").ValueStr()
  6310. tx := restful.Engine.NewSession()
  6311. defer tx.Close()
  6312. 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 ?
  6313. and id = ? and pastureid = ? order by createdate desc `,
  6314. start, end, ftid, pastureid).Query().List()
  6315. if err != nil {
  6316. logs.Error(err)
  6317. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6318. return
  6319. }
  6320. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6321. ftid, pastureid).Query().List()
  6322. if err != nil {
  6323. logs.Error(err)
  6324. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6325. return
  6326. }
  6327. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6328. for i, ft := range ftList {
  6329. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6330. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6331. (select empname from user where id = fit.userId) empname,
  6332. 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
  6333. where fit.fitid = ?
  6334. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6335. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6336. if err != nil {
  6337. logs.Error(err)
  6338. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6339. return
  6340. }
  6341. ft["createdate"] = ft["createdate1"]
  6342. // data["tname"] = ft["tname"]
  6343. // data["tcode"] = ft["tcode"]
  6344. // data["tcolor"] = ft["tcolor"]
  6345. // data["fttype"] = ft["fttype"]
  6346. // data["ccname"] = ft["ccname"]
  6347. // data["source"] = ft["source"]
  6348. // data["version"] = ft["version"]
  6349. // data["remark"] = ft["remark"]
  6350. for n, ft2 := range ftList {
  6351. if i < n {
  6352. if ft["tname"].(string) != ft2["tname"].(string) {
  6353. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6354. }
  6355. if _, ok := ft["tcode"]; ok {
  6356. if _, ok := ft2["tcode"]; ok {
  6357. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6358. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6359. }
  6360. }
  6361. }
  6362. if _, ok := ft["tcolor"]; ok {
  6363. if _, ok := ft2["tcolor"]; ok {
  6364. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6365. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6366. }
  6367. }
  6368. }
  6369. if _, ok := ft["fttype"]; ok {
  6370. if _, ok := ft2["fttype"]; ok {
  6371. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6372. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6373. }
  6374. }
  6375. }
  6376. if _, ok := ft["ccname"]; ok {
  6377. if _, ok := ft2["ccname"]; ok {
  6378. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6379. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6380. }
  6381. }
  6382. }
  6383. if _, ok := ft["source"]; ok {
  6384. if _, ok := ft2["source"]; ok {
  6385. if ft["source"].(string) != ft2["source"].(string) {
  6386. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6387. }
  6388. }
  6389. }
  6390. if _, ok := ft["version"]; ok {
  6391. if _, ok := ft2["version"]; ok {
  6392. if ft["version"].(int64) != ft2["version"].(int64) {
  6393. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6394. }
  6395. }
  6396. }
  6397. if _, ok := ft["remark"]; ok {
  6398. if _, ok := ft2["remark"]; ok {
  6399. if ft["remark"].(string) != ft2["remark"].(string) {
  6400. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6401. }
  6402. }
  6403. }
  6404. break
  6405. }
  6406. }
  6407. dataList := make([]map[string]interface{}, 0)
  6408. if len(fithisList) > 0 {
  6409. for _, fit := range fithisList {
  6410. data := make(map[string]interface{})
  6411. data["feedgroup"] = fit["feedgroup"]
  6412. data["fname"] = fit["fname"]
  6413. data["empname"] = fit["empname"]
  6414. if fit["Eweight"] != nil {
  6415. if fit["Eweight"].(string) != fit["weight"].(string) {
  6416. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6417. } else {
  6418. data["fweight"] = fit["Eweight"]
  6419. }
  6420. data["fweightstatus"] = 1
  6421. } else {
  6422. data["fweight"] = fit["weight"]
  6423. data["fweightstatus"] = 0
  6424. }
  6425. data["autosecond"] = fit["autosecond"]
  6426. // data["tname"] = ft["tname"]
  6427. // data["tcode"] = ft["tcode"]
  6428. // data["tcolor"] = ft["tcolor"]
  6429. // data["fttype"] = ft["fttype"]
  6430. // data["ccname"] = ft["ccname"]
  6431. // data["source"] = ft["source"]
  6432. // data["version"] = ft["version"]
  6433. // data["remark"] = ft["remark"]
  6434. // data["createdate"] = ft["createdate1"]
  6435. // ft["fit"] = data
  6436. dataList = append(dataList, data)
  6437. }
  6438. } else {
  6439. for _, fit := range ftdetailList {
  6440. data := make(map[string]interface{})
  6441. data["feedgroup"] = fit["feedgroup"]
  6442. data["fname"] = fit["fname"]
  6443. // if fit["Eweight"] != nil {
  6444. // data["weight"] = fit["Eweight"]
  6445. // } else {
  6446. data["fweight"] = fit["fweight"]
  6447. // }
  6448. data["autosecond"] = fit["autosecond"]
  6449. // ft["fit"] = data
  6450. dataList = append(dataList, data)
  6451. }
  6452. }
  6453. ft["fit"] = dataList
  6454. }
  6455. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6456. }
  6457. func UpdateMaterialTMR(c *gin.Context) {
  6458. appG := app.Gin{C: c}
  6459. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6460. parammaps := gofasion.NewFasion(string(dataByte))
  6461. tmrid := parammaps.Get("tmrid").ValueStr()
  6462. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6463. lppid := parammaps.Get("lppid").ValueStr()
  6464. times := parammaps.Get("times").ValueStr()
  6465. pastureid := parammaps.Get("pastureid").ValueStr()
  6466. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6467. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6468. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6469. tx := restful.Engine.NewSession()
  6470. defer tx.Close()
  6471. tx.Begin()
  6472. if tmrid != "1000" {
  6473. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6474. if err != nil {
  6475. logs.Error(err)
  6476. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6477. return
  6478. }
  6479. var maxstirfeed float64
  6480. for _, tmr := range tmrList {
  6481. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6482. }
  6483. if status == 0 {
  6484. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6485. if err != nil {
  6486. tx.Rollback()
  6487. logs.Error(err)
  6488. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6489. return
  6490. }
  6491. var lweight float64
  6492. for _, item := range lpplandtl1List {
  6493. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6494. lweight += fl
  6495. }
  6496. if lweight > maxstirfeed {
  6497. lweight = lweight - maxstirfeed
  6498. } else {
  6499. lweight = 0
  6500. }
  6501. if lweight > 0 {
  6502. lweight1 := lweight / float64(len(lpplandtl1List))
  6503. number := 0
  6504. for _, item := range lpplandtl1List {
  6505. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6506. if lweight1 >= fl {
  6507. number++
  6508. }
  6509. }
  6510. lweight := lweight / float64((len(lpplandtl1List) - number))
  6511. for _, item := range lpplandtl1List {
  6512. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6513. if lweight1 >= fl {
  6514. continue
  6515. }
  6516. if tmrtype == "1" {
  6517. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6518. if err != nil {
  6519. tx.Rollback()
  6520. logs.Error(err)
  6521. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6522. return
  6523. }
  6524. } else if tmrtype == "2" {
  6525. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6526. if err != nil {
  6527. tx.Rollback()
  6528. logs.Error(err)
  6529. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6530. return
  6531. }
  6532. }
  6533. if item["fttype"].(int64) == 0 {
  6534. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6535. if err != nil {
  6536. tx.Rollback()
  6537. logs.Error(err)
  6538. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6539. return
  6540. }
  6541. } else {
  6542. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6543. if err != nil {
  6544. tx.Rollback()
  6545. logs.Error(err)
  6546. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6547. return
  6548. }
  6549. }
  6550. }
  6551. } else {
  6552. for _, item := range lpplandtl1List {
  6553. // 自走式
  6554. if tmrtype == "1" {
  6555. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6556. if err != nil {
  6557. logs.Error(err)
  6558. tx.Rollback()
  6559. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6560. return
  6561. }
  6562. } else if tmrtype == "2" {
  6563. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6564. if err != nil {
  6565. logs.Error(err)
  6566. tx.Rollback()
  6567. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6568. return
  6569. }
  6570. }
  6571. }
  6572. }
  6573. } else if status == 1 {
  6574. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6575. if err != nil {
  6576. logs.Error(err)
  6577. tx.Rollback()
  6578. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6579. return
  6580. }
  6581. var lweight float64
  6582. for _, item := range lpplandtl1List {
  6583. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6584. lweight += fl
  6585. }
  6586. if lweight > maxstirfeed {
  6587. lweight = lweight - maxstirfeed
  6588. } else {
  6589. lweight = 0
  6590. }
  6591. for _, item := range lpplandtl1List {
  6592. if lweight > 0 {
  6593. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6594. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6595. if fl >= lweight {
  6596. item["lweight"] = fl - lweight
  6597. lweight = 0
  6598. if tmrtype == "1" {
  6599. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6600. if err != nil {
  6601. logs.Error(err)
  6602. tx.Rollback()
  6603. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6604. return
  6605. }
  6606. } else if tmrtype == "2" {
  6607. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6608. if err != nil {
  6609. logs.Error(err)
  6610. tx.Rollback()
  6611. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6612. return
  6613. }
  6614. }
  6615. if item["fttype"].(int64) == 0 {
  6616. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6617. if err != nil {
  6618. logs.Error(err)
  6619. tx.Rollback()
  6620. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6621. return
  6622. }
  6623. } else {
  6624. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6625. if err != nil {
  6626. logs.Error(err)
  6627. tx.Rollback()
  6628. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6629. return
  6630. }
  6631. }
  6632. } else {
  6633. lweight = lweight - fl
  6634. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6635. if err != nil {
  6636. logs.Error(err)
  6637. tx.Rollback()
  6638. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6639. return
  6640. }
  6641. if item["fttype"].(int64) == 0 {
  6642. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6643. if err != nil {
  6644. logs.Error(err)
  6645. tx.Rollback()
  6646. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6647. return
  6648. }
  6649. } else {
  6650. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6651. if err != nil {
  6652. logs.Error(err)
  6653. tx.Rollback()
  6654. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6655. return
  6656. }
  6657. }
  6658. }
  6659. } else {
  6660. // 自走式
  6661. if tmrtype == "1" {
  6662. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6663. if err != nil {
  6664. logs.Error(err)
  6665. tx.Rollback()
  6666. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6667. return
  6668. }
  6669. } else if tmrtype == "2" {
  6670. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6671. if err != nil {
  6672. logs.Error(err)
  6673. tx.Rollback()
  6674. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6675. return
  6676. }
  6677. }
  6678. }
  6679. }
  6680. } else {
  6681. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6682. if err != nil {
  6683. logs.Error(err)
  6684. tx.Rollback()
  6685. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6686. return
  6687. }
  6688. for _, item := range lpplandtl1List {
  6689. if item["fttype"].(int64) == 0 {
  6690. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6691. if err != nil {
  6692. logs.Error(err)
  6693. tx.Rollback()
  6694. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6695. return
  6696. }
  6697. } else {
  6698. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6699. if err != nil {
  6700. logs.Error(err)
  6701. tx.Rollback()
  6702. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6703. return
  6704. }
  6705. }
  6706. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6707. if err != nil {
  6708. logs.Error(err)
  6709. tx.Rollback()
  6710. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6711. return
  6712. }
  6713. }
  6714. }
  6715. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6716. if err != nil {
  6717. logs.Error(err)
  6718. tx.Rollback()
  6719. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6720. return
  6721. }
  6722. } else {
  6723. if status == 2 {
  6724. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6725. if err != nil {
  6726. logs.Error(err)
  6727. tx.Rollback()
  6728. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6729. return
  6730. }
  6731. for _, item := range lpplandtl1List {
  6732. if item["fttype"].(int64) == 0 {
  6733. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6734. if err != nil {
  6735. logs.Error(err)
  6736. tx.Rollback()
  6737. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6738. return
  6739. }
  6740. } else {
  6741. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6742. if err != nil {
  6743. logs.Error(err)
  6744. tx.Rollback()
  6745. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6746. return
  6747. }
  6748. }
  6749. }
  6750. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6751. if err != nil {
  6752. logs.Error(err)
  6753. tx.Rollback()
  6754. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6755. return
  6756. }
  6757. } else {
  6758. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6759. if err != nil {
  6760. logs.Error(err)
  6761. tx.Rollback()
  6762. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6763. return
  6764. }
  6765. }
  6766. }
  6767. err := tx.Commit()
  6768. if err != nil {
  6769. logs.Error(err)
  6770. tx.Rollback()
  6771. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6772. return
  6773. }
  6774. appG.Response(http.StatusOK, e.SUCCESS, true)
  6775. }
  6776. func UpdateMaterialTMRDate(c *gin.Context) {
  6777. appG := app.Gin{C: c}
  6778. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6779. parammaps := gofasion.NewFasion(string(dataByte))
  6780. tmrid := parammaps.Get("tmrid").ValueStr()
  6781. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6782. lppid := parammaps.Get("lppid").ValueStr()
  6783. times := parammaps.Get("times").ValueStr()
  6784. pastureid := parammaps.Get("pastureid").ValueStr()
  6785. date := parammaps.Get("date").ValueStr()
  6786. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6787. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6788. tx := restful.Engine.NewSession()
  6789. defer tx.Close()
  6790. tx.Begin()
  6791. if tmrid != "1000" {
  6792. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6793. if err != nil {
  6794. logs.Error(err)
  6795. tx.Rollback()
  6796. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6797. return
  6798. }
  6799. var maxstirfeed float64
  6800. for _, tmr := range tmrList {
  6801. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6802. }
  6803. if status == 0 {
  6804. 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()
  6805. if err != nil {
  6806. logs.Error(err)
  6807. tx.Rollback()
  6808. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6809. return
  6810. }
  6811. var lweight float64
  6812. for _, item := range lpplandtl1List {
  6813. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6814. lweight += fl
  6815. }
  6816. if lweight > maxstirfeed {
  6817. lweight = lweight - maxstirfeed
  6818. } else {
  6819. lweight = 0
  6820. }
  6821. if lweight > 0 {
  6822. lweight1 := lweight / float64(len(lpplandtl1List))
  6823. number := 0
  6824. for _, item := range lpplandtl1List {
  6825. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6826. if lweight1 >= fl {
  6827. number++
  6828. }
  6829. }
  6830. lweight := lweight / float64((len(lpplandtl1List) - number))
  6831. for _, item := range lpplandtl1List {
  6832. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6833. if lweight1 >= fl {
  6834. continue
  6835. }
  6836. if tmrtype == "1" {
  6837. _, 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()
  6838. if err != nil {
  6839. logs.Error(err)
  6840. tx.Rollback()
  6841. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6842. return
  6843. }
  6844. } else if tmrtype == "2" {
  6845. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6846. if err != nil {
  6847. logs.Error(err)
  6848. tx.Rollback()
  6849. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6850. return
  6851. }
  6852. }
  6853. if item["fttype"].(int64) == 0 {
  6854. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6855. if err != nil {
  6856. logs.Error(err)
  6857. tx.Rollback()
  6858. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6859. return
  6860. }
  6861. } else {
  6862. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6863. if err != nil {
  6864. logs.Error(err)
  6865. tx.Rollback()
  6866. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6867. return
  6868. }
  6869. }
  6870. }
  6871. } else {
  6872. for _, item := range lpplandtl1List {
  6873. // 自走式
  6874. if tmrtype == "1" {
  6875. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6876. if err != nil {
  6877. logs.Error(err)
  6878. tx.Rollback()
  6879. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6880. return
  6881. }
  6882. } else if tmrtype == "2" {
  6883. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6884. if err != nil {
  6885. logs.Error(err)
  6886. tx.Rollback()
  6887. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6888. return
  6889. }
  6890. }
  6891. }
  6892. }
  6893. } else if status == 1 {
  6894. 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()
  6895. if err != nil {
  6896. logs.Error(err)
  6897. tx.Rollback()
  6898. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6899. return
  6900. }
  6901. var lweight float64
  6902. for _, item := range lpplandtl1List {
  6903. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6904. lweight += fl
  6905. }
  6906. if lweight > maxstirfeed {
  6907. lweight = lweight - maxstirfeed
  6908. } else {
  6909. lweight = 0
  6910. }
  6911. for _, item := range lpplandtl1List {
  6912. if lweight > 0 {
  6913. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6914. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6915. if fl >= lweight {
  6916. item["lweight"] = fl - lweight
  6917. lweight = 0
  6918. if tmrtype == "1" {
  6919. _, 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()
  6920. if err != nil {
  6921. logs.Error(err)
  6922. tx.Rollback()
  6923. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6924. return
  6925. }
  6926. } else if tmrtype == "2" {
  6927. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6928. if err != nil {
  6929. logs.Error(err)
  6930. tx.Rollback()
  6931. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6932. return
  6933. }
  6934. }
  6935. if item["fttype"].(int64) == 0 {
  6936. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6937. if err != nil {
  6938. logs.Error(err)
  6939. tx.Rollback()
  6940. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6941. return
  6942. }
  6943. } else {
  6944. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6945. if err != nil {
  6946. logs.Error(err)
  6947. tx.Rollback()
  6948. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6949. return
  6950. }
  6951. }
  6952. } else {
  6953. lweight = lweight - fl
  6954. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6955. if err != nil {
  6956. logs.Error(err)
  6957. tx.Rollback()
  6958. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6959. return
  6960. }
  6961. if item["fttype"].(int64) == 0 {
  6962. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6963. if err != nil {
  6964. logs.Error(err)
  6965. tx.Rollback()
  6966. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6967. return
  6968. }
  6969. } else {
  6970. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6971. if err != nil {
  6972. logs.Error(err)
  6973. tx.Rollback()
  6974. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6975. return
  6976. }
  6977. }
  6978. }
  6979. } else {
  6980. // 自走式
  6981. if tmrtype == "1" {
  6982. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6983. if err != nil {
  6984. logs.Error(err)
  6985. tx.Rollback()
  6986. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6987. return
  6988. }
  6989. } else if tmrtype == "2" {
  6990. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6991. if err != nil {
  6992. logs.Error(err)
  6993. tx.Rollback()
  6994. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6995. return
  6996. }
  6997. }
  6998. }
  6999. }
  7000. } else {
  7001. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  7002. if err != nil {
  7003. logs.Error(err)
  7004. tx.Rollback()
  7005. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7006. return
  7007. }
  7008. for _, item := range lpplandtl1List {
  7009. if item["fttype"].(int64) == 0 {
  7010. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7011. if err != nil {
  7012. logs.Error(err)
  7013. tx.Rollback()
  7014. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7015. return
  7016. }
  7017. } else {
  7018. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7019. if err != nil {
  7020. logs.Error(err)
  7021. tx.Rollback()
  7022. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7023. return
  7024. }
  7025. }
  7026. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  7027. if err != nil {
  7028. logs.Error(err)
  7029. tx.Rollback()
  7030. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7031. return
  7032. }
  7033. }
  7034. }
  7035. _, 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()
  7036. if err != nil {
  7037. logs.Error(err)
  7038. tx.Rollback()
  7039. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7040. return
  7041. }
  7042. } else {
  7043. if status == 2 {
  7044. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  7045. if err != nil {
  7046. logs.Error(err)
  7047. tx.Rollback()
  7048. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7049. return
  7050. }
  7051. for _, item := range lpplandtl1List {
  7052. if item["fttype"].(int64) == 0 {
  7053. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7054. if err != nil {
  7055. logs.Error(err)
  7056. tx.Rollback()
  7057. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7058. return
  7059. }
  7060. } else {
  7061. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7062. if err != nil {
  7063. logs.Error(err)
  7064. tx.Rollback()
  7065. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7066. return
  7067. }
  7068. }
  7069. }
  7070. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  7071. if err != nil {
  7072. logs.Error(err)
  7073. tx.Rollback()
  7074. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7075. return
  7076. }
  7077. } else {
  7078. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  7079. if err != nil {
  7080. logs.Error(err)
  7081. tx.Rollback()
  7082. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7083. return
  7084. }
  7085. }
  7086. }
  7087. err := tx.Commit()
  7088. if err != nil {
  7089. logs.Error(err)
  7090. tx.Rollback()
  7091. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7092. return
  7093. }
  7094. appG.Response(http.StatusOK, e.SUCCESS, true)
  7095. }
  7096. func Decimal(value float64) float64 {
  7097. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  7098. return value
  7099. }
  7100. func UpdateDailyData(c *gin.Context) {
  7101. appG := app.Gin{C: c}
  7102. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7103. parammaps := gofasion.NewFasion(string(dataByte))
  7104. pid := parammaps.Get("pid").ValueDefaultStr("0")
  7105. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  7106. sort := parammaps.Get("sort").ValueDefaultStr("0")
  7107. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  7108. date := parammaps.Get("date").ValueStr()
  7109. tx := restful.Engine.NewSession()
  7110. defer tx.Close()
  7111. 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()
  7112. if err != nil {
  7113. logs.Error("UpdateDailyData-error-0:", err)
  7114. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7115. return
  7116. }
  7117. if count > 0 {
  7118. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7119. return
  7120. }
  7121. tx.Begin()
  7122. if location == 0 {
  7123. fid := parammaps.Get("fid").ValueStr()
  7124. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).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. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7132. if err != nil {
  7133. logs.Error("UpdateDailyData-error-1:", err)
  7134. tx.Rollback()
  7135. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7136. return
  7137. }
  7138. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7139. if err != nil {
  7140. fmt.Println("Error:", err)
  7141. return
  7142. }
  7143. actualWeight := weight - num
  7144. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7145. if err != nil {
  7146. logs.Error("UpdateDailyData-error-2:", err)
  7147. tx.Rollback()
  7148. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7149. return
  7150. }
  7151. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7152. if err != nil {
  7153. logs.Error("UpdateDailyData-error-3:", err)
  7154. tx.Rollback()
  7155. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7156. return
  7157. }
  7158. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7159. if err != nil {
  7160. logs.Error("UpdateDailyData-error-4:", err)
  7161. tx.Rollback()
  7162. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7163. return
  7164. }
  7165. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7166. if err != nil {
  7167. logs.Error("UpdateDailyData-error-5:", err)
  7168. tx.Rollback()
  7169. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7170. return
  7171. }
  7172. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7173. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7174. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7175. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7176. if err != nil {
  7177. fmt.Println("Error:", err)
  7178. return
  7179. }
  7180. // actual := actualWeight / float64(len(downloadedplanList))
  7181. for _, item := range downloadedplanList {
  7182. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7183. if err != nil {
  7184. fmt.Println("Error:", err)
  7185. return
  7186. }
  7187. actual := itemLweight / lweight * actualWeight
  7188. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7189. if err != nil {
  7190. logs.Error("UpdateDailyData-error-6:", 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 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7196. if err != nil {
  7197. logs.Error("UpdateDailyData-error-7:", err)
  7198. tx.Rollback()
  7199. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7200. return
  7201. }
  7202. _, 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()
  7203. if err != nil {
  7204. logs.Error("UpdateDailyData-error-8:", err)
  7205. tx.Rollback()
  7206. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7207. return
  7208. }
  7209. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7210. if err != nil {
  7211. logs.Error("UpdateDailyData-error-9:", err)
  7212. tx.Rollback()
  7213. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7214. return
  7215. }
  7216. }
  7217. } else {
  7218. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7219. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7220. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7221. // if err != nil {
  7222. // fmt.Println("Error:", err)
  7223. // return
  7224. // }
  7225. for _, item := range downloadedplanList {
  7226. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7227. if err != nil {
  7228. logs.Error("UpdateDailyData-error-6:", err)
  7229. tx.Rollback()
  7230. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7231. return
  7232. }
  7233. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7234. item["lweight"], actualWeight, item["id"]).Execute()
  7235. if err != nil {
  7236. logs.Error("UpdateDailyData-error-7:", err)
  7237. tx.Rollback()
  7238. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7239. return
  7240. }
  7241. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7242. where pid = ?`, item["id"]).Execute()
  7243. if err != nil {
  7244. logs.Error("UpdateDailyData-error-8:", err)
  7245. tx.Rollback()
  7246. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7247. return
  7248. }
  7249. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7250. if err != nil {
  7251. logs.Error("UpdateDailyData-error-9:", err)
  7252. tx.Rollback()
  7253. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7254. return
  7255. }
  7256. }
  7257. }
  7258. } else {
  7259. fbarid := parammaps.Get("fbarid").ValueStr()
  7260. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7261. if err != nil {
  7262. logs.Error("UpdateDailyData-error-10:", err)
  7263. tx.Rollback()
  7264. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7265. return
  7266. }
  7267. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7268. if err != nil {
  7269. logs.Error("UpdateDailyData-error-1:", err)
  7270. tx.Rollback()
  7271. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7272. return
  7273. }
  7274. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7275. if err != nil {
  7276. fmt.Println("Error:", err)
  7277. return
  7278. }
  7279. actualWeight := weight - num
  7280. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7281. if err != nil {
  7282. logs.Error("UpdateDailyData-error-11:", err)
  7283. tx.Rollback()
  7284. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7285. return
  7286. }
  7287. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  7288. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7289. if err != nil {
  7290. logs.Error("UpdateDailyData-error-12:", err)
  7291. tx.Rollback()
  7292. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7293. return
  7294. }
  7295. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7296. where pid = ? `, pid).Execute()
  7297. if err != nil {
  7298. logs.Error("UpdateDailyData-error-13:", err)
  7299. tx.Rollback()
  7300. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7301. return
  7302. }
  7303. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7304. if err != nil {
  7305. logs.Error("UpdateDailyData-error-14:", err)
  7306. tx.Rollback()
  7307. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7308. return
  7309. }
  7310. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7311. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7312. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7313. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7314. if err != nil {
  7315. fmt.Println("Error:", err)
  7316. return
  7317. }
  7318. for _, item := range downloadedplanList {
  7319. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7320. if err != nil {
  7321. fmt.Println("Error:", err)
  7322. return
  7323. }
  7324. actual := itemLweight / lweight * actualWeight
  7325. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7326. if err != nil {
  7327. logs.Error("UpdateDailyData-error-6:", 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 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7333. if err != nil {
  7334. logs.Error("UpdateDailyData-error-7:", err)
  7335. tx.Rollback()
  7336. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7337. return
  7338. }
  7339. _, 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()
  7340. if err != nil {
  7341. logs.Error("UpdateDailyData-error-8:", err)
  7342. tx.Rollback()
  7343. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7344. return
  7345. }
  7346. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7347. if err != nil {
  7348. logs.Error("UpdateDailyData-error-9:", err)
  7349. tx.Rollback()
  7350. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7351. return
  7352. }
  7353. }
  7354. } else {
  7355. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7356. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7357. for _, item := range downloadedplanList {
  7358. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7359. // if err != nil {
  7360. // fmt.Println("Error:", err)
  7361. // return
  7362. // }
  7363. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7364. if err != nil {
  7365. logs.Error("UpdateDailyData-error-6:", err)
  7366. tx.Rollback()
  7367. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7368. return
  7369. }
  7370. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7371. item["lweight"], actualWeight, item["id"]).Execute()
  7372. if err != nil {
  7373. logs.Error("UpdateDailyData-error-7:", err)
  7374. tx.Rollback()
  7375. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7376. return
  7377. }
  7378. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7379. where pid = ?`, item["id"]).Execute()
  7380. if err != nil {
  7381. logs.Error("UpdateDailyData-error-8:", err)
  7382. tx.Rollback()
  7383. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7384. return
  7385. }
  7386. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7387. if err != nil {
  7388. logs.Error("UpdateDailyData-error-9:", err)
  7389. tx.Rollback()
  7390. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7391. return
  7392. }
  7393. }
  7394. }
  7395. }
  7396. err = tx.Commit()
  7397. if err != nil {
  7398. logs.Error("UpdateDailyData-error-20:", err)
  7399. tx.Rollback()
  7400. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7401. return
  7402. }
  7403. appG.Response(http.StatusOK, e.SUCCESS, true)
  7404. }
  7405. func GetFormulaStatistics(c *gin.Context) {
  7406. appG := app.Gin{C: c}
  7407. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7408. parammaps := gofasion.NewFasion(string(dataByte))
  7409. startTime := parammaps.Get("startTime").ValueStr()
  7410. endTime := parammaps.Get("endTime").ValueStr()
  7411. pastureId := parammaps.Get("pastureId").ValueStr()
  7412. tx := restful.Engine.NewSession()
  7413. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7414. if err != nil {
  7415. logs.Error("GetFormulaStatistics-error-1:", err)
  7416. tx.Rollback()
  7417. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7418. return
  7419. }
  7420. var feedtemplet, dateList []string
  7421. for _, f := range feedtempletList {
  7422. feedtemplet = append(feedtemplet, f["tname"].(string))
  7423. }
  7424. layout := "2006-01-02"
  7425. // s := "2023-05-01"
  7426. // e := "2023-05-23"
  7427. start, err := time.Parse(layout, startTime)
  7428. if err != nil {
  7429. fmt.Println(err)
  7430. return
  7431. }
  7432. end, err := time.Parse(layout, endTime)
  7433. if err != nil {
  7434. fmt.Println(err)
  7435. return
  7436. }
  7437. end = end.AddDate(0, 0, 1)
  7438. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7439. dateList = append(dateList, d.Format("2006-01-02"))
  7440. }
  7441. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7442. 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= ?
  7443. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7444. if err != nil {
  7445. logs.Error("GetFormulaStatistics-error-2:", err)
  7446. tx.Rollback()
  7447. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7448. return
  7449. }
  7450. var data2 [][]interface{}
  7451. for _, f := range feedtemplet {
  7452. var data1 []interface{}
  7453. for _, date := range dateList {
  7454. exist := false
  7455. for _, item := range downloadedplanList {
  7456. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7457. data1 = append(data1, item["total"])
  7458. exist = true
  7459. break
  7460. }
  7461. }
  7462. if !exist {
  7463. data1 = append(data1, 0)
  7464. }
  7465. }
  7466. data2 = append(data2, data1)
  7467. }
  7468. //前端让加的
  7469. feedtemplet = append(feedtemplet, "")
  7470. {
  7471. var data1 []interface{}
  7472. for _, f := range dateList {
  7473. // f = f + "\n"
  7474. fmt.Println(f)
  7475. data1 = append(data1, 0)
  7476. }
  7477. data2 = append(data2, data1)
  7478. }
  7479. resp := make(map[string]interface{}, 0)
  7480. resp["xdata"] = dateList
  7481. resp["data1"] = feedtemplet
  7482. resp["data2"] = data2
  7483. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7484. }
  7485. func GetPlanData(c *gin.Context) {
  7486. appG := app.Gin{C: c}
  7487. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7488. fsion := gofasion.NewFasion(string(dataByte))
  7489. sqlnamestr := fsion.Get("name").ValueStr()
  7490. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7491. offset := fsion.Get("offset").ValueDefaultInt(0)
  7492. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7493. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7494. month := fsion.Get("month").ValueDefaultStr("map")
  7495. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7496. tx := restful.Engine.NewSession()
  7497. err := tx.Begin()
  7498. defer func() {
  7499. switch {
  7500. case err != nil:
  7501. if tx != nil {
  7502. tx.Rollback()
  7503. }
  7504. default:
  7505. if tx != nil {
  7506. err = tx.Commit()
  7507. }
  7508. }
  7509. if tx != nil {
  7510. tx.Close()
  7511. }
  7512. }()
  7513. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7514. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7515. if sql != "" {
  7516. s_params := make([]interface{}, 0)
  7517. if fsion.HasKey("parammaps") {
  7518. parammaps := fsion.Get("parammaps")
  7519. paramslist := strings.Split(p, ",")
  7520. if len(paramslist) > 0 && p != "" {
  7521. for _, value := range paramslist {
  7522. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7523. if tempv, exists := c.Get("jwt_username"); exists {
  7524. s_params = append(s_params, tempv.(string))
  7525. } else {
  7526. s_params = append(s_params, "")
  7527. }
  7528. } else {
  7529. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7530. }
  7531. }
  7532. }
  7533. }
  7534. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7535. if err != nil {
  7536. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7537. } else {
  7538. paramslist1 := strings.Split(p1, ",")
  7539. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7540. s_params1 := make([]interface{}, 0)
  7541. if len(paramslist1) > 0 && p1 != "" {
  7542. for _, v := range paramslist1 {
  7543. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7544. }
  7545. }
  7546. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7547. for _, item := range arr {
  7548. trgaddressList := []string{}
  7549. if _, ok := item["trgaddress"]; ok {
  7550. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7551. for _, str := range trgaddressList1 {
  7552. if str != "" {
  7553. trgaddressList = append(trgaddressList, str)
  7554. }
  7555. }
  7556. }
  7557. item["trgaddressList"] = trgaddressList
  7558. }
  7559. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7560. }
  7561. // var wg sync.WaitGroup
  7562. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7563. // wg.Add(1)
  7564. // go func(value map[string]interface{}) {
  7565. // defer wg.Done()
  7566. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7567. // }(value)
  7568. // }
  7569. // wg.Wait()
  7570. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7571. }
  7572. } else {
  7573. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7574. }
  7575. }
  7576. func PostPlanData(c *gin.Context) {
  7577. appG := app.Gin{C: c}
  7578. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7579. fsion := gofasion.NewFasion(string(dataByte))
  7580. logging.Info("PostRJSBData err: ", string(dataByte))
  7581. s_params := make([]interface{}, 0)
  7582. tx := restful.Engine.NewSession()
  7583. err := tx.Begin()
  7584. defer func() {
  7585. switch {
  7586. case err != nil:
  7587. if tx != nil {
  7588. tx.Rollback()
  7589. }
  7590. default:
  7591. if tx != nil {
  7592. err = tx.Commit()
  7593. }
  7594. }
  7595. if tx != nil {
  7596. tx.Close()
  7597. }
  7598. }()
  7599. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7600. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7601. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7602. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7603. if !fsion.HasKey("parammaps") {
  7604. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7605. return
  7606. }
  7607. parammaps := fsion.Get("parammaps")
  7608. // paramslist := strings.Split(p, ",")
  7609. // if len(paramslist) > 0 && p != "" {
  7610. // for _, value := range paramslist {
  7611. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7612. // }
  7613. // }
  7614. // _, err = tx.SQL(sql, s_params...).Execute()
  7615. // if err != nil {
  7616. // logging.Error("PostRJSBData err: ", err)
  7617. // msg := geterrmsg(err.Error())
  7618. // appG.Response(http.StatusOK, e.ERROR, msg)
  7619. // return
  7620. // }
  7621. s_params = make([]interface{}, 0)
  7622. paramslist := strings.Split(p1, ",")
  7623. if len(paramslist) > 0 && p1 != "" {
  7624. for _, value := range paramslist {
  7625. // if value == "ID" {
  7626. // id := parammaps.Get("ID").ValueStr()
  7627. // pastureid := parammaps.Get("pastureid").ValueStr()
  7628. // 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
  7629. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7630. // if err != nil {
  7631. // logging.Error("PostRJSBData err: ", err)
  7632. // msg := geterrmsg(err.Error())
  7633. // appG.Response(http.StatusOK, e.ERROR, msg)
  7634. // return
  7635. // }
  7636. // for _, item := range datalist {
  7637. // id = item["id"]
  7638. // }
  7639. // s_params = append(s_params, id)
  7640. // } else {
  7641. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7642. // }
  7643. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7644. }
  7645. }
  7646. _, err = tx.SQL(sql1, s_params...).Execute()
  7647. if err != nil {
  7648. logging.Error("PostRJSBData1 err: ", err)
  7649. msg := geterrmsg(err.Error())
  7650. appG.Response(http.StatusOK, e.ERROR, msg)
  7651. return
  7652. }
  7653. s_params = make([]interface{}, 0)
  7654. paramslist = strings.Split(p2, ",")
  7655. if len(paramslist) > 0 && p2 != "" {
  7656. for _, value := range paramslist {
  7657. if value == "ID" {
  7658. id := parammaps.Get("ID").ValueStr()
  7659. pastureid := parammaps.Get("pastureid").ValueStr()
  7660. 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
  7661. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7662. if err != nil {
  7663. logging.Error("PostRJSBData err: ", err)
  7664. msg := geterrmsg(err.Error())
  7665. appG.Response(http.StatusOK, e.ERROR, msg)
  7666. return
  7667. }
  7668. for _, item := range datalist {
  7669. id = item["id"]
  7670. }
  7671. s_params = append(s_params, id)
  7672. } else {
  7673. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7674. }
  7675. }
  7676. }
  7677. _, err = tx.SQL(sql2, s_params...).Execute()
  7678. if err != nil {
  7679. logging.Error("PostRJSBData2 err: ", err)
  7680. msg := geterrmsg(err.Error())
  7681. appG.Response(http.StatusOK, e.ERROR, msg)
  7682. return
  7683. }
  7684. s_params = make([]interface{}, 0)
  7685. paramslist = strings.Split(p3, ",")
  7686. if len(paramslist) > 0 && p3 != "" {
  7687. for _, value := range paramslist {
  7688. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7689. }
  7690. }
  7691. _, err = tx.SQL(sql3, s_params...).Execute()
  7692. if err != nil {
  7693. logging.Error("PostRJSBData3 err: ", err)
  7694. msg := geterrmsg(err.Error())
  7695. appG.Response(http.StatusOK, e.ERROR, msg)
  7696. return
  7697. }
  7698. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7699. }
  7700. func CheckFeedTrgaddress(c *gin.Context) {
  7701. appG := app.Gin{C: c}
  7702. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7703. fsion := gofasion.NewFasion(string(dataByte))
  7704. fclassid := fsion.Get("fclassid").ValueStr()
  7705. feedId := fsion.Get("feedId").ValueStr()
  7706. backup1 := fsion.Get("backup1").ValueStr()
  7707. backup1List := strings.Split(backup1, ",")
  7708. tx := restful.Engine.NewSession()
  7709. defer tx.Close()
  7710. // if backup1 != "" {
  7711. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7712. for _, feed := range feedList {
  7713. if feed["backup1"] == "" {
  7714. continue
  7715. }
  7716. feedbackupList := strings.Split(feed["backup1"], ",")
  7717. for _, feedbackup := range feedbackupList {
  7718. for _, backup := range backup1List {
  7719. if feedbackup == backup {
  7720. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7721. return
  7722. }
  7723. }
  7724. }
  7725. }
  7726. // }
  7727. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7728. }
  7729. func ThiGetDataByName(c *gin.Context) {
  7730. appG := app.Gin{C: c}
  7731. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7732. fsion := gofasion.NewFasion(string(dataByte))
  7733. sqlnamestr := fsion.Get("name").ValueStr()
  7734. offset := fsion.Get("offset").ValueDefaultInt(0)
  7735. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7736. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7737. tx := restful.Engine.NewSession()
  7738. err := tx.Begin()
  7739. defer func() {
  7740. switch {
  7741. case err != nil:
  7742. logging.Error("tx.Begin 事务启动失败__error:", err)
  7743. if tx != nil {
  7744. tx.Rollback()
  7745. }
  7746. default:
  7747. if tx != nil {
  7748. err = tx.Commit()
  7749. }
  7750. }
  7751. if tx != nil {
  7752. tx.Close()
  7753. }
  7754. }()
  7755. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7756. if sql != "" {
  7757. s_params := make([]interface{}, 0)
  7758. if fsion.HasKey("parammaps") {
  7759. parammaps := fsion.Get("parammaps")
  7760. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7761. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7762. }
  7763. paramslist := strings.Split(p, ",")
  7764. if len(paramslist) > 0 && p != "" {
  7765. for _, value := range paramslist {
  7766. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7767. if tempv, exists := c.Get("jwt_username"); exists {
  7768. s_params = append(s_params, tempv.(string))
  7769. } else {
  7770. s_params = append(s_params, "")
  7771. }
  7772. } else {
  7773. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7774. }
  7775. }
  7776. }
  7777. } else if fsion.HasKey("params") {
  7778. params := fsion.Get("params").Array()
  7779. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7780. for _, v_params := range params {
  7781. s_params = append(s_params, v_params.ValueStr())
  7782. }
  7783. }
  7784. if returntype == "xlsx" {
  7785. var xlsxfile *xlsx.File
  7786. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7787. //c.File("c:/dd.xlsx")
  7788. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7789. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7790. c.Header("Content-Transfer-Encoding", "binary")
  7791. _ = xlsxfile.Write(c.Writer)
  7792. } else {
  7793. if sqlnamestr == "getHomepageStr" {
  7794. parammaps := fsion.Get("parammaps")
  7795. pastureid := parammaps.Get("pastureid").ValueStr()
  7796. var montimeList []float64
  7797. var montime float64
  7798. var wg sync.WaitGroup
  7799. now := time.Now()
  7800. for i := 0; i < 30; i++ {
  7801. wg.Add(1)
  7802. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7803. go func(nowstr string) {
  7804. defer wg.Done()
  7805. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7806. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7807. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7808. montimeList = append(montimeList, m)
  7809. }(nowstr)
  7810. }
  7811. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7812. if err != nil {
  7813. logging.Error("GetDataByName err: ", err)
  7814. msg := geterrmsg(err.Error())
  7815. appG.Response(http.StatusOK, e.ERROR, msg)
  7816. }
  7817. wg.Wait()
  7818. for _, m := range montimeList {
  7819. montime += m
  7820. }
  7821. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7822. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7823. return
  7824. }
  7825. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7826. if err != nil {
  7827. logging.Error("GetDataByName err: ", err)
  7828. msg := geterrmsg(err.Error())
  7829. appG.Response(http.StatusOK, e.ERROR, msg)
  7830. } else {
  7831. if sqlnamestr == "getFeedTrgaddressList" {
  7832. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7833. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7834. trgaddressList := []string{}
  7835. for _, str := range trgaddressList1 {
  7836. if str != "" {
  7837. trgaddressList = append(trgaddressList, str)
  7838. }
  7839. }
  7840. item["trgaddressList"] = trgaddressList
  7841. }
  7842. }
  7843. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7844. }
  7845. }
  7846. } else {
  7847. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7848. }
  7849. }
  7850. // func ToggleCcount(c *gin.Context) {
  7851. // appG := app.Gin{C: c}
  7852. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7853. // fsion := gofasion.NewFasion(string(dataByte))
  7854. // // 0 实际 1 软件
  7855. // status := fsion.Get("status").ValueDefaultInt64(0)
  7856. // pastureId := fsion.Get("pastureId").ValueStr()
  7857. // tx := restful.Engine.NewSession()
  7858. // err := tx.Begin()
  7859. // defer func() {
  7860. // switch {
  7861. // case err != nil:
  7862. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7863. // if tx != nil {
  7864. // tx.Rollback()
  7865. // }
  7866. // default:
  7867. // if tx != nil {
  7868. // err = tx.Commit()
  7869. // }
  7870. // }
  7871. // if tx != nil {
  7872. // tx.Close()
  7873. // }
  7874. // }()
  7875. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7876. // if err != nil {
  7877. // logs.Error(err)
  7878. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7879. // return
  7880. // }
  7881. // for _, bar := range barList {
  7882. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7883. // if err != nil {
  7884. // logs.Error(err)
  7885. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7886. // return
  7887. // }
  7888. // if !exist {
  7889. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7890. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7891. // if err != nil {
  7892. // logs.Error(err)
  7893. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7894. // return
  7895. // }
  7896. // }
  7897. // }
  7898. // if status == 0 {
  7899. // tx.Exec(`update feedp set ccount = actualcount `)
  7900. // }else{
  7901. // tx.Exec(`update feedp set ccount = softccount `)
  7902. // }
  7903. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7904. // if err != nil {
  7905. // logs.Error(err)
  7906. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7907. // return
  7908. // }
  7909. // for _, feedpData :=range feedpList{
  7910. // var feedpargs []interface{}
  7911. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7912. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7913. // if _, ok := feedpData["ftname"]; ok {
  7914. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7915. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7916. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7917. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7918. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7919. // } else {
  7920. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7921. // }
  7922. // if _, ok := feedpData["ptsfname"]; ok {
  7923. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7924. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7925. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7926. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7927. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7928. // } else {
  7929. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7930. // }
  7931. // upFeedpSql += " where barname = ? and pastureid = ? "
  7932. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7933. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7934. // if err != nil {
  7935. // logs.Error(err)
  7936. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7937. // return
  7938. // }
  7939. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7940. // if err != nil {
  7941. // logs.Error(err)
  7942. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7943. // return
  7944. // }
  7945. // if !exist1 {
  7946. // _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  7947. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7948. // if err != nil {
  7949. // logs.Error(err)
  7950. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7951. // return
  7952. // }
  7953. // }
  7954. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7955. // if err != nil {
  7956. // logs.Error(err)
  7957. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7958. // return
  7959. // }
  7960. // if !exist2 {
  7961. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,2,0,0,0,-1,-1) `,
  7962. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7963. // if err != nil {
  7964. // logs.Error(err)
  7965. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7966. // return
  7967. // }
  7968. // }
  7969. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7970. // if err != nil {
  7971. // logs.Error(err)
  7972. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7973. // return
  7974. // }
  7975. // if !exist3 {
  7976. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,3,0,0,0,-1,-1) `,
  7977. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7978. // if err != nil {
  7979. // logs.Error(err)
  7980. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7981. // return
  7982. // }
  7983. // }
  7984. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7985. // if err != nil {
  7986. // logs.Error(err)
  7987. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7988. // return
  7989. // }
  7990. // if !exist4 {
  7991. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,4,0,0,0,-1,-1) `,
  7992. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7993. // if err != nil {
  7994. // logs.Error(err)
  7995. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7996. // return
  7997. // }
  7998. // }
  7999. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  8000. // if err != nil {
  8001. // logs.Error(err)
  8002. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8003. // return
  8004. // }
  8005. // if !exist5 {
  8006. // _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
  8007. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  8008. // if err != nil {
  8009. // logs.Error(err)
  8010. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8011. // return
  8012. // }
  8013. // }
  8014. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  8015. // if err != nil {
  8016. // logs.Error(err)
  8017. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8018. // return
  8019. // }
  8020. // if !exist6 {
  8021. // _, 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) `,
  8022. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  8023. // if err != nil {
  8024. // logs.Error(err)
  8025. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8026. // return
  8027. // }
  8028. // }
  8029. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8030. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8031. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8032. // and pastureid = ? and times = ?`
  8033. // var fpdargs1 []interface{}
  8034. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8035. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8036. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8037. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8038. // if err != nil {
  8039. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8040. // return
  8041. // }
  8042. // var fpdargs2 []interface{}
  8043. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8044. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8045. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8046. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8047. // if err != nil {
  8048. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8049. // return
  8050. // }
  8051. // var fpdargs3 []interface{}
  8052. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8053. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8054. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8055. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8056. // if err != nil {
  8057. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8058. // return
  8059. // }
  8060. // var fpdargs4 []interface{}
  8061. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8062. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8063. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8064. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8065. // if err != nil {
  8066. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8067. // return
  8068. // }
  8069. // var fpdargs5 []interface{}
  8070. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8071. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8072. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8073. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8074. // if err != nil {
  8075. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8076. // return
  8077. // }
  8078. // var fpdargs6 []interface{}
  8079. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8080. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8081. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8082. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8083. // if err != nil {
  8084. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8085. // return
  8086. // }
  8087. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8088. // 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()
  8089. // if err != nil {
  8090. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8091. // return
  8092. // }
  8093. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8094. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8095. // upFpdetailList := make([]*upFpdetail, 0)
  8096. // for _, newfpd := range newList {
  8097. // for _, oldfpd := range oldFpdList {
  8098. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8099. // var oldweight, newweight float64
  8100. // if oldfpd["weight"] != nil {
  8101. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8102. // }
  8103. // if newfpd["weight"] != nil {
  8104. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8105. // }
  8106. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8107. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  8108. // Old: oldweight,
  8109. // New: newweight,
  8110. // Times: newfpd["times"].(int64),
  8111. // Ptid: newfpd["ptid"].(int64),
  8112. // Fweight: fweight,
  8113. // Id: oldfpd["id"].(int64),
  8114. // })
  8115. // break
  8116. // }
  8117. // }
  8118. // }
  8119. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8120. // }
  8121. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8122. // }
  8123. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8124. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8125. if err != nil {
  8126. return err
  8127. }
  8128. for _, item := range feedpList {
  8129. // if item["ftid"].(string) != data["ftid"].(string) {
  8130. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8131. if err != nil {
  8132. return err
  8133. }
  8134. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8135. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8136. if err != nil {
  8137. return err
  8138. }
  8139. // }
  8140. }
  8141. return nil
  8142. }
  8143. func PostPlanDatas(c *gin.Context) {
  8144. appG := app.Gin{C: c}
  8145. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8146. fsions := gofasion.NewFasion(string(dataByte))
  8147. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8148. tx := restful.Engine.NewSession()
  8149. err := tx.Begin()
  8150. defer func() {
  8151. switch {
  8152. case err != nil:
  8153. if tx != nil {
  8154. tx.Rollback()
  8155. }
  8156. default:
  8157. if tx != nil {
  8158. err = tx.Commit()
  8159. }
  8160. }
  8161. if tx != nil {
  8162. tx.Close()
  8163. }
  8164. }()
  8165. pastureId := fsions.Get("pastureid").ValueStr()
  8166. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8167. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8168. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8169. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8170. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8171. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8172. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8173. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8174. for _, parammaps := range fsions.Get("arrList").Array() {
  8175. fmt.Println(parammaps.Json())
  8176. if parammaps.Json() == "null" {
  8177. continue
  8178. }
  8179. // if !fsion.HasKey("arrList") {
  8180. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8181. // return
  8182. // continue
  8183. // }
  8184. // parammaps := fsion.Get("arrList")
  8185. s_params := make([]interface{}, 0)
  8186. // paramslist := strings.Split(p, ",")
  8187. // if len(paramslist) > 0 && p != "" {
  8188. // for _, value := range paramslist {
  8189. // if value == "pastureid" {
  8190. // s_params = append(s_params, pastureId)
  8191. // } else {
  8192. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8193. // }
  8194. // }
  8195. // }
  8196. // _, err = tx.SQL(sql, s_params...).Execute()
  8197. // if err != nil {
  8198. // logging.Error("PostRJSBData err: ", err)
  8199. // msg := geterrmsg(err.Error())
  8200. // appG.Response(http.StatusOK, e.ERROR, msg)
  8201. // return
  8202. // }
  8203. s_params = make([]interface{}, 0)
  8204. paramslist := strings.Split(p1, ",")
  8205. if len(paramslist) > 0 && p1 != "" {
  8206. for _, value := range paramslist {
  8207. // if value == "ID" {
  8208. // id := parammaps.Get("ID").ValueStr()
  8209. // pastureid := parammaps.Get("pastureid").ValueStr()
  8210. // 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
  8211. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8212. // if err != nil {
  8213. // logging.Error("PostRJSBData err: ", err)
  8214. // msg := geterrmsg(err.Error())
  8215. // appG.Response(http.StatusOK, e.ERROR, msg)
  8216. // return
  8217. // }
  8218. // for _, item := range datalist {
  8219. // id = item["id"]
  8220. // }
  8221. // s_params = append(s_params, id)
  8222. // } else {
  8223. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8224. // }
  8225. if value == "pastureid" {
  8226. s_params = append(s_params, pastureId)
  8227. } else {
  8228. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8229. }
  8230. }
  8231. }
  8232. _, err = tx.SQL(sql1, s_params...).Execute()
  8233. if err != nil {
  8234. logging.Error("PostRJSBData1 err: ", err)
  8235. msg := geterrmsg(err.Error())
  8236. appG.Response(http.StatusOK, e.ERROR, msg)
  8237. return
  8238. }
  8239. s_params = make([]interface{}, 0)
  8240. paramslist = strings.Split(p2, ",")
  8241. if len(paramslist) > 0 && p2 != "" {
  8242. for _, value := range paramslist {
  8243. if value == "ID" {
  8244. id := parammaps.Get("ID").ValueStr()
  8245. pastureid := parammaps.Get("pastureid").ValueStr()
  8246. 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
  8247. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8248. if err != nil {
  8249. logging.Error("PostRJSBData err: ", err)
  8250. msg := geterrmsg(err.Error())
  8251. appG.Response(http.StatusOK, e.ERROR, msg)
  8252. return
  8253. }
  8254. for _, item := range datalist {
  8255. id = item["id"]
  8256. }
  8257. s_params = append(s_params, id)
  8258. } else if value == "pastureid" {
  8259. s_params = append(s_params, pastureId)
  8260. } else {
  8261. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8262. }
  8263. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8264. }
  8265. }
  8266. _, err = tx.SQL(sql2, s_params...).Execute()
  8267. if err != nil {
  8268. logging.Error("PostRJSBData2 err: ", err)
  8269. msg := geterrmsg(err.Error())
  8270. appG.Response(http.StatusOK, e.ERROR, msg)
  8271. return
  8272. }
  8273. s_params = make([]interface{}, 0)
  8274. paramslist = strings.Split(p3, ",")
  8275. if len(paramslist) > 0 && p3 != "" {
  8276. for _, value := range paramslist {
  8277. if value == "pastureid" {
  8278. s_params = append(s_params, pastureId)
  8279. } else {
  8280. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8281. }
  8282. }
  8283. }
  8284. _, err = tx.SQL(sql3, s_params...).Execute()
  8285. if err != nil {
  8286. logging.Error("PostRJSBData3 err: ", err)
  8287. msg := geterrmsg(err.Error())
  8288. appG.Response(http.StatusOK, e.ERROR, msg)
  8289. return
  8290. }
  8291. }
  8292. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8293. }
  8294. func FpdBatchEdit(c *gin.Context) {
  8295. appG := app.Gin{C: c}
  8296. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8297. fsions := gofasion.NewFasion(string(dataByte))
  8298. barList := fsions.Get("barList").Array()
  8299. pastureid := fsions.Get("pastureId").ValueStr()
  8300. tx := restful.Engine.NewSession()
  8301. defer tx.Close()
  8302. 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
  8303. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8304. if err != nil {
  8305. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8306. return
  8307. }
  8308. for _, barFsions := range barList {
  8309. dataexcel := make(map[string]interface{}, 0)
  8310. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8311. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8312. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8313. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8314. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8315. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8316. continue
  8317. }
  8318. // /*
  8319. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8320. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8321. if err != nil {
  8322. logs.Error(err)
  8323. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8324. return
  8325. }
  8326. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8327. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8328. if err != nil {
  8329. logs.Error(err)
  8330. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8331. return
  8332. }
  8333. // */
  8334. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8335. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8336. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8337. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8338. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8339. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8340. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8341. if err != nil {
  8342. logs.Error(err)
  8343. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8344. return
  8345. }
  8346. if !ftexist {
  8347. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8348. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8349. if err != nil {
  8350. logs.Error(err)
  8351. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8352. return
  8353. }
  8354. tx.SQL(` update fpdetail set ptuse = 0 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. }
  8361. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8362. if err != nil {
  8363. logs.Error(err)
  8364. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8365. return
  8366. }
  8367. if !exist {
  8368. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8369. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8370. if err != nil {
  8371. logs.Error(err)
  8372. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8373. return
  8374. }
  8375. }
  8376. var feedpargs []interface{}
  8377. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8378. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8379. if _, ok := dataexcel["ftname"]; ok {
  8380. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8381. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8382. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8383. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8384. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8385. } else {
  8386. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8387. }
  8388. if _, ok := dataexcel["ptsfname"]; ok {
  8389. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8390. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8391. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8392. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8393. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8394. } else {
  8395. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8396. }
  8397. upFeedpSql += " where barname = ? and pastureid = ? "
  8398. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8399. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8400. if err != nil {
  8401. logs.Error(err)
  8402. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8403. return
  8404. }
  8405. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8406. if err != nil {
  8407. logs.Error(err)
  8408. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8409. return
  8410. }
  8411. if !exist1 {
  8412. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  8413. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8414. if err != nil {
  8415. logs.Error(err)
  8416. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8417. return
  8418. }
  8419. }
  8420. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8421. if err != nil {
  8422. logs.Error(err)
  8423. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8424. return
  8425. }
  8426. if !exist2 {
  8427. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,2,0,0,0,-1,-1) `,
  8428. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8429. if err != nil {
  8430. logs.Error(err)
  8431. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8432. return
  8433. }
  8434. }
  8435. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8436. if err != nil {
  8437. logs.Error(err)
  8438. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8439. return
  8440. }
  8441. if !exist3 {
  8442. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,3,0,0,0,-1,-1) `,
  8443. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8444. if err != nil {
  8445. logs.Error(err)
  8446. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8447. return
  8448. }
  8449. }
  8450. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8451. if err != nil {
  8452. logs.Error(err)
  8453. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8454. return
  8455. }
  8456. if !exist4 {
  8457. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,4,0,0,0,-1,-1) `,
  8458. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8459. if err != nil {
  8460. logs.Error(err)
  8461. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8462. return
  8463. }
  8464. }
  8465. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8466. if err != nil {
  8467. logs.Error(err)
  8468. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8469. return
  8470. }
  8471. if !exist5 {
  8472. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
  8473. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8474. if err != nil {
  8475. logs.Error(err)
  8476. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8477. return
  8478. }
  8479. }
  8480. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8481. if err != nil {
  8482. logs.Error(err)
  8483. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8484. return
  8485. }
  8486. if !exist6 {
  8487. _, 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) `,
  8488. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8489. if err != nil {
  8490. logs.Error(err)
  8491. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8492. return
  8493. }
  8494. }
  8495. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8496. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8497. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8498. and pastureid = ? and times = ?`
  8499. var fpdargs1 []interface{}
  8500. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8501. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8502. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8503. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8504. if err != nil {
  8505. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8506. return
  8507. }
  8508. var fpdargs2 []interface{}
  8509. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8510. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8511. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8512. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8513. if err != nil {
  8514. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8515. return
  8516. }
  8517. var fpdargs3 []interface{}
  8518. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8519. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8520. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8521. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8522. if err != nil {
  8523. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8524. return
  8525. }
  8526. var fpdargs4 []interface{}
  8527. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8528. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8529. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8530. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8531. if err != nil {
  8532. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8533. return
  8534. }
  8535. var fpdargs5 []interface{}
  8536. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8537. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8538. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8539. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8540. if err != nil {
  8541. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8542. return
  8543. }
  8544. var fpdargs6 []interface{}
  8545. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8546. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8547. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8548. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8549. if err != nil {
  8550. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8551. return
  8552. }
  8553. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8554. 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()
  8555. if err != nil {
  8556. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8557. return
  8558. }
  8559. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8560. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8561. upFpdetailList := make([]*upFpdetail, 0)
  8562. for _, newfpd := range newList {
  8563. for _, oldfpd := range oldFpdList {
  8564. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8565. var oldweight, newweight float64
  8566. if oldfpd["weight"] != nil {
  8567. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8568. }
  8569. if newfpd["weight"] != nil {
  8570. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8571. }
  8572. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8573. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8574. Old: oldweight,
  8575. New: newweight,
  8576. Times: newfpd["times"].(int64),
  8577. Ptid: newfpd["ptid"].(int64),
  8578. Fweight: fweight,
  8579. Id: oldfpd["id"].(int64),
  8580. })
  8581. break
  8582. }
  8583. }
  8584. }
  8585. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8586. }
  8587. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8588. }
  8589. func UdBarSync(c *gin.Context) {
  8590. appG := app.Gin{C: c}
  8591. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8592. fsions := gofasion.NewFasion(string(dataByte))
  8593. pastureid := fsions.Get("pastureId").ValueStr()
  8594. tx := restful.Engine.NewSession()
  8595. defer tx.Close()
  8596. pastureinfo := new(udPastureInfo)
  8597. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8598. if err != nil {
  8599. logs.Error(err)
  8600. return
  8601. }
  8602. // gm.UdBarSync(pastureid, pastureinfo.Werks)
  8603. jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8604. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8605. }
  8606. func UdFeedSync(c *gin.Context) {
  8607. appG := app.Gin{C: c}
  8608. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8609. fsions := gofasion.NewFasion(string(dataByte))
  8610. pastureid := fsions.Get("pastureId").ValueStr()
  8611. tx := restful.Engine.NewSession()
  8612. defer tx.Close()
  8613. pastureinfo := new(udPastureInfo)
  8614. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8615. if err != nil {
  8616. logs.Error(err)
  8617. return
  8618. }
  8619. // gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8620. jpud.UdFeedSync(pastureid, pastureinfo.Werks)
  8621. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8622. }
  8623. func UdFeedtempletPush(c *gin.Context) {
  8624. appG := app.Gin{C: c}
  8625. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8626. fsions := gofasion.NewFasion(string(dataByte))
  8627. pastureid := fsions.Get("pastureId").ValueStr()
  8628. date := fsions.Get("date").ValueStr()
  8629. tx := restful.Engine.NewSession()
  8630. defer tx.Close()
  8631. pastureinfo := new(udPastureInfo)
  8632. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8633. if err != nil {
  8634. logs.Error(err)
  8635. return
  8636. }
  8637. // gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8638. jpud.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8639. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8640. }
  8641. func UdUtirPush(c *gin.Context) {
  8642. appG := app.Gin{C: c}
  8643. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8644. fsions := gofasion.NewFasion(string(dataByte))
  8645. pastureid := fsions.Get("pastureId").ValueStr()
  8646. date := fsions.Get("date").ValueStr()
  8647. tx := restful.Engine.NewSession()
  8648. defer tx.Close()
  8649. pastureinfo := new(udPastureInfo)
  8650. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8651. if err != nil {
  8652. logs.Error(err)
  8653. return
  8654. }
  8655. // gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8656. jpud.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8657. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8658. }
  8659. func UdBarFeedRemainPush(c *gin.Context) {
  8660. appG := app.Gin{C: c}
  8661. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8662. fsions := gofasion.NewFasion(string(dataByte))
  8663. pastureid := fsions.Get("pastureId").ValueStr()
  8664. date := fsions.Get("date").ValueStr()
  8665. tx := restful.Engine.NewSession()
  8666. defer tx.Close()
  8667. pastureinfo := new(udPastureInfo)
  8668. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8669. if err != nil {
  8670. logs.Error(err)
  8671. return
  8672. }
  8673. // gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8674. jpud.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8675. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8676. }
  8677. func UdMaterialIssuePush(c *gin.Context) {
  8678. appG := app.Gin{C: c}
  8679. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8680. fsions := gofasion.NewFasion(string(dataByte))
  8681. pastureid := fsions.Get("pastureId").ValueStr()
  8682. date := fsions.Get("date").ValueStr()
  8683. tx := restful.Engine.NewSession()
  8684. defer tx.Close()
  8685. pastureinfo := new(udPastureInfo)
  8686. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8687. if err != nil {
  8688. logs.Error(err)
  8689. return
  8690. }
  8691. // gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8692. jpud.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8693. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8694. }
  8695. //搅拌
  8696. func YmyUtirPush(c *gin.Context) {
  8697. appG := app.Gin{C: c}
  8698. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8699. fsions := gofasion.NewFasion(string(dataByte))
  8700. pastureid := fsions.Get("pastureId").ValueStr()
  8701. date := fsions.Get("date").ValueStr()
  8702. tx := restful.Engine.NewSession()
  8703. defer tx.Close()
  8704. pastureinfo := new(udPastureInfo)
  8705. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8706. if err != nil {
  8707. logs.Error(err)
  8708. return
  8709. }
  8710. ymy.YmyUtirPush(pastureid, pastureinfo.Werks, date)
  8711. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8712. }
  8713. //撒料
  8714. func YmyMaterialIssuePush(c *gin.Context) {
  8715. appG := app.Gin{C: c}
  8716. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8717. fsions := gofasion.NewFasion(string(dataByte))
  8718. pastureid := fsions.Get("pastureId").ValueStr()
  8719. date := fsions.Get("date").ValueStr()
  8720. tx := restful.Engine.NewSession()
  8721. defer tx.Close()
  8722. pastureinfo := new(udPastureInfo)
  8723. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8724. if err != nil {
  8725. logs.Error(err)
  8726. return
  8727. }
  8728. ymy.YmyMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8729. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8730. }
  8731. func YmyFeedtempletPush(c *gin.Context) {
  8732. appG := app.Gin{C: c}
  8733. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8734. fsions := gofasion.NewFasion(string(dataByte))
  8735. pastureid := fsions.Get("pastureId").ValueStr()
  8736. date := fsions.Get("date").ValueStr()
  8737. tx := restful.Engine.NewSession()
  8738. defer tx.Close()
  8739. pastureinfo := new(udPastureInfo)
  8740. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8741. if err != nil {
  8742. logs.Error(err)
  8743. return
  8744. }
  8745. ymy.YmyFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8746. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8747. }
  8748. //饲料
  8749. func YmySyncFeed(c *gin.Context) {
  8750. appG := app.Gin{C: c}
  8751. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8752. fsions := gofasion.NewFasion(string(dataByte))
  8753. pastureid := fsions.Get("pastureId").ValueStr()
  8754. // date := fsions.Get("date").ValueStr()
  8755. tx := restful.Engine.NewSession()
  8756. defer tx.Close()
  8757. ymy.YmySyncFeed(pastureid)
  8758. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8759. }
  8760. // 栏舍
  8761. func YmySyncBar(c *gin.Context) {
  8762. appG := app.Gin{C: c}
  8763. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8764. fsions := gofasion.NewFasion(string(dataByte))
  8765. pastureid := fsions.Get("pastureId").ValueStr()
  8766. // date := fsions.Get("date").ValueStr()
  8767. tx := restful.Engine.NewSession()
  8768. defer tx.Close()
  8769. pastureinfo := new(udPastureInfo)
  8770. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8771. if err != nil {
  8772. logs.Error(err)
  8773. return
  8774. }
  8775. ymy.YmySyncBar(pastureinfo.Werks, pastureid)
  8776. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8777. }
  8778. func DelFeedTemplet(c *gin.Context) {
  8779. appG := app.Gin{C: c}
  8780. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8781. fsions := gofasion.NewFasion(string(dataByte))
  8782. ftId := fsions.Get("ftId").ValueStr()
  8783. // userId := fsions.Get("userId").ValueStr()
  8784. tx := restful.Engine.NewSession()
  8785. defer tx.Close()
  8786. _, err := tx.Exec(` delete from feedtemplet 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 feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8794. if err != nil {
  8795. logs.Error(err)
  8796. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8797. return
  8798. }
  8799. */
  8800. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8801. if err != nil {
  8802. logs.Error(err)
  8803. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8804. return
  8805. }
  8806. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8807. if err != nil {
  8808. logs.Error(err)
  8809. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8810. return
  8811. }
  8812. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8813. if count > 0 {
  8814. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id 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. }
  8821. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8822. if err != nil {
  8823. logs.Error(err)
  8824. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8825. return
  8826. }
  8827. // var barIdStr []string
  8828. // for _, bar := range barIdList {
  8829. // barIdStr = append(barIdStr, bar["barid"])
  8830. // }
  8831. // if len(barIdStr) > 0 {
  8832. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8833. // if err != nil {
  8834. // logs.Error(err)
  8835. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8836. // return
  8837. // }
  8838. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8839. // if err != nil {
  8840. // logs.Error(err)
  8841. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8842. // return
  8843. // }
  8844. // now := time.Now()
  8845. // for _, newFpd := range newFpdDataList {
  8846. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8847. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8848. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8849. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8850. // if err != nil {
  8851. // logs.Error(err)
  8852. // appG.Response(http.StatusOK, e.ERROR, false)
  8853. // return
  8854. // }
  8855. // }
  8856. // for _, newFeedp := range newFeedpList {
  8857. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8858. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8859. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8860. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8861. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8862. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8863. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8864. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8865. // if err != nil {
  8866. // logs.Error(err)
  8867. // appG.Response(http.StatusOK, e.ERROR, false)
  8868. // return
  8869. // }
  8870. // }
  8871. // }
  8872. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8873. }
  8874. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8875. sysOpt := new(models.SysOpt)
  8876. tx.Table("sysopt").Where("inforname = ?", "separateVehicles").Get(sysOpt)
  8877. lweight := 0.0
  8878. if sysOpt.InforValue != "" {
  8879. lweight, _ = strconv.ParseFloat(sysOpt.InforValue, 64)
  8880. } else if sysOpt.InforValue == "" || sysOpt.InforValue == "0" {
  8881. return
  8882. }
  8883. fmt.Println(sysOpt)
  8884. data := fasion["parammaps"].(map[string]interface{})
  8885. // plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(2) ").Count()
  8886. downloadedplanList := make([]*models.DownloadedPlan, 0)
  8887. tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype = 2 ").Find(&downloadedplanList)
  8888. fmt.Println(lweight)
  8889. for _, downloadedplan := range downloadedplanList {
  8890. if downloadedplan.LWeight < lweight {
  8891. break
  8892. }
  8893. downloadplandtl1List := make([]*models.DownloadPlanDtl1, 0)
  8894. downloadplandtl1ExecList := make([]*models.DownloadPlanDtl1Exec, 0)
  8895. downloadplandtl2List := make([]*models.DownloadPlanDtl2, 0)
  8896. tx.Table("downloadplandtl1").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1List)
  8897. tx.Table("downloadplandtl2").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl2List)
  8898. tx.Table("downloadplandtl1_exec").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1ExecList)
  8899. lweightCount := math.Floor(downloadedplan.LWeight / lweight)
  8900. for i := 0; i <= int(lweightCount); i++ {
  8901. if i == 0 {
  8902. tx.Exec(` update downloadedplan set lweight = ? where id = ? `, lweight, downloadedplan.ID)
  8903. for _, downloadplandtl1 := range downloadplandtl1List {
  8904. tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl1.LWeight, downloadplandtl1.ID)
  8905. }
  8906. for _, downloadplandtl2 := range downloadplandtl2List {
  8907. tx.Exec(` update downloadplandtl2 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8908. }
  8909. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  8910. tx.Exec(` update downloadplandtl1_exec set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8911. }
  8912. // && downloadedplan.LWeight >lweight
  8913. } else if i < int(lweightCount) {
  8914. parts := strings.Split(downloadedplan.ProjName, ".")
  8915. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  8916. data := &models.DownloadedPlan{
  8917. PastureID: downloadedplan.PastureID,
  8918. MyDate: downloadedplan.MyDate,
  8919. ProjName: strings.Join(parts, "."),
  8920. DataCaptureNo: downloadedplan.DataCaptureNo,
  8921. TmrID: downloadedplan.TmrID,
  8922. TmrtName: downloadedplan.TmrtName,
  8923. HaveButton: downloadedplan.HaveButton,
  8924. InButtonType: downloadedplan.InButtonType,
  8925. PlanTime: downloadedplan.PlanTime,
  8926. InTime: downloadedplan.InTime,
  8927. CompletedTime: downloadedplan.CompletedTime,
  8928. IsCompleted: downloadedplan.IsCompleted,
  8929. LpPlanType: downloadedplan.LpPlanType,
  8930. Times: downloadedplan.Times,
  8931. Sort: downloadedplan.Sort,
  8932. Remark: downloadedplan.Remark,
  8933. ItemNum: downloadedplan.ItemNum,
  8934. OutItems: downloadedplan.OutItems,
  8935. FeedPName: downloadedplan.FeedPName,
  8936. FeedPCount: downloadedplan.FeedPCount,
  8937. Pid: downloadedplan.Pid,
  8938. TempID: downloadedplan.TempID,
  8939. TempletName: downloadedplan.TempletName,
  8940. PtsTempID: downloadedplan.PtsTempID,
  8941. PtsTempletName: downloadedplan.PtsTempletName,
  8942. ThoWeight: downloadedplan.ThoWeight,
  8943. FpWeight: downloadedplan.FpWeight,
  8944. LWeight: lweight,
  8945. IWeight: downloadedplan.IWeight,
  8946. OWeight: downloadedplan.OWeight,
  8947. TVersion: downloadedplan.TVersion,
  8948. PtVersion: downloadedplan.PtVersion,
  8949. Enable: downloadedplan.Enable,
  8950. IsUse: downloadedplan.IsUse,
  8951. OldTmrID: downloadedplan.OldTmrID,
  8952. DriverID: downloadedplan.DriverID,
  8953. Artificial: downloadedplan.Artificial,
  8954. }
  8955. _, err := tx.Insert(data)
  8956. fmt.Println(data, err)
  8957. for _, downloadplandtl1 := range downloadplandtl1List {
  8958. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8959. d1 := &models.DownloadPlanDtl1{
  8960. PastureID: downloadplandtl1.PastureID,
  8961. Pid: data.ID,
  8962. Flpid: downloadplandtl1.Flpid,
  8963. Fid: downloadplandtl1.Fid,
  8964. LWeight: lweight / downloadedplan.LWeight * downloadplandtl1.LWeight,
  8965. Sort: downloadplandtl1.Sort,
  8966. ButtonType: downloadplandtl1.ButtonType,
  8967. OptDevice: downloadplandtl1.OptDevice,
  8968. FeedCode: downloadplandtl1.FeedCode,
  8969. FName: downloadplandtl1.FName,
  8970. FeedSort: downloadplandtl1.FeedSort,
  8971. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  8972. StirDelay: downloadplandtl1.StirDelay,
  8973. FWeight: downloadplandtl1.FWeight,
  8974. TmrLoadName: downloadplandtl1.TmrLoadName,
  8975. DryFeed: downloadplandtl1.DryFeed,
  8976. PriceFeed: downloadplandtl1.PriceFeed,
  8977. OutWeight: downloadplandtl1.OutWeight,
  8978. ErrRatio: downloadplandtl1.ErrRatio,
  8979. Date: downloadplandtl1.Date,
  8980. ButtonSucc: downloadplandtl1.ButtonSucc,
  8981. Type: downloadplandtl1.Type,
  8982. Deviation: downloadplandtl1.Deviation,
  8983. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  8984. }
  8985. tx.Insert(d1)
  8986. }
  8987. for _, downloadplandtl2 := range downloadplandtl2List {
  8988. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8989. d2 := &models.DownloadPlanDtl2{
  8990. PastureID: downloadplandtl2.PastureID,
  8991. Pid: data.ID,
  8992. Flpid: downloadplandtl2.Flpid,
  8993. Fbarid: downloadplandtl2.Fbarid,
  8994. FName: downloadplandtl2.FName,
  8995. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8996. LWeightHis: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8997. RemainLeftW: downloadplandtl2.RemainLeftW,
  8998. AllowRW: downloadplandtl2.AllowRW,
  8999. Sort: downloadplandtl2.Sort,
  9000. HaveButton: downloadplandtl2.HaveButton,
  9001. BeginTag: downloadplandtl2.BeginTag,
  9002. EndTag: downloadplandtl2.EndTag,
  9003. ButtonType: downloadplandtl2.ButtonType,
  9004. OptDevice: downloadplandtl2.OptDevice,
  9005. CowCount: downloadplandtl2.CowCount,
  9006. CowClassID: downloadplandtl2.CowClassID,
  9007. CowClassName: downloadplandtl2.CowClassName,
  9008. BigCowName: downloadplandtl2.BigCowName,
  9009. PWeight: downloadplandtl2.PWeight,
  9010. CCountRatio: downloadplandtl2.CCountRatio,
  9011. SumRTime: downloadplandtl2.SumRTime,
  9012. FeedTempletID: downloadplandtl2.FeedTempletID,
  9013. FeedTempletName: downloadplandtl2.FeedTempletName,
  9014. DryWeight: downloadplandtl2.DryWeight,
  9015. SumWeight: downloadplandtl2.SumWeight,
  9016. PriceWeight: downloadplandtl2.PriceWeight,
  9017. // ProcessTime :downloadplandtl2.ProcessTime ,
  9018. Fpid: downloadplandtl2.Fpid,
  9019. UseInBarType: downloadplandtl2.UseInBarType,
  9020. Date: downloadplandtl2.Date,
  9021. AllowRatio: downloadplandtl2.AllowRatio,
  9022. ErrRatio: downloadplandtl2.ErrRatio,
  9023. ButtonSucc: downloadplandtl2.ButtonSucc,
  9024. Type: downloadplandtl2.Type,
  9025. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9026. XxwBarCode: downloadplandtl2.XxwBarCode,
  9027. }
  9028. _, err := tx.Insert(d2)
  9029. fmt.Println(err)
  9030. }
  9031. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9032. d2 := &models.DownloadPlanDtl1Exec{
  9033. PastureID: downloadplandtl2.PastureID,
  9034. Pid: data.ID,
  9035. Flpid: downloadplandtl2.Flpid,
  9036. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9037. HaveButton: downloadplandtl2.HaveButton,
  9038. ButtonType: downloadplandtl2.ButtonType,
  9039. OptDevice: downloadplandtl2.OptDevice,
  9040. Sort: downloadplandtl2.Sort,
  9041. FName: downloadplandtl2.FName,
  9042. FCount: downloadplandtl2.FCount,
  9043. TmrLoadName: downloadplandtl2.TmrLoadName,
  9044. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9045. StirDelay: downloadplandtl2.StirDelay,
  9046. ButtonSucc: downloadplandtl2.ButtonSucc,
  9047. ErrRatio: downloadplandtl2.ErrRatio,
  9048. Date: downloadplandtl2.Date,
  9049. Type: downloadplandtl2.Type,
  9050. Deviation: downloadplandtl2.Deviation,
  9051. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9052. }
  9053. _, err := tx.Insert(d2)
  9054. fmt.Println(err)
  9055. }
  9056. } else {
  9057. parts := strings.Split(downloadedplan.ProjName, ".")
  9058. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  9059. if downloadedplan.LWeight-float64(i)*lweight <= 0 {
  9060. continue
  9061. }
  9062. data := &models.DownloadedPlan{
  9063. PastureID: downloadedplan.PastureID,
  9064. MyDate: downloadedplan.MyDate,
  9065. ProjName: strings.Join(parts, "."),
  9066. DataCaptureNo: downloadedplan.DataCaptureNo,
  9067. TmrID: downloadedplan.TmrID,
  9068. TmrtName: downloadedplan.TmrtName,
  9069. HaveButton: downloadedplan.HaveButton,
  9070. InButtonType: downloadedplan.InButtonType,
  9071. PlanTime: downloadedplan.PlanTime,
  9072. InTime: downloadedplan.InTime,
  9073. CompletedTime: downloadedplan.CompletedTime,
  9074. IsCompleted: downloadedplan.IsCompleted,
  9075. LpPlanType: downloadedplan.LpPlanType,
  9076. Times: downloadedplan.Times,
  9077. Sort: downloadedplan.Sort,
  9078. Remark: downloadedplan.Remark,
  9079. ItemNum: downloadedplan.ItemNum,
  9080. OutItems: downloadedplan.OutItems,
  9081. FeedPName: downloadedplan.FeedPName,
  9082. FeedPCount: downloadedplan.FeedPCount,
  9083. Pid: downloadedplan.Pid,
  9084. TempID: downloadedplan.TempID,
  9085. TempletName: downloadedplan.TempletName,
  9086. PtsTempID: downloadedplan.PtsTempID,
  9087. PtsTempletName: downloadedplan.PtsTempletName,
  9088. ThoWeight: downloadedplan.ThoWeight,
  9089. FpWeight: downloadedplan.FpWeight,
  9090. LWeight: downloadedplan.LWeight - float64(i)*lweight,
  9091. IWeight: downloadedplan.IWeight,
  9092. OWeight: downloadedplan.OWeight,
  9093. TVersion: downloadedplan.TVersion,
  9094. PtVersion: downloadedplan.PtVersion,
  9095. Enable: downloadedplan.Enable,
  9096. IsUse: downloadedplan.IsUse,
  9097. OldTmrID: downloadedplan.OldTmrID,
  9098. DriverID: downloadedplan.DriverID,
  9099. Artificial: downloadedplan.Artificial,
  9100. }
  9101. _, err := tx.Insert(data)
  9102. fmt.Println(data, err)
  9103. for _, downloadplandtl1 := range downloadplandtl1List {
  9104. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9105. d1 := &models.DownloadPlanDtl1{
  9106. PastureID: downloadplandtl1.PastureID,
  9107. Pid: data.ID,
  9108. Flpid: downloadplandtl1.Flpid,
  9109. Fid: downloadplandtl1.Fid,
  9110. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl1.LWeight,
  9111. Sort: downloadplandtl1.Sort,
  9112. ButtonType: downloadplandtl1.ButtonType,
  9113. OptDevice: downloadplandtl1.OptDevice,
  9114. FeedCode: downloadplandtl1.FeedCode,
  9115. FName: downloadplandtl1.FName,
  9116. FeedSort: downloadplandtl1.FeedSort,
  9117. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  9118. StirDelay: downloadplandtl1.StirDelay,
  9119. FWeight: downloadplandtl1.FWeight,
  9120. TmrLoadName: downloadplandtl1.TmrLoadName,
  9121. DryFeed: downloadplandtl1.DryFeed,
  9122. PriceFeed: downloadplandtl1.PriceFeed,
  9123. OutWeight: downloadplandtl1.OutWeight,
  9124. ErrRatio: downloadplandtl1.ErrRatio,
  9125. Date: downloadplandtl1.Date,
  9126. ButtonSucc: downloadplandtl1.ButtonSucc,
  9127. Type: downloadplandtl1.Type,
  9128. Deviation: downloadplandtl1.Deviation,
  9129. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  9130. }
  9131. tx.Insert(d1)
  9132. }
  9133. for _, downloadplandtl2 := range downloadplandtl2List {
  9134. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9135. d2 := &models.DownloadPlanDtl2{
  9136. PastureID: downloadplandtl2.PastureID,
  9137. Pid: data.ID,
  9138. Flpid: downloadplandtl2.Flpid,
  9139. Fbarid: downloadplandtl2.Fbarid,
  9140. FName: downloadplandtl2.FName,
  9141. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9142. LWeightHis: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9143. RemainLeftW: downloadplandtl2.RemainLeftW,
  9144. AllowRW: downloadplandtl2.AllowRW,
  9145. Sort: downloadplandtl2.Sort,
  9146. HaveButton: downloadplandtl2.HaveButton,
  9147. BeginTag: downloadplandtl2.BeginTag,
  9148. EndTag: downloadplandtl2.EndTag,
  9149. ButtonType: downloadplandtl2.ButtonType,
  9150. OptDevice: downloadplandtl2.OptDevice,
  9151. CowCount: downloadplandtl2.CowCount,
  9152. CowClassID: downloadplandtl2.CowClassID,
  9153. CowClassName: downloadplandtl2.CowClassName,
  9154. BigCowName: downloadplandtl2.BigCowName,
  9155. PWeight: downloadplandtl2.PWeight,
  9156. CCountRatio: downloadplandtl2.CCountRatio,
  9157. SumRTime: downloadplandtl2.SumRTime,
  9158. FeedTempletID: downloadplandtl2.FeedTempletID,
  9159. FeedTempletName: downloadplandtl2.FeedTempletName,
  9160. DryWeight: downloadplandtl2.DryWeight,
  9161. SumWeight: downloadplandtl2.SumWeight,
  9162. PriceWeight: downloadplandtl2.PriceWeight,
  9163. // ProcessTime :downloadplandtl2.ProcessTime ,
  9164. Fpid: downloadplandtl2.Fpid,
  9165. UseInBarType: downloadplandtl2.UseInBarType,
  9166. Date: downloadplandtl2.Date,
  9167. AllowRatio: downloadplandtl2.AllowRatio,
  9168. ErrRatio: downloadplandtl2.ErrRatio,
  9169. ButtonSucc: downloadplandtl2.ButtonSucc,
  9170. Type: downloadplandtl2.Type,
  9171. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9172. XxwBarCode: downloadplandtl2.XxwBarCode,
  9173. }
  9174. _, err := tx.Insert(d2)
  9175. fmt.Println(err)
  9176. }
  9177. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9178. d2 := &models.DownloadPlanDtl1Exec{
  9179. PastureID: downloadplandtl2.PastureID,
  9180. Pid: data.ID,
  9181. Flpid: downloadplandtl2.Flpid,
  9182. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9183. HaveButton: downloadplandtl2.HaveButton,
  9184. ButtonType: downloadplandtl2.ButtonType,
  9185. OptDevice: downloadplandtl2.OptDevice,
  9186. Sort: downloadplandtl2.Sort,
  9187. FName: downloadplandtl2.FName,
  9188. FCount: downloadplandtl2.FCount,
  9189. TmrLoadName: downloadplandtl2.TmrLoadName,
  9190. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9191. StirDelay: downloadplandtl2.StirDelay,
  9192. ButtonSucc: downloadplandtl2.ButtonSucc,
  9193. ErrRatio: downloadplandtl2.ErrRatio,
  9194. Date: downloadplandtl2.Date,
  9195. Type: downloadplandtl2.Type,
  9196. Deviation: downloadplandtl2.Deviation,
  9197. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9198. }
  9199. fmt.Println(d2)
  9200. _, err := tx.Insert(d2)
  9201. fmt.Println(err)
  9202. }
  9203. }
  9204. }
  9205. }
  9206. downloadedplanSortList := make([]*models.DownloadedPlan, 0)
  9207. tx.SQL(`SELECT * FROM downloadedplan WHERE mydate = ? ORDER BY projname`, data["startTime"]).Find(&downloadedplanSortList)
  9208. for i, d := range downloadedplanSortList {
  9209. tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, d.ID)
  9210. }
  9211. }
  9212. func EditPlanSort(c *gin.Context) {
  9213. appG := app.Gin{C: c}
  9214. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9215. fsions := gofasion.NewFasion(string(dataByte))
  9216. planIdStr := fsions.Get("planId").ValueStr()
  9217. mydate := fsions.Get("mydate").ValueStr()
  9218. sort := fsions.Get("sort").ValueStr()
  9219. tx := restful.Engine.NewSession()
  9220. defer tx.Close()
  9221. tx.Begin()
  9222. type downloadedplan struct {
  9223. Id int64 `xorm:"id"`
  9224. Sort int `xorm:"sort"`
  9225. Pid int64 `xorm:"pid"`
  9226. }
  9227. planInfo := new(downloadedplan)
  9228. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  9229. if err != nil {
  9230. logs.Error(err)
  9231. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9232. tx.Rollback()
  9233. return
  9234. }
  9235. sort1, _ := strconv.Atoi(sort)
  9236. if sort1 == planInfo.Sort {
  9237. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  9238. tx.Rollback()
  9239. return
  9240. }
  9241. 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()
  9242. if err != nil {
  9243. logs.Error(err)
  9244. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9245. tx.Rollback()
  9246. return
  9247. }
  9248. if count1 == 0 {
  9249. tx.Rollback()
  9250. logs.Error(err)
  9251. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  9252. return
  9253. }
  9254. 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()
  9255. if err != nil {
  9256. logs.Error(err)
  9257. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9258. tx.Rollback()
  9259. return
  9260. }
  9261. if count > 0 {
  9262. tx.Rollback()
  9263. logs.Error(err)
  9264. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  9265. return
  9266. }
  9267. if planInfo.Sort > sort1 {
  9268. 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()
  9269. if err != nil {
  9270. logs.Error(err)
  9271. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9272. tx.Rollback()
  9273. return
  9274. }
  9275. var minSort, pidCount int
  9276. for _, sort := range minSortList {
  9277. minSort, _ = strconv.Atoi(sort["sort"])
  9278. }
  9279. planList := make([]*downloadedplan, 0)
  9280. 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)
  9281. if err != nil {
  9282. logs.Error(err)
  9283. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9284. tx.Rollback()
  9285. return
  9286. }
  9287. planPid := planInfo.Pid
  9288. planList1 := make([]*downloadedplan, 0)
  9289. planList2 := make([]*downloadedplan, 0)
  9290. for _, plan := range planList {
  9291. if plan.Pid == planPid {
  9292. pidCount++
  9293. planList1 = append(planList1, plan)
  9294. } else {
  9295. planList2 = append(planList2, plan)
  9296. }
  9297. }
  9298. planList1 = append(planList1, planList2...)
  9299. for i, plan := range planList1 {
  9300. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  9301. if err != nil {
  9302. logs.Error(err)
  9303. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9304. tx.Rollback()
  9305. return
  9306. }
  9307. }
  9308. } else {
  9309. 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()
  9310. if err != nil {
  9311. logs.Error(err)
  9312. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9313. tx.Rollback()
  9314. return
  9315. }
  9316. var maxSort int
  9317. for _, sort := range maxSortList {
  9318. maxSort, _ = strconv.Atoi(sort["sort"])
  9319. }
  9320. planList := make([]*downloadedplan, 0)
  9321. 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)
  9322. if err != nil {
  9323. logs.Error(err)
  9324. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9325. tx.Rollback()
  9326. return
  9327. }
  9328. planPid := planInfo.Pid
  9329. planList1 := make([]*downloadedplan, 0)
  9330. planList2 := make([]*downloadedplan, 0)
  9331. for _, plan := range planList {
  9332. if plan.Pid == planPid {
  9333. // pidCount++
  9334. planList1 = append(planList1, plan)
  9335. } else {
  9336. planList2 = append(planList2, plan)
  9337. }
  9338. }
  9339. planList2 = append(planList2, planList1...)
  9340. for i, plan := range planList2 {
  9341. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  9342. if err != nil {
  9343. logs.Error(err)
  9344. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9345. tx.Rollback()
  9346. return
  9347. }
  9348. }
  9349. }
  9350. err = tx.Commit()
  9351. if err != nil {
  9352. logs.Error(err)
  9353. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9354. tx.Rollback()
  9355. return
  9356. }
  9357. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9358. }
  9359. func EditDownloadedplanArtificial(c *gin.Context) {
  9360. appG := app.Gin{C: c}
  9361. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9362. fsions := gofasion.NewFasion(string(dataByte))
  9363. planIdStr := fsions.Get("planId").ValueStr()
  9364. tx := restful.Engine.NewSession()
  9365. defer tx.Close()
  9366. tx.Begin()
  9367. planIdList := strings.Split(planIdStr, ",")
  9368. for _, planId := range planIdList {
  9369. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? `, planId)
  9370. if err != nil {
  9371. logs.Error(err)
  9372. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9373. tx.Rollback()
  9374. return
  9375. }
  9376. }
  9377. err := tx.Commit()
  9378. if err != nil {
  9379. logs.Error(err)
  9380. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9381. tx.Rollback()
  9382. return
  9383. }
  9384. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9385. }
  9386. type PlanRFID struct {
  9387. RFID string `json:"RFID"`
  9388. Lweight string `json:"lweight"`
  9389. Gear string `json:"gear"`
  9390. Speed string `json:"speed"`
  9391. }
  9392. func GetPlanRFID(c *gin.Context) {
  9393. appG := app.Gin{C: c}
  9394. RFIDStr := c.Query("RFID")
  9395. planRFIDList := make([]*PlanRFID, 0)
  9396. planRFIDList = append(planRFIDList, &PlanRFID{
  9397. RFID: RFIDStr,
  9398. Lweight: "1411.1",
  9399. Gear: "1",
  9400. Speed: "10",
  9401. })
  9402. planRFIDList = append(planRFIDList, &PlanRFID{
  9403. RFID: RFIDStr,
  9404. Lweight: "1322.1",
  9405. Gear: "1",
  9406. Speed: "10",
  9407. })
  9408. planRFIDList = append(planRFIDList, &PlanRFID{
  9409. RFID: RFIDStr,
  9410. Lweight: "1904.1",
  9411. Gear: "1",
  9412. Speed: "10",
  9413. })
  9414. planRFIDList = append(planRFIDList, &PlanRFID{
  9415. RFID: RFIDStr,
  9416. Lweight: "1870.1",
  9417. Gear: "1",
  9418. Speed: "10",
  9419. })
  9420. planRFIDList = append(planRFIDList, &PlanRFID{
  9421. RFID: RFIDStr,
  9422. Lweight: "2041.1",
  9423. Gear: "1",
  9424. Speed: "10",
  9425. })
  9426. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  9427. }
  9428. type tmrEquipmentMuster struct {
  9429. A string
  9430. N string
  9431. }
  9432. func GetTmrEquipmentMuster(c *gin.Context) {
  9433. appG := app.Gin{C: c}
  9434. id := c.Query("id")
  9435. tx := restful.Engine.NewSession()
  9436. defer tx.Close()
  9437. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  9438. if err != nil {
  9439. logs.Error(err)
  9440. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9441. return
  9442. }
  9443. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  9444. for _, data := range dataList {
  9445. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  9446. for _, g := range tmrEquipmentMusterList {
  9447. a, _ := strconv.ParseFloat(g.A, 64)
  9448. n, _ := strconv.ParseFloat(g.N, 64)
  9449. a1, n1 := ddmmtoddd(a, n)
  9450. g.A = fmt.Sprintf("%f", n1)
  9451. g.N = fmt.Sprintf("%f", a1)
  9452. }
  9453. }
  9454. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  9455. }
  9456. func ddmmtoddd(lng, lat float64) (float64, float64) {
  9457. lngDegree := fmt.Sprintf("%f", lng/100)
  9458. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  9459. lngDegreeInt := int(lngDegreefloat * 1000000)
  9460. dd := lngDegreeInt / 100 * 100 / 60
  9461. fmt.Println(dd)
  9462. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  9463. latDegree := fmt.Sprintf("%f", lat/100)
  9464. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  9465. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  9466. latDegreeInt := int(latDegreefloat * 1000000)
  9467. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  9468. a, _ := strconv.ParseFloat(lngStr, 64)
  9469. b, _ := strconv.ParseFloat(latStr, 64)
  9470. return coordtransform.WGS84toGCJ02(b, a)
  9471. }
  9472. func EditDownloadedplanExecWeight(c *gin.Context) {
  9473. appG := app.Gin{C: c}
  9474. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9475. fsions := gofasion.NewFasion(string(dataByte))
  9476. pid := fsions.Get("pid").ValueStr()
  9477. sort := fsions.Get("sort").ValueStr()
  9478. weight := fsions.Get("weight").ValueStr()
  9479. userId := fsions.Get("userId").ValueStr()
  9480. tx := restful.Engine.NewSession()
  9481. defer tx.Close()
  9482. tx.Begin()
  9483. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  9484. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  9485. pid, sort, pid, sort, weight, userId)
  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_exec set actualweightminus = ? where pid = ? and 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.Exec(` update downloadplandtl1 set actualweightminus = lweight / (select sum(lweight) from downloadplandtl1 where pid = ? and sort = ? ) * ? where pid = ? and sort = ? `, pid, sort, weight, pid, sort)
  9500. if err != nil {
  9501. logs.Error(err)
  9502. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9503. tx.Rollback()
  9504. return
  9505. }
  9506. err = tx.Commit()
  9507. if err != nil {
  9508. logs.Error(err)
  9509. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9510. tx.Rollback()
  9511. return
  9512. }
  9513. appG.Response(http.StatusOK, e.SUCCESS, true)
  9514. }
  9515. func EditDownloadplandtl2Weight(c *gin.Context) {
  9516. appG := app.Gin{C: c}
  9517. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9518. fsions := gofasion.NewFasion(string(dataByte))
  9519. pid := fsions.Get("pid").ValueStr()
  9520. sort := fsions.Get("sort").ValueStr()
  9521. weight := fsions.Get("weight").ValueStr()
  9522. userId := fsions.Get("userId").ValueStr()
  9523. tx := restful.Engine.NewSession()
  9524. defer tx.Close()
  9525. tx.Begin()
  9526. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9527. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9528. pid, sort, pid, sort, weight, userId)
  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.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9536. if err != nil {
  9537. logs.Error(err)
  9538. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9539. tx.Rollback()
  9540. return
  9541. }
  9542. err = tx.Commit()
  9543. if err != nil {
  9544. logs.Error(err)
  9545. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9546. tx.Rollback()
  9547. return
  9548. }
  9549. appG.Response(http.StatusOK, e.SUCCESS, true)
  9550. }
  9551. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9552. params := fasion.Get("parammaps")
  9553. surplus := params.Get("surplus").ValueStr()
  9554. surplusId := params.Get("surplusId").ValueStr()
  9555. tx := restful.Engine.NewSession()
  9556. defer tx.Close()
  9557. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9558. if surplusId != "0" {
  9559. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9560. if err != nil {
  9561. log.Println("PostDataByName-error-1: ", err)
  9562. return errors.New("配方修改失败!")
  9563. }
  9564. type ftdetail struct {
  9565. Id string
  9566. Fname string
  9567. Sort int64
  9568. }
  9569. ftList := make([]*ftdetail, 0)
  9570. for _, data := range dataList {
  9571. ft := new(ftdetail)
  9572. ft.Fname = data["fname"]
  9573. ft.Id = data["id"]
  9574. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9575. if err != nil {
  9576. log.Println("PostDataByName-error-2: ", err)
  9577. return err
  9578. }
  9579. ft.Sort = sort
  9580. ftList = append(ftList, ft)
  9581. }
  9582. if surplus == "日粮" {
  9583. for _, ft := range ftList {
  9584. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9585. }
  9586. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9587. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9588. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9589. fmt.Println(err)
  9590. } else {
  9591. var sort int64
  9592. for _, ft := range ftList {
  9593. if ft.Fname == surplus {
  9594. sort = ft.Sort
  9595. break
  9596. }
  9597. }
  9598. if sort == 0 {
  9599. for _, ft := range ftList {
  9600. ft.Sort = ft.Sort + 1
  9601. }
  9602. } else {
  9603. for _, ft := range ftList {
  9604. if ft.Sort >= sort {
  9605. ft.Sort = ft.Sort + 1
  9606. }
  9607. }
  9608. }
  9609. for _, ft := range ftList {
  9610. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9611. }
  9612. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9613. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9614. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9615. if err != nil {
  9616. log.Println("PostDataByName-error-1: ", err)
  9617. fmt.Println(err)
  9618. return errors.New("配方修改失败!")
  9619. }
  9620. }
  9621. }
  9622. return nil
  9623. }
  9624. func FeedSurplus(fasion *gofasion.Fasion) {
  9625. tx := restful.Engine.NewSession()
  9626. defer tx.Close()
  9627. params := fasion.Get("parammaps")
  9628. feedId := params.Get("id").ValueStr()
  9629. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9630. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9631. }
  9632. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9633. // params := fasion.Get("parammaps")
  9634. // surplus := params.Get("surplus").ValueStr()
  9635. // surplusId := params.Get("surplusId").ValueStr()
  9636. tx := restful.Engine.NewSession()
  9637. defer tx.Close()
  9638. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9639. if surplusId != "0" {
  9640. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9641. if err != nil {
  9642. log.Println("PostDataByName-error-1: ", err)
  9643. return errors.New("配方修改失败!")
  9644. }
  9645. type ftdetail struct {
  9646. Id string
  9647. Fname string
  9648. Sort int64
  9649. }
  9650. ftList := make([]*ftdetail, 0)
  9651. for _, data := range dataList {
  9652. ft := new(ftdetail)
  9653. ft.Fname = data["fname"]
  9654. ft.Id = data["id"]
  9655. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9656. if err != nil {
  9657. log.Println("PostDataByName-error-2: ", err)
  9658. return err
  9659. }
  9660. ft.Sort = sort
  9661. ftList = append(ftList, ft)
  9662. }
  9663. if surplus == "日粮" {
  9664. for _, ft := range ftList {
  9665. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9666. }
  9667. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9668. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9669. pastureId, id, surplusId, surplusId, surplusId)
  9670. fmt.Println(err)
  9671. } else {
  9672. var sort int64
  9673. for _, ft := range ftList {
  9674. if ft.Fname == surplus {
  9675. sort = ft.Sort
  9676. break
  9677. }
  9678. }
  9679. if sort == 0 {
  9680. for _, ft := range ftList {
  9681. ft.Sort = ft.Sort + 1
  9682. }
  9683. } else {
  9684. for _, ft := range ftList {
  9685. if ft.Sort >= sort {
  9686. ft.Sort = ft.Sort + 1
  9687. }
  9688. }
  9689. }
  9690. for _, ft := range ftList {
  9691. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9692. }
  9693. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9694. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9695. id, surplusId, surplusId, sort, surplusId, pastureId)
  9696. if err != nil {
  9697. log.Println("PostDataByName-error-1: ", err)
  9698. fmt.Println(err)
  9699. return errors.New("配方修改失败!")
  9700. }
  9701. }
  9702. }
  9703. return nil
  9704. }
  9705. func GetLanguageStatus() string {
  9706. tx := restful.Engine.NewSession()
  9707. defer tx.Close()
  9708. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9709. if err != nil {
  9710. log.Println(err)
  9711. return "0"
  9712. }
  9713. return dataList[0]["inforvalue"]
  9714. }
  9715. func EditLanguage(c *gin.Context) {
  9716. appG := app.Gin{C: c}
  9717. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9718. fsions := gofasion.NewFasion(string(dataByte))
  9719. language := fsions.Get("language").ValueStr()
  9720. tx := restful.Engine.NewSession()
  9721. defer tx.Close()
  9722. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9723. if err != nil {
  9724. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9725. return
  9726. }
  9727. if language == "0" {
  9728. _, err := tx.Exec(`delete from dictlist `)
  9729. if err != nil {
  9730. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9731. return
  9732. }
  9733. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9734. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9735. if err != nil {
  9736. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9737. return
  9738. }
  9739. } else {
  9740. _, err := tx.Exec(`delete from dictlist `)
  9741. if err != nil {
  9742. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9743. return
  9744. }
  9745. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9746. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9747. if err != nil {
  9748. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9749. return
  9750. }
  9751. }
  9752. appG.Response(http.StatusOK, e.SUCCESS, true)
  9753. }
  9754. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9755. tx := restful.Engine.NewSession()
  9756. defer tx.Close()
  9757. 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
  9758. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9759. if err != nil {
  9760. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9761. return
  9762. }
  9763. for _, dataexcel := range barList {
  9764. // dataexcel := make(map[string]interface{}, 0)
  9765. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9766. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9767. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9768. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9769. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9770. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9771. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9772. // if err != nil {
  9773. // logs.Error(err)
  9774. // return
  9775. // }
  9776. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9777. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9778. // if err != nil {
  9779. // logs.Error(err)
  9780. // return
  9781. // }
  9782. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9783. continue
  9784. }
  9785. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9786. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9787. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9788. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9789. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9790. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9791. // /*
  9792. tx.SQL(` update lpplandtl1 set lweight = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9793. if err != nil {
  9794. logs.Error(err)
  9795. return
  9796. }
  9797. tx.SQL(` update fpdetail set ptuse = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9798. if err != nil {
  9799. logs.Error(err)
  9800. return
  9801. }
  9802. // */
  9803. exist, err := tx.SQL(` select id from feedp where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9804. if err != nil {
  9805. logs.Error(err)
  9806. return
  9807. }
  9808. if !exist {
  9809. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9810. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9811. if err != nil {
  9812. logs.Error(err)
  9813. return
  9814. }
  9815. }
  9816. var feedpargs []interface{}
  9817. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9818. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9819. if _, ok := dataexcel["ftname"]; ok {
  9820. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9821. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9822. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9823. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9824. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9825. } else {
  9826. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9827. }
  9828. if _, ok := dataexcel["ptsfname"]; ok {
  9829. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9830. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9831. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9832. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9833. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9834. } else {
  9835. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9836. }
  9837. upFeedpSql += " where barname = ? and pastureid = ? "
  9838. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9839. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9840. if err != nil {
  9841. logs.Error(err)
  9842. return
  9843. }
  9844. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9845. if err != nil {
  9846. logs.Error(err)
  9847. return
  9848. }
  9849. if !exist1 {
  9850. _, 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) `,
  9851. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9852. if err != nil {
  9853. logs.Error(err)
  9854. return
  9855. }
  9856. }
  9857. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9858. if err != nil {
  9859. logs.Error(err)
  9860. return
  9861. }
  9862. if !exist2 {
  9863. _, 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) `,
  9864. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9865. if err != nil {
  9866. logs.Error(err)
  9867. return
  9868. }
  9869. }
  9870. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9871. if err != nil {
  9872. logs.Error(err)
  9873. return
  9874. }
  9875. if !exist3 {
  9876. _, 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) `,
  9877. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9878. if err != nil {
  9879. logs.Error(err)
  9880. return
  9881. }
  9882. }
  9883. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9884. if err != nil {
  9885. logs.Error(err)
  9886. return
  9887. }
  9888. if !exist4 {
  9889. _, 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) `,
  9890. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9891. if err != nil {
  9892. logs.Error(err)
  9893. return
  9894. }
  9895. }
  9896. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9897. if err != nil {
  9898. logs.Error(err)
  9899. return
  9900. }
  9901. if !exist5 {
  9902. _, 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) `,
  9903. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9904. if err != nil {
  9905. logs.Error(err)
  9906. return
  9907. }
  9908. }
  9909. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9910. if err != nil {
  9911. logs.Error(err)
  9912. return
  9913. }
  9914. if !exist6 {
  9915. _, 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) `,
  9916. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9917. if err != nil {
  9918. logs.Error(err)
  9919. return
  9920. }
  9921. }
  9922. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9923. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9924. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9925. and pastureid = ? and times = ?`
  9926. var fpdargs1 []interface{}
  9927. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9928. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9929. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9930. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9931. if err != nil {
  9932. fmt.Println(err)
  9933. return
  9934. }
  9935. var fpdargs2 []interface{}
  9936. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9937. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9938. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9939. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9940. if err != nil {
  9941. fmt.Println(err)
  9942. return
  9943. }
  9944. var fpdargs3 []interface{}
  9945. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9946. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9947. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9948. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9949. if err != nil {
  9950. fmt.Println(err)
  9951. return
  9952. }
  9953. var fpdargs4 []interface{}
  9954. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9955. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9956. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9957. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9958. if err != nil {
  9959. fmt.Println(err)
  9960. return
  9961. }
  9962. var fpdargs5 []interface{}
  9963. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9964. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9965. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9966. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9967. if err != nil {
  9968. fmt.Println(err)
  9969. return
  9970. }
  9971. var fpdargs6 []interface{}
  9972. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  9973. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9974. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  9975. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  9976. if err != nil {
  9977. fmt.Println(err)
  9978. return
  9979. }
  9980. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  9981. 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()
  9982. if err != nil {
  9983. return
  9984. }
  9985. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9986. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9987. upFpdetailList := make([]*upFpdetail, 0)
  9988. for _, newfpd := range newList {
  9989. for _, oldfpd := range oldFpdList {
  9990. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  9991. var oldweight, newweight float64
  9992. if oldfpd["weight"] != nil {
  9993. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  9994. }
  9995. if newfpd["weight"] != nil {
  9996. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  9997. }
  9998. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  9999. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10000. Old: oldweight,
  10001. New: newweight,
  10002. Times: newfpd["times"].(int64),
  10003. Ptid: newfpd["ptid"].(int64),
  10004. Fweight: fweight,
  10005. Id: oldfpd["id"].(int64),
  10006. })
  10007. break
  10008. }
  10009. }
  10010. }
  10011. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  10012. }
  10013. }
  10014. func AddXxwFtdetail(c *gin.Context) {
  10015. appG := app.Gin{C: c}
  10016. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  10017. c.Bind(&xxwFtdetailList)
  10018. tx := restful.Engine.NewSession()
  10019. defer tx.Close()
  10020. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  10021. if err != nil {
  10022. logs.Error(err)
  10023. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10024. }
  10025. _, err = tx.Insert(xxwFtdetailList)
  10026. if err != nil {
  10027. logs.Error(err)
  10028. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10029. }
  10030. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  10031. appG.Response(http.StatusOK, e.SUCCESS, true)
  10032. }
  10033. func AddXxwFeedtemplet(c *gin.Context) {
  10034. appG := app.Gin{C: c}
  10035. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  10036. c.Bind(&xxwFeedtempletList)
  10037. tx := restful.Engine.NewSession()
  10038. defer tx.Close()
  10039. pastureinfo := new(udPastureInfo)
  10040. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  10041. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  10042. if err != nil {
  10043. logs.Error(err)
  10044. return
  10045. }
  10046. for _, ft := range xxwFeedtempletList {
  10047. ids, err := setting.SnowIds.NextId()
  10048. if err != nil {
  10049. ids = time.Now().UnixNano()
  10050. logging.Info("create SnowIds err", err)
  10051. }
  10052. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  10053. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  10054. ft.RecipeobjName, ft.RecipeobjName)
  10055. if err != nil {
  10056. logs.Error(err)
  10057. return
  10058. }
  10059. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  10060. _, 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')),
  10061. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  10062. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  10063. if err != nil {
  10064. logs.Error(err)
  10065. return
  10066. }
  10067. }
  10068. appG.Response(http.StatusOK, e.SUCCESS, true)
  10069. }
  10070. func ProcessExcel(c *gin.Context) {
  10071. appG := app.Gin{C: c}
  10072. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10073. fasion := gofasion.NewFasion(string(dataByte))
  10074. params := fasion.Get("parammaps")
  10075. pastureid := params.Get("pastureid").ValueStr()
  10076. startTime := params.Get("startTime").ValueStr()
  10077. stopTime := params.Get("stopTime").ValueStr()
  10078. iscompleted := params.Get("iscompleted").ValueStr()
  10079. lpplantype := params.Get("lpplantype").ValueStr()
  10080. error := params.Get("error").ValueStr()
  10081. hlwc1 := params.Get("hlwc1").ValueStr()
  10082. hlwc2 := params.Get("hlwc2").ValueStr()
  10083. slwc1 := params.Get("slwc1").ValueStr()
  10084. slwc2 := params.Get("slwc2").ValueStr()
  10085. hlzq1 := params.Get("hlzq1").ValueStr()
  10086. hlzq2 := params.Get("hlzq2").ValueStr()
  10087. slzq1 := params.Get("slzq1").ValueStr()
  10088. slzq2 := params.Get("slzq2").ValueStr()
  10089. fclassid := params.Get("fclassid").ValueStr()
  10090. minproesstime := params.Get("minproesstime").ValueStr()
  10091. maxproesstime := params.Get("maxproesstime").ValueStr()
  10092. tx := restful.Engine.NewSession()
  10093. defer tx.Close()
  10094. planList, err := tx.SQL(`SELECT
  10095. 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
  10096. FROM downloadedplan d
  10097. join pasture p on p.pastureid = d.pastureid
  10098. WHERE d.pastureid= ? and d.intime IS NOT NULL
  10099. AND mydate >= ? AND mydate <= ?
  10100. AND (iscompleted=? or ?='')
  10101. AND (lpplantype = ? or ? = '')
  10102. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  10103. 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
  10104. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  10105. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10106. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  10107. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10108. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  10109. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10110. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  10111. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10112. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  10113. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  10114. 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,
  10115. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  10116. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  10117. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  10118. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10119. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  10120. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  10121. or (?= '' and ? = '' ))
  10122. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  10123. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  10124. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  10125. maxproesstime, minproesstime, maxproesstime).QueryString()
  10126. if err != nil {
  10127. logs.Error(err)
  10128. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10129. return
  10130. }
  10131. planExecList, err := tx.SQL(`SELECT
  10132. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10133. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10134. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  10135. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10136. ) proesstime,
  10137. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10138. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  10139. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10140. sumproesstime, d1.pid,
  10141. d1.sort,
  10142. d1.fname,
  10143. d1.lweight,
  10144. d1.actualweightminus,
  10145. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  10146. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  10147. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  10148. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  10149. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  10150. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  10151. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  10152. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10153. d1.begintime stoptime,
  10154. d1.lastactualweight,
  10155. d1.actualweight,
  10156. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  10157. case d1.buttontype
  10158. when 1 then '自动'
  10159. when 2 then '手动'
  10160. when 3 then '手动'
  10161. end,
  10162. case d1.buttontype
  10163. when 1 then 'Automatic'
  10164. when 2 then 'Manual'
  10165. when 3 then 'Manual'
  10166. end
  10167. ) buttontype
  10168. FROM
  10169. downloadplandtl1_exec d1
  10170. WHERE d1.date between ? and ?
  10171. ORDER BY sort
  10172. `, startTime, stopTime).QueryString()
  10173. if err != nil {
  10174. logs.Error(err)
  10175. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10176. return
  10177. }
  10178. planExec2, err := tx.SQL(`SELECT
  10179. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  10180. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10181. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10182. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  10183. ) proesstime,
  10184. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  10185. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10186. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  10187. d1.sort,
  10188. d1.fname,
  10189. d1.lweight,
  10190. d1.actualweightminus,
  10191. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  10192. ABS(d1.lweight- d1.actualweightminus) diff,
  10193. 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,
  10194. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10195. d1.begintime stoptime,
  10196. d1.lastactualweight,
  10197. d1.actualweight,d1.pid
  10198. FROM
  10199. downloadplandtl2 d1
  10200. WHERE d1.date between ? and ?
  10201. ORDER BY sort`, startTime, stopTime).QueryString()
  10202. if err != nil {
  10203. logs.Error(err)
  10204. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10205. return
  10206. }
  10207. // 创建一个新的 Excel 文件
  10208. f := excelizexuri.NewFile()
  10209. // 创建工作表名称
  10210. sheetName := "Sheet1"
  10211. // border := []excelizexuri.Border{
  10212. // {Type: "left", Color: "000000", Style: 1},
  10213. // {Type: "right", Color: "000000", Style: 1},
  10214. // {Type: "top", Color: "000000", Style: 1},
  10215. // {Type: "bottom", Color: "000000", Style: 1},
  10216. // }
  10217. // 创建新的样式
  10218. style := &excelizexuri.Style{
  10219. // Border: border,
  10220. Alignment: &excelizexuri.Alignment{
  10221. Vertical: "center",
  10222. Horizontal: "center",
  10223. ShrinkToFit: true,
  10224. WrapText: true,
  10225. },
  10226. }
  10227. styleTitle := &excelizexuri.Style{
  10228. Fill: excelizexuri.Fill{
  10229. Color: []string{"FFFF0000"}, // 尝试使用完整的ARGB格式
  10230. },
  10231. // Border: border,
  10232. Font: &excelizexuri.Font{
  10233. Bold: true, // 加粗
  10234. Size: 24, // 字体大小
  10235. // Name: "宋体", // 字体名称
  10236. // WrapText :true,
  10237. Color: "000000", // 字体颜色(黑色)
  10238. },
  10239. Alignment: &excelizexuri.Alignment{
  10240. Vertical: "center", // 垂直居中
  10241. Horizontal: "center", // 水平居中
  10242. ShrinkToFit: true,
  10243. WrapText: true,
  10244. },
  10245. }
  10246. // 创建样式 ID
  10247. styleTitleId, err := f.NewStyle(styleTitle)
  10248. if err != nil {
  10249. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10250. return
  10251. }
  10252. // 创建样式 ID
  10253. styleID, err := f.NewStyle(style)
  10254. if err != nil {
  10255. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10256. return
  10257. }
  10258. // 合并单元格并设置内容
  10259. f.MergeCell(sheetName, "A1", "K1")
  10260. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  10261. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  10262. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  10263. planExecMap := make(map[string][]map[string]string, 0)
  10264. for _, planExec := range planExecList {
  10265. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  10266. }
  10267. plan2Map := make(map[string][]map[string]string, 0)
  10268. for _, plan2 := range planExec2 {
  10269. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  10270. }
  10271. num := 2
  10272. var notBorder []int
  10273. for _, plan := range planList {
  10274. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  10275. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10276. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10277. for i, header := range headers {
  10278. // 从 A2 开始
  10279. if header == "开始日期" {
  10280. cell := "%" + fmt.Sprintf("c%d", num)
  10281. cell = fmt.Sprintf(cell, 'A'+i+1)
  10282. f.SetCellValue(sheetName, cell, header)
  10283. f.SetCellStyle(sheetName, cell, cell, styleID)
  10284. continue
  10285. }
  10286. cell := "%" + fmt.Sprintf("c%d", num)
  10287. cell = fmt.Sprintf(cell, 'A'+i)
  10288. f.SetCellValue(sheetName, cell, header)
  10289. f.SetCellStyle(sheetName, cell, cell, styleID)
  10290. }
  10291. num += 1
  10292. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  10293. cell := "%" + fmt.Sprintf("c%d", num)
  10294. cell = fmt.Sprintf(cell, 'A'+0)
  10295. f.SetCellValue(sheetName, cell, plan["pastureName"])
  10296. f.SetCellStyle(sheetName, cell, cell, styleID)
  10297. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  10298. cell = "%" + fmt.Sprintf("c%d", num)
  10299. cell = fmt.Sprintf(cell, 'A'+1)
  10300. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  10301. f.SetCellStyle(sheetName, cell, cell, styleID)
  10302. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  10303. cell = "%" + fmt.Sprintf("c%d", num)
  10304. cell = fmt.Sprintf(cell, 'A'+2)
  10305. f.SetCellValue(sheetName, cell, plan["projname"])
  10306. f.SetCellStyle(sheetName, cell, cell, styleID)
  10307. cell = "%" + fmt.Sprintf("c%d", num)
  10308. cell = fmt.Sprintf(cell, 'A'+3)
  10309. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10310. f.SetCellValue(sheetName, cell, plan["mydate"])
  10311. f.SetCellStyle(sheetName, cell, cell, styleID)
  10312. cell = "%" + fmt.Sprintf("c%d", num)
  10313. cell = fmt.Sprintf(cell, 'A'+6)
  10314. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10315. f.SetCellValue(sheetName, cell, plan["intime"])
  10316. f.SetCellStyle(sheetName, cell, cell, styleID)
  10317. num += 1
  10318. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10319. for i, header := range headers1 {
  10320. cell = "%" + fmt.Sprintf("c%d", num)
  10321. cell = fmt.Sprintf(cell, 'C'+i)
  10322. f.SetCellValue(sheetName, cell, header)
  10323. f.SetCellStyle(sheetName, cell, cell, styleID)
  10324. // maxWidth := len(header)
  10325. // colName := string('C' + i)
  10326. // f.SetColWidth(sheetName, colName, colName, 20)
  10327. f.SetColWidth(sheetName, header, header, 40)
  10328. }
  10329. num += 1
  10330. // 在循环外部创建红色样式(只创建一次)
  10331. redStyle := &excelizexuri.Style{
  10332. Fill: excelizexuri.Fill{
  10333. Type: "pattern",
  10334. Color: []string{"FF0000"},
  10335. Pattern: 1,
  10336. },
  10337. // Font: &excelizexuri.Font{
  10338. // Bold: true, // 加粗
  10339. // Size: 24, // 字体大小
  10340. // // Name: "宋体", // 字体名称
  10341. // // WrapText :true,
  10342. // Color: "FFFF0000", // 字体颜色(黑色)
  10343. // },
  10344. Alignment: &excelizexuri.Alignment{
  10345. Vertical: "center",
  10346. Horizontal: "center",
  10347. ShrinkToFit: true,
  10348. WrapText: true,
  10349. },
  10350. }
  10351. redStyleID, err := f.NewStyle(redStyle)
  10352. if err != nil {
  10353. c.String(http.StatusInternalServerError, "Failed to create red style: "+err.Error())
  10354. return
  10355. }
  10356. // 在循环内部正确使用条件判断
  10357. for _, planExec := range planExecMap[plan["id"]] {
  10358. var currentStyleID int
  10359. if planExec["abnormal"] == "1" {
  10360. currentStyleID = redStyleID
  10361. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, planExec["abnormal"]) // 调试
  10362. } else {
  10363. currentStyleID = styleID
  10364. }
  10365. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10366. sort, _ := strconv.Atoi(planExec["sort"])
  10367. f.SetCellValue(sheetName, cell, sort)
  10368. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10369. cell = fmt.Sprintf("D%d", num)
  10370. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  10371. f.SetCellValue(sheetName, cell, lweight)
  10372. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10373. cell = fmt.Sprintf("E%d", num)
  10374. if _, ok := planExec["actualweightminus"]; ok {
  10375. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  10376. f.SetCellValue(sheetName, cell, actualweightminus)
  10377. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10378. } else {
  10379. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  10380. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10381. }
  10382. cell = fmt.Sprintf("F%d", num)
  10383. f.SetCellValue(sheetName, cell, planExec["fname"])
  10384. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10385. cell = fmt.Sprintf("G%d", num)
  10386. if _, ok := planExec["diff"]; ok {
  10387. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  10388. f.SetCellValue(sheetName, cell, diff)
  10389. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10390. } else {
  10391. f.SetCellValue(sheetName, cell, planExec["diff"])
  10392. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10393. }
  10394. cell = fmt.Sprintf("H%d", num)
  10395. if _, ok := planExec["diffRate"]; ok {
  10396. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  10397. f.SetCellValue(sheetName, cell, diffRate)
  10398. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10399. } else {
  10400. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  10401. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10402. }
  10403. cell = fmt.Sprintf("I%d", num)
  10404. f.SetCellValue(sheetName, cell, planExec["intime"])
  10405. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10406. cell = fmt.Sprintf("J%d", num)
  10407. if _, ok := planExec["lastactualweight"]; ok {
  10408. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  10409. f.SetCellValue(sheetName, cell, lastactualweight)
  10410. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10411. } else {
  10412. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  10413. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10414. }
  10415. cell = fmt.Sprintf("K%d", num)
  10416. if _, ok := planExec["actualweight"]; ok {
  10417. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  10418. f.SetCellValue(sheetName, cell, actualweight)
  10419. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10420. } else {
  10421. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  10422. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10423. }
  10424. num += 1
  10425. }
  10426. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10427. for i, header := range headers2 {
  10428. cell := "%" + fmt.Sprintf("c%d", num)
  10429. cell = fmt.Sprintf(cell, 'C'+i)
  10430. f.SetCellValue(sheetName, cell, header)
  10431. f.SetCellStyle(sheetName, cell, cell, styleID)
  10432. maxWidth := len(header)
  10433. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  10434. }
  10435. num += 1
  10436. for _, plan2 := range plan2Map[plan["id"]] {
  10437. var currentStyleID int
  10438. if plan2["abnormal"] == "1" {
  10439. currentStyleID = redStyleID
  10440. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, plan2["abnormal"]) // 调试
  10441. } else {
  10442. currentStyleID = styleID
  10443. }
  10444. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10445. sort, _ := strconv.Atoi(plan2["sort"])
  10446. f.SetCellValue(sheetName, cell, sort)
  10447. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10448. cell = fmt.Sprintf("D%d", num)
  10449. f.SetCellValue(sheetName, cell, plan2["fname"])
  10450. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10451. cell = fmt.Sprintf("E%d", num)
  10452. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  10453. f.SetCellValue(sheetName, cell, lweight)
  10454. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10455. cell = fmt.Sprintf("F%d", num)
  10456. if _, ok := plan2["actualweightminus"]; ok {
  10457. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  10458. f.SetCellValue(sheetName, cell, actualweightminus)
  10459. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10460. } else {
  10461. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  10462. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10463. }
  10464. cell = fmt.Sprintf("G%d", num)
  10465. if _, ok := plan2["diff"]; ok {
  10466. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  10467. f.SetCellValue(sheetName, cell, diff)
  10468. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10469. } else {
  10470. f.SetCellValue(sheetName, cell, plan2["diff"])
  10471. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10472. }
  10473. cell = fmt.Sprintf("H%d", num)
  10474. if _, ok := plan2["diffRate"]; ok {
  10475. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  10476. f.SetCellValue(sheetName, cell, diffRate)
  10477. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10478. } else {
  10479. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  10480. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10481. }
  10482. cell = fmt.Sprintf("I%d", num)
  10483. f.SetCellValue(sheetName, cell, plan2["intime"])
  10484. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10485. cell = fmt.Sprintf("J%d", num)
  10486. if _, ok := plan2["lastactualweight"]; ok {
  10487. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  10488. f.SetCellValue(sheetName, cell, lastactualweight)
  10489. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10490. } else {
  10491. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  10492. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10493. }
  10494. cell = fmt.Sprintf("K%d", num)
  10495. if _, ok := plan2["lastactualweight"]; ok {
  10496. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  10497. f.SetCellValue(sheetName, cell, actualweight)
  10498. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10499. } else {
  10500. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  10501. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10502. }
  10503. num += 1
  10504. }
  10505. num += 1
  10506. notBorder = append(notBorder, num)
  10507. }
  10508. // for i := 2; i < num; i++ {
  10509. // exist := false
  10510. // for _, n := range notBorder {
  10511. // if i+1 == n {
  10512. // exist = true
  10513. // break
  10514. // }
  10515. // }
  10516. // if !exist {
  10517. // // 为 A-K 列设置边框
  10518. // for col := 'A'; col <= 'K'; col++ {
  10519. // cellName := fmt.Sprintf("%c%d", col, i)
  10520. // style, _ := f.NewStyle(&excelizexuri.Style{
  10521. // // Border: border,
  10522. // Alignment: &excelizexuri.Alignment{
  10523. // Vertical: "center",
  10524. // Horizontal: "center",
  10525. // ShrinkToFit: true,
  10526. // WrapText: true,
  10527. // },
  10528. // })
  10529. // f.SetCellStyle(sheetName, cellName, cellName, style)
  10530. // }
  10531. // }
  10532. // }
  10533. for col := 'A'; col <= 'K'; col++ {
  10534. colName := string(col)
  10535. switch colName {
  10536. case "A", "B": // 牧场名称、TMR列
  10537. f.SetColWidth(sheetName, colName, colName, 10)
  10538. case "C": // 操作编号列
  10539. f.SetColWidth(sheetName, colName, colName, 10)
  10540. case "D", "E": // 计划重量、实际重量列
  10541. f.SetColWidth(sheetName, colName, colName, 12)
  10542. case "F": // 代表成分/投料位置列
  10543. f.SetColWidth(sheetName, colName, colName, 20)
  10544. case "G", "H": // 误差数、准确率列
  10545. f.SetColWidth(sheetName, colName, colName, 12)
  10546. case "I": // 完成时间列
  10547. f.SetColWidth(sheetName, colName, colName, 15)
  10548. case "J", "K": // 起始读数重量、完成读数重量列
  10549. f.SetColWidth(sheetName, colName, colName, 15)
  10550. }
  10551. }
  10552. // 设置响应头
  10553. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10554. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10555. c.Header("Content-Transfer-Encoding", "binary")
  10556. // 写入 Excel 文件到响应
  10557. if err := f.Write(c.Writer); err != nil {
  10558. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10559. return
  10560. }
  10561. }
  10562. func RestartMqtt(c *gin.Context) {
  10563. appG := app.Gin{C: c}
  10564. // 发送 GET 请求到 MQTT 重启接口
  10565. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10566. if err != nil {
  10567. logging.Error("RestartMqtt request failed:", err)
  10568. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10569. return
  10570. }
  10571. defer resp.Body.Close()
  10572. // 读取响应内容f
  10573. body, err := ioutil.ReadAll(resp.Body)
  10574. if err != nil {
  10575. logging.Error("RestartMqtt read response failed:", err)
  10576. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10577. return
  10578. }
  10579. // 检查响应状态码
  10580. if resp.StatusCode != http.StatusOK {
  10581. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10582. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10583. return
  10584. }
  10585. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10586. }
  10587. func FpdBatchEditByWeight(c *gin.Context) {
  10588. appG := app.Gin{C: c}
  10589. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10590. fsions := gofasion.NewFasion(string(dataByte))
  10591. barList := fsions.Get("barList").Array()
  10592. pastureid := fsions.Get("pastureId").ValueStr()
  10593. tx := restful.Engine.NewSession()
  10594. defer tx.Close()
  10595. 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
  10596. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10597. if err != nil {
  10598. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10599. return
  10600. }
  10601. for _, barFsions := range barList {
  10602. dataexcel := make(map[string]interface{}, 0)
  10603. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10604. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10605. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10606. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10607. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10608. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10609. continue
  10610. }
  10611. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10612. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10613. // if err != nil {
  10614. // logs.Error(err)
  10615. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10616. // return
  10617. // }
  10618. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10619. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10620. // if err != nil {
  10621. // logs.Error(err)
  10622. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10623. // return
  10624. // }
  10625. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10626. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10627. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10628. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10629. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10630. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10631. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10632. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10633. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10634. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10635. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10636. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10637. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10638. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10639. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10640. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10641. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10642. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10643. if err != nil {
  10644. logs.Error(err)
  10645. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10646. return
  10647. }
  10648. if !ftexist {
  10649. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10650. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10651. if err != nil {
  10652. logs.Error(err)
  10653. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10654. return
  10655. }
  10656. tx.SQL(` update fpdetail set ptuse = 0 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. }
  10663. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10664. if err != nil {
  10665. logs.Error(err)
  10666. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10667. return
  10668. }
  10669. if !exist {
  10670. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10671. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10672. if err != nil {
  10673. logs.Error(err)
  10674. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10675. return
  10676. }
  10677. }
  10678. var feedpargs []interface{}
  10679. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10680. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10681. if _, ok := dataexcel["ftname"]; ok {
  10682. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10683. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10684. // upFeedpSql += `,ftweight = ? `
  10685. // feedpargs = append(feedpargs, weight)
  10686. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10687. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10688. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10689. } else {
  10690. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10691. }
  10692. // if _, ok := dataexcel["ptsfname"]; ok {
  10693. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10694. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10695. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10696. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10697. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10698. // } else {
  10699. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10700. // }
  10701. upFeedpSql += " where barname = ? and pastureid = ? "
  10702. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10703. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10704. if err != nil {
  10705. logs.Error(err)
  10706. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10707. return
  10708. }
  10709. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10710. if err != nil {
  10711. logs.Error(err)
  10712. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10713. return
  10714. }
  10715. if !exist1 {
  10716. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10717. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10718. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10719. if err != nil {
  10720. logs.Error(err)
  10721. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10722. return
  10723. }
  10724. }
  10725. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10726. if err != nil {
  10727. logs.Error(err)
  10728. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10729. return
  10730. }
  10731. if !exist2 {
  10732. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,2,0,0,0,-1,-1) `,
  10733. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10734. if err != nil {
  10735. logs.Error(err)
  10736. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10737. return
  10738. }
  10739. }
  10740. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10741. if err != nil {
  10742. logs.Error(err)
  10743. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10744. return
  10745. }
  10746. if !exist3 {
  10747. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,3,0,0,0,-1,-1) `,
  10748. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10749. if err != nil {
  10750. logs.Error(err)
  10751. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10752. return
  10753. }
  10754. }
  10755. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10756. if err != nil {
  10757. logs.Error(err)
  10758. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10759. return
  10760. }
  10761. if !exist4 {
  10762. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,4,0,0,0,-1,-1) `,
  10763. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10764. if err != nil {
  10765. logs.Error(err)
  10766. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10767. return
  10768. }
  10769. }
  10770. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  10771. if err != nil {
  10772. logs.Error(err)
  10773. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10774. return
  10775. }
  10776. if !exist5 {
  10777. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
  10778. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10779. if err != nil {
  10780. logs.Error(err)
  10781. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10782. return
  10783. }
  10784. }
  10785. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  10786. if err != nil {
  10787. logs.Error(err)
  10788. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10789. return
  10790. }
  10791. if !exist6 {
  10792. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
  10793. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10794. if err != nil {
  10795. logs.Error(err)
  10796. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10797. return
  10798. }
  10799. }
  10800. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10801. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10802. and pastureid = ? and times = ?`
  10803. var fpdargs1 []interface{}
  10804. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10805. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10806. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10807. if err != nil {
  10808. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10809. return
  10810. }
  10811. var fpdargs2 []interface{}
  10812. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10813. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10814. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10815. if err != nil {
  10816. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10817. return
  10818. }
  10819. var fpdargs3 []interface{}
  10820. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10821. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10822. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10823. if err != nil {
  10824. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10825. return
  10826. }
  10827. var fpdargs4 []interface{}
  10828. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10829. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10830. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10831. if err != nil {
  10832. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10833. return
  10834. }
  10835. var fpdargs5 []interface{}
  10836. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10837. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10838. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10839. if err != nil {
  10840. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10841. return
  10842. }
  10843. var fpdargs6 []interface{}
  10844. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10845. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10846. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10847. if err != nil {
  10848. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10849. return
  10850. }
  10851. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10852. 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()
  10853. if err != nil {
  10854. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10855. return
  10856. }
  10857. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10858. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10859. upFpdetailList := make([]*upFpdetail, 0)
  10860. for _, newfpd := range newList {
  10861. for _, oldfpd := range oldFpdList {
  10862. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10863. var oldweight, newweight float64
  10864. if oldfpd["weight"] != nil {
  10865. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10866. }
  10867. if newfpd["weight"] != nil {
  10868. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10869. }
  10870. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10871. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10872. Old: oldweight,
  10873. New: newweight,
  10874. Times: newfpd["times"].(int64),
  10875. Ptid: newfpd["ptid"].(int64),
  10876. Fweight: fweight,
  10877. Id: oldfpd["id"].(int64),
  10878. })
  10879. break
  10880. }
  10881. }
  10882. }
  10883. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10884. }
  10885. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10886. }
  10887. func FtImportExcel(c *gin.Context) {
  10888. appG := app.Gin{C: c}
  10889. inputdata := ""
  10890. c.Request.ParseForm()
  10891. params := c.Request.Form
  10892. file, _, err := c.Request.FormFile("file")
  10893. if err != nil {
  10894. appG.Response(http.StatusOK, e.ERROR, err)
  10895. return
  10896. }
  10897. sqlnamestrs := params.Get("name")
  10898. sheetname := params.Get("sheetname")
  10899. pastureid := params.Get("pastureid")
  10900. //importParams := params.Get("importParams")
  10901. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10902. // 必输项参数 (字符串格式 "field1,field2,field3")
  10903. requiredParams := params.Get("requiredParams")
  10904. // 日期参数
  10905. dateParams := params.Get("dateParams")
  10906. // 数字参数
  10907. numParams := params.Get("numParams")
  10908. //将字符串分割开
  10909. dateParamslist := strings.Split(dateParams, ",")
  10910. requiredParamslist := strings.Split(requiredParams, ",")
  10911. numParamslist := strings.Split(numParams, ",")
  10912. queryData := make([]interface{}, 0)
  10913. sqlslist := strings.Split(sqlnamestrs, ",")
  10914. xlsx1, err := excelize.OpenReader(file)
  10915. if err != nil {
  10916. fmt.Println(err)
  10917. return
  10918. }
  10919. ok := 0
  10920. error := 0
  10921. isdone := true
  10922. rows := xlsx1.GetRows(sheetname)
  10923. // 限制10000条,多余的截取掉
  10924. if len(rows) > 10000 {
  10925. rows = rows[:10000]
  10926. }
  10927. tx := restful.Engine.NewSession()
  10928. ftNameList := make(map[string]interface{})
  10929. var ftNames []interface{}
  10930. for i, row := range rows {
  10931. if i > 0 {
  10932. entry := make(map[string]interface{})
  10933. outentry := make(map[string]interface{})
  10934. for j, colCell := range rows[0] {
  10935. for k, colCell1 := range row {
  10936. if j == k {
  10937. outentry[colCell] = colCell1
  10938. entry[colCell] = colCell1
  10939. }
  10940. }
  10941. }
  10942. inputdata = ""
  10943. a := ""
  10944. fmt.Println(outentry, entry)
  10945. //校验日期格式
  10946. for _, v := range dateParamslist {
  10947. if v == "" {
  10948. continue
  10949. }
  10950. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10951. dtime, err := TransfTime(d.(string))
  10952. if err != nil {
  10953. a = strings.Trim(v, " ")
  10954. break
  10955. }
  10956. outentry[strings.Trim(v, " ")] = dtime
  10957. }
  10958. }
  10959. if a != "" {
  10960. outentry["error_msg"] = a + " 格式错误"
  10961. error++
  10962. queryData = append(queryData, outentry)
  10963. continue
  10964. }
  10965. a = ""
  10966. //校验必填格式
  10967. for _, v := range requiredParamslist {
  10968. if v == "" {
  10969. continue
  10970. }
  10971. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  10972. a = strings.Trim(v, " ")
  10973. break
  10974. }
  10975. }
  10976. if a != "" {
  10977. outentry["error_msg"] = a + " 未填或格式错误"
  10978. error++
  10979. queryData = append(queryData, outentry)
  10980. continue
  10981. }
  10982. a = ""
  10983. //校验数字格式
  10984. for _, v := range numParamslist {
  10985. if v == "" {
  10986. continue
  10987. }
  10988. d, ok := outentry[strings.Trim(v, " ")]
  10989. if !ok || d == "" {
  10990. outentry[strings.Trim(v, " ")] = 0
  10991. } else {
  10992. var fl float64
  10993. switch d.(type) {
  10994. case string:
  10995. fl, err = strconv.ParseFloat(d.(string), 64)
  10996. }
  10997. if err != nil || fl < 0 {
  10998. a = strings.Trim(v, " ")
  10999. break
  11000. }
  11001. }
  11002. }
  11003. if a != "" {
  11004. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  11005. error++
  11006. queryData = append(queryData, outentry)
  11007. continue
  11008. }
  11009. err := tx.Begin()
  11010. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  11011. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  11012. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  11013. }
  11014. for _, sqlnamestr := range sqlslist {
  11015. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  11016. paramslist := strings.Split(paramslists, ",")
  11017. if len(paramslist) > 0 {
  11018. s_params := make([]interface{}, 0)
  11019. for _, value := range paramslist {
  11020. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  11021. if tempv, exists := c.Get("jwt_username"); exists {
  11022. s_params = append(s_params, tempv.(string))
  11023. } else {
  11024. s_params = append(s_params, "")
  11025. }
  11026. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  11027. s_params = append(s_params, pastureid)
  11028. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  11029. ids, err := setting.SnowIds.NextId()
  11030. if err != nil {
  11031. ids = time.Now().UnixNano()
  11032. logging.Info("create SnowIds err", err)
  11033. }
  11034. s_params = append(s_params, ids)
  11035. } else {
  11036. if outentry[strings.Trim(value, " ")] == nil {
  11037. s_params = append(s_params, "")
  11038. } else {
  11039. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  11040. }
  11041. }
  11042. }
  11043. outentry["input"] = inputdata
  11044. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  11045. if err != nil {
  11046. if tx != nil {
  11047. tx.Rollback()
  11048. }
  11049. if tx != nil {
  11050. tx.Close()
  11051. }
  11052. msg := geterrmsg(err.Error())
  11053. outentry["error_msg"] = msg
  11054. error++
  11055. queryData = append(queryData, outentry)
  11056. isdone = true
  11057. break
  11058. } else {
  11059. if len(returnmsgmap1) > 0 {
  11060. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  11061. if tx != nil {
  11062. tx.Rollback()
  11063. }
  11064. if tx != nil {
  11065. tx.Close()
  11066. }
  11067. msg := geterrmsg(va.(string))
  11068. outentry["error_msg"] = msg
  11069. error++
  11070. queryData = append(queryData, outentry)
  11071. isdone = true
  11072. break
  11073. }
  11074. }
  11075. isdone = false
  11076. }
  11077. }
  11078. }
  11079. ftNames = append(ftNames, outentry["配方名称"])
  11080. switch {
  11081. case err != nil:
  11082. if tx != nil {
  11083. tx.Rollback()
  11084. }
  11085. default:
  11086. if tx != nil {
  11087. err = tx.Commit()
  11088. }
  11089. }
  11090. if tx != nil {
  11091. tx.Close()
  11092. }
  11093. }
  11094. if !isdone {
  11095. ok++
  11096. isdone = true
  11097. }
  11098. }
  11099. go ftSync(ftNames, pastureid)
  11100. data := make(map[string]interface{})
  11101. data["result"] = queryData
  11102. data["success"] = ok
  11103. data["err_count"] = error
  11104. appG.Response(http.StatusOK, e.SUCCESS, data)
  11105. }
  11106. func ftSync(ftNameList []interface{}, pastureId string) {
  11107. tx := restful.Engine.NewSession()
  11108. defer tx.Close()
  11109. for _, ftName := range ftNameList {
  11110. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  11111. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  11112. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  11113. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  11114. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  11115. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  11116. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  11117. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  11118. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, ftName).QueryString()
  11119. FpdBatchEditGrfd(pastureId, values1)
  11120. }
  11121. }
  11122. func CopyFeedtemplet(c *gin.Context) {
  11123. appG := app.Gin{C: c}
  11124. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11125. fsion := gofasion.NewFasion(string(dataByte))
  11126. pastureid := fsion.Get("pastureid").ValueStr()
  11127. newName := fsion.Get("newName").ValueStr()
  11128. id := fsion.Get("id").ValueStr()
  11129. tx := restful.Engine.NewSession()
  11130. defer tx.Close()
  11131. count, err := tx.SQL(` select count(1) from feedtemplet where tname = ? `, newName).Count()
  11132. if err != nil {
  11133. appG.Response(http.StatusOK, e.ERROR, err)
  11134. return
  11135. }
  11136. if count > 0 {
  11137. appG.Response(http.StatusOK, e.ERROR, "配方名称重复!")
  11138. return
  11139. }
  11140. type ftCode struct {
  11141. Tcode string `xorm:"tcode"`
  11142. }
  11143. code := new(ftCode)
  11144. err = tx.SQL(`select if(left((select max(tcode) from feedtemplet where pastureid = ?),8) =
  11145. (select DATE_FORMAT(now(),"%Y%m%d")),(select max(tcode)+1 from feedtemplet where pastureid = ?),
  11146. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))) tcode`, pastureid, pastureid).GetFirst(code).Error
  11147. if err != nil {
  11148. appG.Response(http.StatusOK, e.ERROR, err)
  11149. return
  11150. }
  11151. if code.Tcode == "" {
  11152. appG.Response(http.StatusOK, e.ERROR, "配方编码生产失败!")
  11153. return
  11154. }
  11155. _, err = tx.Exec(`INSERT INTO feedtemplet(pastureid,tname,tcode,tcolor,ccid,ccname,fttype,fttypeid,source,
  11156. remark,enable,sort,volume,autozone)
  11157. select pastureid,?,?,tcolor,ccid,ccname,fttype,fttypeid,source,
  11158. remark,enable,sort,volume,autozone from feedtemplet where id = ? `, newName, code.Tcode, id)
  11159. if err != nil {
  11160. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11161. return
  11162. }
  11163. _, err = tx.Exec(`insert into ftdetail(pastureid,ftid,fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11164. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry)
  11165. select pastureid,(select id from feedtemplet where tcode = ? ),fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11166. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry
  11167. from ftdetail where ftid = ? `, code.Tcode, id)
  11168. if err != nil {
  11169. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11170. return
  11171. }
  11172. appG.Response(http.StatusOK, e.SUCCESS, true)
  11173. }
  11174. func Test(c *gin.Context) {
  11175. appG := app.Gin{C: c}
  11176. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11177. appG.Response(http.StatusOK, e.SUCCESS, string(dataByte))
  11178. }
  11179. func GetPlanDry(c *gin.Context) {
  11180. appG := app.Gin{C: c}
  11181. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11182. fsion := gofasion.NewFasion(string(dataByte))
  11183. date := fsion.Get("date").ValueStr()
  11184. tx := restful.Engine.NewSession()
  11185. defer tx.Close()
  11186. dataList, err := tx.SQL(`SELECT
  11187. t.feedtempletName,
  11188. ifnull(t.feedtempletPrice,0)feedtempletPrice,
  11189. ifnull(t.feedtempletWeight,0)feedtempletWeight,
  11190. ifnull(t.feedtempletDryWeight,0)feedtempletDryWeight,
  11191. t.tmrno,
  11192. t.bname,
  11193. t.barid,
  11194. t.dry,
  11195. t.actualweightminus,
  11196. t.mydate,
  11197. t.pasturename,
  11198. t.endDate,
  11199. t.startDate,
  11200. t.times,
  11201. -- 计算startDate和endDate的中间时间
  11202. ifnull(DATE_FORMAT(
  11203. DATE_ADD(
  11204. t.startDate,
  11205. INTERVAL TIMESTAMPDIFF(SECOND, t.startDate, t.endDate)/2 SECOND
  11206. ),
  11207. '%Y-%m-%d %H:%i:%s'
  11208. ),'') AS midTime
  11209. FROM (
  11210. SELECT
  11211. (SELECT sort FROM downloadedplan WHERE pid = d.pid AND mydate = d.mydate AND lpplantype IN (0,1)) tmrno,
  11212. b.bname,
  11213. b.id barid,
  11214. 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
  11215. JOIN downloadplandtl1 dd1 ON dd.id = dd1.pid
  11216. JOIN feednur fn ON fn.fid = dd1.fid
  11217. WHERE dd.pid = d.pid AND dd.mydate = d.mydate AND lpplantype IN (0,1,4))/100),2) dry,
  11218. 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,
  11219. DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate,
  11220. p.pasture_name pastureName,
  11221. DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endDate,
  11222. DATE_FORMAT(IFNULL(
  11223. (SELECT MAX(intime) FROM downloadplandtl2 d1
  11224. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d1.intime<d2.intime),
  11225. (SELECT MAX(intime) FROM downloadplandtl1_exec de
  11226. WHERE de.date=d2.date AND de.pastureid = d2.pastureid AND de.pid=d2.pid)
  11227. ), '%Y-%m-%d %H:%i:%s') startDate,
  11228. d.times ,
  11229. ( SELECT
  11230. round(SUM(
  11231. IF(ftd.preftid<>0,
  11232. ftd.fweight*IFNULL((SELECT SUM(ftd1.fweight*f1.dry/100)/SUM(ftd1.fweight) FROM ftdetaildate ftd1
  11233. JOIN feednur f1 ON f1.fid= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11234. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11235. ftd.fweight*f.dry/100)) ,2)
  11236. dryweight
  11237. FROM ftdetaildate ftd
  11238. LEFT JOIN feednur f ON f.fid= ftd.fid AND f.pastureid = ftd.pastureid
  11239. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletDryWeight,(
  11240. select
  11241. sum(ftd.fweight)
  11242. FROM ftdetaildate ftd
  11243. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletWeight,
  11244. ( SELECT
  11245. round(SUM(
  11246. IF(ftd.preftid<>0,
  11247. IFNULL((SELECT SUM(ftd1.fweight*f1.uprice) FROM ftdetaildate ftd1
  11248. JOIN feed f1 ON f1.id= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11249. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11250. ftd.fweight*f.uprice)) ,2)
  11251. dryweight
  11252. FROM ftdetaildate ftd
  11253. LEFT JOIN feed f ON f.id= ftd.fid AND f.pastureid = ftd.pastureid
  11254. WHERE ftd.ftid = d.tempid and ftd.date = d2.date )
  11255. feedtempletPrice,d.templetname feedtempletName
  11256. FROM downloadedplan d
  11257. JOIN downloadplandtl2 d2 ON d.id=d2.PID
  11258. JOIN bar b ON b.id = d2.fbarid
  11259. JOIN pasture p ON p.pastureid = d.pastureid
  11260. WHERE d.mydate = DATE_FORMAT(?,'%Y-%m-%d')
  11261. AND d2.type = 0
  11262. AND d.havebutton = 1
  11263. ) t
  11264. WHERE 1=1 `, date).QueryString()
  11265. if err != nil {
  11266. logs.Error(err)
  11267. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11268. return
  11269. }
  11270. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11271. }
  11272. func GetBar(c *gin.Context) {
  11273. appG := app.Gin{C: c}
  11274. tx := restful.Engine.NewSession()
  11275. defer tx.Close()
  11276. pastureinfo := new(udPastureInfo)
  11277. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  11278. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  11279. if err != nil {
  11280. logs.Error(err)
  11281. return
  11282. }
  11283. dataList, err := tx.SQL(` select id,bname from bar where pastureid = ?`, pastureinfo.Pastureid).QueryString()
  11284. if err != nil {
  11285. logs.Error(err)
  11286. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11287. return
  11288. }
  11289. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11290. }
  11291. func GetHomepage(c *gin.Context) {
  11292. appG := app.Gin{C: c}
  11293. tx := restful.Engine.NewSession()
  11294. defer tx.Close()
  11295. dataList, err := tx.SQL(` SELECT
  11296. ifnull((SELECT CONCAT(ROUND(if(SUM(lweight) <= SUM(iweight),SUM(lweight)/SUM(iweight),SUM(iweight)/SUM(lweight))*100,2),'%') yesRateHL
  11297. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11298. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) ),'0.00%')yesRateHL, -- 昨日混料准确率
  11299. (SELECT CONCAT(ROUND(SUM(iweight)/SUM(lweight)*100,2),'%') yesRateHL
  11300. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11301. 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日混料准确率
  11302. ifnull((SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11303. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11304. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) ),'0.00%')yesRateSL, -- 昨日撒料准确率
  11305. (SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11306. FROM downloadedplan dt 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') and dt.lpplantype in(0,2) )monRateSL, -- 进30日撒料准确率
  11308. 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),'%') -- 正确率
  11309. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11310. WHERE dt.pastureid = d.pastureid AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')),'0.00%') yesRateSLR, -- 昨日正确率
  11311. (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),'%') -- 正确率
  11312. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11313. WHERE dt.pastureid = d.pastureid
  11314. 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日正确率
  11315. (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,
  11316. (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,
  11317. 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,
  11318. 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,
  11319. ifnull(round(getSLtimeDiffSINGEL(d.pastureid,d.mydate),2),0.00) temtime,
  11320. ifnull(round(getSLtimeDiffMonth(d.pastureid) ,2),0.00) montime
  11321. FROM
  11322. (SELECT (select column_default as pastureid from information_schema.COLUMNS
  11323. 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()
  11324. if err != nil {
  11325. logs.Error(err)
  11326. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11327. return
  11328. }
  11329. dataList1, err := tx.SQL(`select
  11330. 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
  11331. LEFT JOIN ftdetail ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1'
  11332. join feed f on f.id = ifnull(ftd.fid,d1.fid) where d1.date = date_format(now(),'%Y-%m-%d') `).QueryString()
  11333. if err != nil {
  11334. logs.Error(err)
  11335. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11336. return
  11337. }
  11338. for _, data := range dataList {
  11339. for _, data1 := range dataList1 {
  11340. data["totalCost"] = data1["totalCost"]
  11341. data["cost"] = data1["cost"]
  11342. }
  11343. }
  11344. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11345. }
  11346. func GetFeedingManagement(c *gin.Context) {
  11347. appG := app.Gin{C: c}
  11348. typea := c.Query("typea") // 0 栏舍 1 日期
  11349. startDate := c.Query("startdate")
  11350. endDate := c.Query("enddate")
  11351. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11352. // fsion := gofasion.NewFasion(string(dataByte))
  11353. tx := restful.Engine.NewSession()
  11354. defer tx.Close()
  11355. if typea == "0" {
  11356. 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
  11357. SUM(
  11358. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11359. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11360. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11361. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11362. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11363. )
  11364. )actualweightminus ,
  11365. 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(fn.dry,0)
  11372. ) dryweight , SUM(
  11373. 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 ,
  11374. 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)*
  11375. 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 )),
  11376. 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)*
  11377. 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 ))
  11378. ) * ifnull(f.uprice,0)
  11379. ) priceweight
  11380. ,(select ccount from feedpdate where date = d1.date and barid = d2.fbarid) ccount,b.bname
  11381. FROM
  11382. downloadedplan d
  11383. JOIN downloadplandtl2 d2
  11384. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11385. JOIN downloadplandtl1 d1
  11386. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11387. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11388. 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
  11389. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11390. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11391. left join feednur fn on fn.fid = f.id
  11392. WHERE d.mydate BETWEEN ? AND ? GROUP BY d2.fbarid ) t `, startDate, endDate).QueryString()
  11393. if err != nil {
  11394. logs.Error(err)
  11395. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11396. return
  11397. }
  11398. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11399. } else {
  11400. 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
  11401. SUM(
  11402. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11403. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11404. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11405. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11406. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11407. )
  11408. )actualweightminus ,
  11409. 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(fn.dry,0)
  11416. ) dryweight , SUM(
  11417. 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 ,
  11418. 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)*
  11419. 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 )),
  11420. 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)*
  11421. 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 ))
  11422. ) * ifnull(f.uprice,0)
  11423. ) priceweight
  11424. ,(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
  11425. FROM
  11426. downloadedplan d
  11427. JOIN downloadplandtl2 d2
  11428. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11429. JOIN downloadplandtl1 d1
  11430. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11431. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11432. 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
  11433. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11434. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11435. left join feednur fn on fn.fid = f.id
  11436. WHERE d.mydate BETWEEN ? AND ?
  11437. GROUP BY d.mydate) t `, startDate, endDate).QueryString()
  11438. if err != nil {
  11439. logs.Error(err)
  11440. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11441. return
  11442. }
  11443. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11444. }
  11445. }
  11446. func GetFpdetailFname(c *gin.Context) {
  11447. appG := app.Gin{C: c}
  11448. // id := c.Query("id")
  11449. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11450. fsion := gofasion.NewFasion(string(dataByte))
  11451. id := fsion.Get("id").ValueDefaultStr("")
  11452. tx := restful.Engine.NewSession()
  11453. defer tx.Close()
  11454. fpdetailFnameList := make([]*models.FpdetailFname, 0)
  11455. err := tx.SQL(` SELECT
  11456. TRIM(ftid)ftid,TRIM(fid)fid,
  11457. IFNULL((SELECT fname FROM feed WHERE pastureid =ftdetail.pastureid AND id = ftdetail.fid),ftdetail. fname) fname,
  11458. fweight,sort,
  11459. TRIM(ftdetail.id) id, fweight /(select sum(fweight) from ftdetail where ftid = (select ftid from feedp where barid = ? ) ) sumFweight
  11460. FROM
  11461. ftdetail
  11462. WHERE ( ftid=(select ftid from feedp where barid = ? )) AND is_show = 1
  11463. ORDER BY ftdetail.sort,ftdetail.id `, id, id).Find(&fpdetailFnameList)
  11464. if err != nil {
  11465. logs.Error(err)
  11466. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11467. return
  11468. }
  11469. fpdetailList := make([]*models.Fpdetail, 0)
  11470. err = tx.SQL(`select id,barid,barname,times,weight from fpdetail where barid = ?`, id).Find(&fpdetailList)
  11471. if err != nil {
  11472. logs.Error(err)
  11473. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11474. return
  11475. }
  11476. for _, f := range fpdetailFnameList {
  11477. f.FWeight = 0
  11478. for _, fpd := range fpdetailList {
  11479. value := f.SumFWeight * fpd.Weight
  11480. // 将其四舍五入到小数点后两位
  11481. roundedValue := math.Round(value*100) / 100
  11482. if fpd.Times == 1 {
  11483. f.TimesOne = roundedValue
  11484. } else if fpd.Times == 2 {
  11485. f.TimesTwo = roundedValue
  11486. } else if fpd.Times == 3 {
  11487. f.TimesThree = roundedValue
  11488. } else if fpd.Times == 4 {
  11489. f.TimesFour = roundedValue
  11490. } else if fpd.Times == 5 {
  11491. f.TimesFive = roundedValue
  11492. } else if fpd.Times == 6 {
  11493. f.TimesSix = roundedValue
  11494. }
  11495. f.FWeight += value
  11496. }
  11497. }
  11498. fpdetailFname := new(models.FpdetailFname)
  11499. fpdetailFname.FName = "合计"
  11500. for _, f := range fpdetailFnameList {
  11501. fpdetailFname.TimesOne += f.TimesOne
  11502. fpdetailFname.TimesTwo += f.TimesTwo
  11503. fpdetailFname.TimesThree += f.TimesThree
  11504. fpdetailFname.TimesFour += f.TimesFour
  11505. fpdetailFname.TimesFive += f.TimesFive
  11506. fpdetailFname.TimesSix += f.TimesSix
  11507. fpdetailFname.FWeight += f.FWeight
  11508. f.FWeight = RoundFloat(f.FWeight, 2)
  11509. }
  11510. // 在处理代码中
  11511. fpdetailFname.TimesOne = RoundFloat(fpdetailFname.TimesOne, 2)
  11512. fpdetailFname.TimesTwo = RoundFloat(fpdetailFname.TimesTwo, 2)
  11513. fpdetailFname.TimesThree = RoundFloat(fpdetailFname.TimesThree, 2)
  11514. fpdetailFname.TimesFour = RoundFloat(fpdetailFname.TimesFour, 2)
  11515. fpdetailFname.TimesFive = RoundFloat(fpdetailFname.TimesFive, 2)
  11516. fpdetailFname.TimesSix = RoundFloat(fpdetailFname.TimesSix, 2)
  11517. fpdetailFname.FWeight = RoundFloat(fpdetailFname.FWeight, 2)
  11518. fpdetailFnameList = append(fpdetailFnameList, fpdetailFname)
  11519. appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11520. }
  11521. func RoundFloat(x float64, prec int) float64 {
  11522. output := math.Pow(10, float64(prec))
  11523. return math.Round(x*output) / output
  11524. }
  11525. func GetLyUdData(c *gin.Context) {
  11526. appG := app.Gin{C: c}
  11527. // id := c.Query("id")
  11528. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11529. fsion := gofasion.NewFasion(string(dataByte))
  11530. myDate := fsion.Get("myDate").ValueDefaultStr("")
  11531. times := fsion.Get("Times").ValueDefaultStr("")
  11532. name := fsion.Get("name").ValueDefaultStr("")
  11533. tx := restful.Engine.NewSession()
  11534. defer tx.Close()
  11535. if name == "dateplanlist" {
  11536. 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
  11537. join pasture p on dl.pastureId=p.pastureid JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId
  11538. where dl.Mydate = ? AND dl.lpplanType =0 and dl.Times= ? GROUP BY dl.id union all
  11539. 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
  11540. from downloadedplan dl join pasture p on dl.pastureId=p.pastureid
  11541. 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
  11542. where dl.Mydate = ? AND dl.lpplanType =2 and dl.Times= ?
  11543. GROUP BY dl.id order by ProjName `, myDate, times, myDate, times).Query().List()
  11544. fmt.Println(err)
  11545. appG.Response(http.StatusOK, e.SUCCESS, data)
  11546. return
  11547. } else if name == "getAddFeed" {
  11548. 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,
  11549. 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,
  11550. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM downloadedplan dd
  11551. JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11552. 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
  11553. join feedtemplet ftd on ftd.id = d.tempid and ftd.pastureId = d.pastureId
  11554. JOIN feed f ON f.id = d1.fid AND f.pastureId = d.pastureId
  11555. WHERE DATE_FORMAT(dd.Mydate ,'%Y-%m-%d' ) = ? and dd.Times =? and d1.type = 0
  11556. 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,
  11557. round(d1.LWEIGHT *(ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and ftid = ftdd.ftid and pastureId = d.pastureId )),2) expWeight,
  11558. 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,
  11559. '' 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,
  11560. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM
  11561. downloadedplan dd JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11562. 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
  11563. join feedtemplet ftd on ftd.id = d1.fid and ftd.pastureId = d.pastureId
  11564. join ftdetaildate ftdd on ftdd.ftid = ftd.id and ftdd.date = d.Mydate and ftdd.pastureId = d.pastureId
  11565. join feed f on f.id = ftdd.fid and f.pastureId = d.pastureId
  11566. 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()
  11567. appG.Response(http.StatusOK, e.SUCCESS, data)
  11568. return
  11569. } else if name == "getDeleteFeed" {
  11570. 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,
  11571. 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 ,
  11572. (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
  11573. ,d2.xxwBarCode as penId,if(d.lpplanType=2,(select id from downloadedplan p where p.pid=d.pid and p.mydate=? and p.Times=?
  11574. and p.lpplanType=1 limit 1),d2.pid) Id from downloadedplan d LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID
  11575. and d.pastureId=d2.pastureId where d.mydate=? AND d.lpplanType in (0,2) and d.Times=?`, myDate, times, myDate, times).Query().List()
  11576. appG.Response(http.StatusOK, e.SUCCESS, data)
  11577. return
  11578. }
  11579. // appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11580. }