1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878 |
- package api
- import (
- "bytes"
- "database/sql"
- "encoding/json"
- "errors"
- "fmt"
- "io/ioutil"
- "net/http"
- "os"
- "path"
- "regexp"
- "sort"
- "strconv"
- "strings"
- "sync"
- "time"
- "tmr-watch/conf/setting"
- "tmr-watch/http/handle/gm"
- "tmr-watch/http/handle/restful"
- "tmr-watch/module"
- "tmr-watch/pkg/app"
- "tmr-watch/pkg/e"
- "tmr-watch/pkg/logging"
- "github.com/360EntSecGroup-Skylar/excelize"
- "github.com/Anderson-Lu/gofasion/gofasion"
- "github.com/astaxie/beego/logs"
- "github.com/gin-gonic/gin"
- "github.com/qichengzx/coordtransform"
- "github.com/tealeg/xlsx"
- "github.com/xormplus/xorm"
- )
- // @Summary 根据SQL执行得到数据集
- // @Tags getData
- // @Accept json
- // @Produce json
- // @Param sql query string true "sql"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/getdata [POST]
- func GetData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlstr := fsion.Get("sql").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- func Testpartitions(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
- user := fsion.Get("user").ValueStr() //获取新数据库用户
- passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
- host := fsion.Get("host").ValueStr() //获取新数据库名称
- port := fsion.Get("port").ValueStr() //获取新数据库名称
- sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
- if sqls == nil || err1 != nil {
- appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
- }
- sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
- connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
- mydb, err := sql.Open("mysql", connecting) //连接新连接
- if err != nil {
- println("err1", err.Error())
- }
- _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
- if err != nil {
- println("err2", err.Error())
- }
- mydb.Close()
- connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
- mydb, err = sql.Open("mysql", connecting)
- if err != nil {
- println("err3", err.Error())
- }
- defer mydb.Close()
- if err == nil {
- mydb.SetMaxOpenConns(10)
- mydb.SetMaxIdleConns(10)
- }
- errmsg := ""
- if err == nil {
- //tx ,_ :=mydb.Begin()
- for _, sqlstr := range sqlstrs {
- //println("sqlstr---",sqlstr)
- if sqlstr == "" {
- continue
- }
- _, err = mydb.Exec(sqlstr)
- if err != nil {
- println("err4", err.Error())
- errmsg = err.Error()
- //err1 :=tx.Rollback()
- }
- }
- //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
- //err =tx.Commit()
- }
- if errmsg == "" {
- appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
- }
- }
- func TestData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlstr := fsion.Get("sql").ValueStr()
- token := ""
- if tempv, exists := c.Get("jwt_username"); exists {
- token = tempv.(string)
- }
- appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByName
- // @Accept json
- // @Produce json
- // @Param sqlname body string true "sqlname"
- // @Param offset body int true "offset"
- // @Param pagecount body int true "pagecount"
- // @Param returntype body string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByName [POST]
- func GetDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
- // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
- // tmrNameList := []string{}
- // for _, tmr := range tmrArray {
- // tmrNameList = append(tmrNameList, tmr.ValueStr())
- // }
- // s_params = append(s_params, strings.Join(tmrNameList, ","))
- // } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- if sqlnamestr == "getHomepageStr" {
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- var montimeList []float64
- var montime float64
- var wg sync.WaitGroup
- now := time.Now()
- for i := 0; i < 30; i++ {
- wg.Add(1)
- nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
- go func(nowstr string) {
- defer wg.Done()
- sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
- slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
- m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
- montimeList = append(montimeList, m)
- }(nowstr)
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- wg.Wait()
- for _, m := range montimeList {
- montime += m
- }
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- return
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByName
- // @Accept json
- // @Produce json
- // @Param sqlname body string true "sqlname"
- // @Param offset body int true "offset"
- // @Param pagecount body int true "pagecount"
- // @Param returntype body string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByName [POST]
- func GetDataBySqlIN(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // 错误处理
- // 将报错信息处理成汉字
- func geterrmsg(errstr string) (msgstr string) {
- var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
- rs := []rune(errstr)
- if hzRegexp.MatchString(string(rs[0])) {
- msgstr = errstr
- return
- }
- if strings.Contains(errstr, "Duplicate entry") {
- strs := strings.Split(errstr, ` key '`)
- if len(strs) > 1 {
- if len(strs[len(strs)-1]) > 1 {
- errstr = "Duplicate entry :" + strs[len(strs)-1]
- }
- }
- }
- msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
- if err != nil {
- msgstr = errstr
- return
- }
- if msg == nil || len(msg) == 0 {
- var param []interface{}
- param = append(param, errstr, errstr)
- go func() {
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
- if err != nil {
- logging.Error("insert into err_msg(err,msg) err", err)
- }
- }()
- msgstr = errstr
- } else {
- msgstr = msg[0]["msg"]
- }
- return
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname body json true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Param s formData json true "ss"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByNameForm [POST]
- func GetDataByNameForm(c *gin.Context) {
- appG := app.Gin{C: c}
- //sqlnamestr := c.PostForm("measureNumber")
- //dataByte, _ := ioutil.ReadAll(c.Request.Body)
- //fsion := gofasion.NewFasion(string(dataByte))
- //sqlnamestr := fsion.Get("name").ValueStr()
- //offset := fsion.Get("offset").ValueInt()
- //pagecount := fsion.Get("pagecount").ValueInt()
- //returntype := fsion.Get("returntype").ValueStr()
- //params := fsion.Get("params").Array()
- c.Request.ParseForm()
- params := c.Request.Form
- offset := 0
- pageSize_ := 0
- returntype := params.Get("page")
- if returntype == "" {
- returntype = "0"
- }
- if tempv, exists := c.Get("jwt_username"); exists {
- params.Set("JwtUserName", tempv.(string))
- } else {
- params.Set("JwtUserName", "")
- }
- sqlnamestr := params.Get("name")
- logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
- s_params := make([]interface{}, 0)
- if returntype == "1" {
- pageNum, error := strconv.Atoi(params.Get("pageNum"))
- if error != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
- }
- pageSize, error := strconv.Atoi(params.Get("pageSize"))
- if error != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
- }
- pageSize_ = pageSize
- offset = pageNum
- }
- sql, p := restful.GetSqlByNameDB(sqlnamestr)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, params.Get(strings.Trim(value, " ")))
- }
- }
- if sql != "" {
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- c.Header("Content-Type", "application/octet-stream")
- c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
- if err != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
- }
- }
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
- }
- }
- // @Summary 递归获取所有
- // @Tags menu
- // @Accept json
- // @Produce json
- // @Param Ton query string true "Ton"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Router /authdata/GetRoleMenus [GET]
- func GetRecuDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- parentidname := fsion.Get("idname").ValueStr()
- sql, p := restful.GetSqlByNameDB(sqlnamestr)
- params := make(map[string]interface{})
- s_params := make([]interface{}, 0)
- if fsion.HasKey("params") {
- for _, v_params := range fsion.Get("params").Array() {
- s_params = append(s_params, v_params.ValueStr())
- }
- params["params"] = s_params
- } else {
- jparams := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- params[value] = tempv.(string)
- } else {
- params[value] = ""
- }
- } else {
- params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
- }
- }
- }
- }
- queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
- logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByNames
- // @Accept json
- // @Produce json
- // @RequestBody sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByNames [POST]
- func GetDataByNames(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlParams := fsion.Array()
- queryData := make(map[string]interface{})
- for _, v := range sqlParams {
- fsion2 := gofasion.NewFasion(v.Json())
- logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
- sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
- if sql == "" {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = "sql没找到"
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- } else if sql != "" {
- offset := fsion2.Get("offset").ValueInt()
- pagecount := fsion2.Get("pagecount").ValueInt()
- returntype := fsion2.Get("returntype").ValueStr()
- s_params := make([]interface{}, 0)
- if fsion2.HasKey("parammaps") {
- parammaps := fsion2.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion2.HasKey("params") {
- params := fsion2.Get("params").Array()
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
- if err != nil {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = err.Error()
- queryData[fsion2.Get("name").ValueStr()] = errorm
- logging.Error("GetDataByNames err: ", err)
- continue
- } else {
- queryData[fsion2.Get("name").ValueStr()] = queryData1
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByNameForm [POST]
- func PostDataByNameForm(c *gin.Context) {
- appG := app.Gin{C: c}
- c.Request.ParseForm()
- params := c.Request.Form
- sqlnamestr := params.Get("name")
- logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
- s_params := make([]interface{}, 0)
- sql, p := restful.GetSqlByNameDB(sqlnamestr)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 {
- for _, value := range paramslist {
- s_params = append(s_params, params.Get(strings.Trim(value, " ")))
- }
- }
- if sql != "" {
- queryData, err := execDataBySql(sql, s_params)
- if err != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
- }
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
- }
- }
- // GetReportform 将数据集转换格式
- // @Tags PostDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- func GetReportform(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- checked := fsion.Get("checked").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- parammaps := fsion.Get("parammaps")
- typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
- mode := parammaps.Get("mode").ValueDefaultInt(0)
- logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- // GetUpkeepPlan 保养计划
- func GetUpkeepPlan(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- if v, ok := value["id"]; ok {
- //month = "2020-03"
- seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
- if seviceplans != nil {
- for _, va := range seviceplans { //根据保养计划获取保养单
- //day,_ :=strconv.Atoi(va["day"])
- bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
- //buk := make(map[string]map[string]string)
- for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
- jstr := ""
- if bu["plantime"][8:9] == "0" {
- jstr = "m" + bu["plantime"][9:]
- } else {
- jstr = "m" + bu["plantime"][8:]
- }
- if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
- } else {
- if bu["flowCompeleted"] >= "2" {
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
- } else {
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
- }
- }
- }
- }
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
- // todo 优化性能 children统一查询
- // @Tags PostDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- func GetArrList(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func GetAccount(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // PostDataByName 根据APISQL表中SQL执行得到数据集
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func PostDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- var err error
- queryData, err := module.PostDataByName(c, fsion)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- var (
- keyWord string
- )
- switch fsion.Get("name").ValueStr() {
- case "insertFeedclass":
- keyWord = "feed"
- err = module.GroupCategorySync(keyWord, fsion)
- case "deleteFeedclass":
- keyWord = "feed_delete"
- err = module.GroupCategoryDelete(keyWord, fsion)
- case "insertCowclass":
- keyWord = "cow"
- err = module.GroupCategorySync(keyWord, fsion)
- case "deleteCowclass":
- keyWord = "cow_delete"
- err = module.GroupCategoryDelete(keyWord, fsion)
- default:
- }
- if err != nil {
- logging.Error(keyWord, err)
- }
- if queryData != nil {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- //人脸识别/格润富德接口
- func GetRJSBData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("plancount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- }
- var wg sync.WaitGroup
- for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- wg.Add(1)
- go func(value map[string]interface{}) {
- defer wg.Done()
- _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
- }(value)
- }
- wg.Wait()
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func PostRJSBData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- logging.Info("PostRJSBData err: ", string(dataByte))
- s_params := make([]interface{}, 0)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
- if !fsion.HasKey("parammaps") {
- appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- return
- }
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- appG.Response(http.StatusOK, e.SUCCESS, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- // if value == "ID" {
- // id := parammaps.Get("ID").ValueStr()
- // pastureid := parammaps.Get("pastureid").ValueStr()
- // 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
- // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- // for _, item := range datalist {
- // id = item["id"]
- // }
- // s_params = append(s_params, id)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- if value == "ID" {
- id := parammaps.Get("ID").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- 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
- d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- for _, item := range datalist {
- id = item["id"]
- }
- s_params = append(s_params, id)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func PostRJSBDatas(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte)).Array()
- logging.Info("PostRJSBDatas err: ", string(dataByte))
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
- for _, fsion := range fsions {
- if !fsion.HasKey("parammaps") {
- appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- return
- }
- parammaps := fsion.Get("parammaps")
- ID := parammaps.Get("ID").ValueStr()
- if ID == "" {
- continue
- }
- s_params := make([]interface{}, 0)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- appG.Response(http.StatusOK, e.SUCCESS, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- // if value == "ID" {
- // id := parammaps.Get("ID").ValueStr()
- // pastureid := parammaps.Get("pastureid").ValueStr()
- // 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
- // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- // for _, item := range datalist {
- // id = item["id"]
- // }
- // s_params = append(s_params, id)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- if value == "ID" {
- id := parammaps.Get("ID").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- 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
- d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- for _, item := range datalist {
- id = item["id"]
- }
- s_params = append(s_params, id)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags ExecDataByConfig
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func ExecDataByConfig(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- tempval_ := make(map[string]interface{})
- tempCommon := make(map[string]interface{})
- tempval := make([]map[string]interface{}, 0)
- err := json.Unmarshal(dataByte, &tempval_)
- logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- if err != nil {
- } else {
- if v, ok := tempval_["common"].(map[string]interface{}); ok {
- tempCommon = v
- }
- if v, ok := tempval_["data"].([]interface{}); ok {
- for _, Tvalue := range v {
- if v1, ok := Tvalue.(map[string]interface{}); ok {
- tempval = append(tempval, v1)
- }
- }
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- if err != nil {
- logging.Error("tx.Begin 事务启动失败__error:", err)
- }
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- if err == nil {
- if tempv, exists := c.Get("jwt_username"); exists {
- tempCommon["jwt_username"] = tempv.(string)
- }
- for _, paramvalue := range tempval {
- fmt.Println(paramvalue["name"])
- if paramvalue["name"].(string) == "updateBigFP" {
- err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- }
- }
- for _, paramvalue := range tempval {
- if _, ok := paramvalue["resultname"]; !ok {
- paramvalue["resultname"] = paramvalue["name"]
- }
- _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
- if err != nil {
- logging.Error("ExecDataParam error:", err)
- break
- }
- if paramvalue["name"].(string) == "createdownloadedplan" {
- checkPlan(tx, paramvalue, tempCommon, tempval, 0)
- }
- }
- if err == nil {
- if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
- appG.Response(http.StatusOK, e.SUCCESS, tempval)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
- }
- } else {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- }
- }
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- }
- func interfacetostring(val interface{}) string {
- switch val.(type) {
- case string:
- ss := val.(string)
- return ss
- break
- case int:
- ss := val.(int)
- return strconv.Itoa(ss)
- break
- case int64:
- ss := val.(int64)
- return strconv.FormatInt(ss, 10)
- break
- case float64:
- ss := val.(float64)
- return strconv.FormatFloat(ss, 'E', -1, 32)
- break
- }
- return ""
- }
- func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
- if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if tempstrb > -1 && tempstre > -1 {
- for _, ParamMapList := range ParamMap {
- if v, ok := ParamMapList["resultname"]; ok {
- if v == valuestring[tempstrb+1:tempstre] {
- if v1, ok := ParamMapList["resultmaps"]; ok {
- if newA, ok := v1.([]map[string]interface{}); ok {
- return interfacetostring(newA[0][valuestring[tempstre+1:]])
- } else if newA, ok := v1.(map[string]interface{}); ok {
- return interfacetostring(newA[valuestring[tempstre+1:]])
- }
- }
- }
- }
- }
- } else {
- return valuestring
- }
- } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
- return strconv.FormatInt(int64(valuestring), 10)
- }
- return ""
- }
- func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
- if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if tempstrb > -1 && tempstre > -1 {
- if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
- if s, ok := v.(string); ok {
- return s
- } else if s, ok := v.(float64); ok {
- return strconv.FormatFloat(s, 'f', -1, 64)
- // return strconv.FormatInt(int64(s), 10)
- }
- }
- }
- }
- return ""
- }
- 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) {
- sqlname := fasion["name"].(string)
- sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
- if v, ok := fasion["type"]; ok {
- sqltype = v.(string)
- }
- sql := ""
- p := ""
- s_params := make([]interface{}, 0)
- if sqltype != "" {
- sql, p = restful.GetSqlByName(sqlname, tx)
- //sqlApi, _ := models.GetApisqlByName(sqlname)
- if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- ss := ""
- if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if ss == "" && CommonParamMap != nil {
- if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
- ss = valuestring
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
- if CommonParamMap[valuestring[tempstre+1:]] != nil {
- ss = CommonParamMap[valuestring[tempstre+1:]].(string)
- }
- } else {
- if sqlname != "checkPassword" && sqlname != "updatePwd" {
- ss = ""
- }
- }
- }
- }
- if ss == "" && ParentParamMap != nil {
- ss = getParamValue_(v, value, ParentParamMap)
- }
- if ss == "" && sameParamMap != nil {
- ss = getParamValue(v, value, sameParamMap)
- }
- if ss == "" && ParamMap != nil {
- ss = getParamValue(v, value, ParamMap)
- }
- s_params = append(s_params, ss)
- }
- }
- }
- }
- }
- if sql == "" {
- sqltype = ""
- }
- if sqltype == "s1" {
- tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
- if v, ok := tempValParam.(map[string]interface{}); ok {
- fasion["resultmaps"] = v["list"].([]map[string]interface{})
- }
- if err != nil {
- return nil, err
- }
- err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
- } else if sqltype == "sm" {
- tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
- if v, ok := tempValParam.(map[string]interface{}); ok {
- fasion["resultmaps"] = v["list"].([]map[string]interface{})
- } else {
- }
- if err != nil {
- return nil, err
- }
- err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
- } else if sqltype == "v" {
- tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
- if v, ok := tempValParam.(map[string]interface{}); ok {
- fasion["resultmaps"] = v["list"].([]map[string]interface{})
- } else {
- }
- if err != nil {
- return nil, err
- }
- if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
- return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
- }
- } else if sqltype == "e" {
- tempVal_arrary := make([]map[string]interface{}, 0)
- tempVal_map := make(map[string]interface{})
- tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
- if err == nil {
- fasion["resultmaps"] = tempValParam.(map[string]interface{})
- tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
- tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
- tempVal_arrary = append(tempVal_arrary, tempVal_map)
- return tempVal_arrary, err
- }
- return nil, err
- } else {
- if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
- err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return nil, err
- }
- }
- return nil, nil
- }
- func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
- var err error
- subarray, ok := fasion["children"]
- if ok {
- for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
- tempVal_arrary := make([]map[string]interface{}, 0)
- for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
- tempVal_ := make(map[string]interface{})
- if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
- } else {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
- }
- tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
- if err != nil {
- return err
- }
- tempVal_arrary = append(tempVal_arrary, tempVal_)
- }
- v.(map[string]interface{})["children"] = tempVal_arrary
- }
- }
- return nil
- }
- // @Summary 删除图片
- // @Tags RemovePicByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func RemovePicByName(c *gin.Context) {
- logging.Info("RemovePicByName ", c.Keys)
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- picname := fsion.Get("picname").ValueStr()
- sql, _ := restful.GetSqlByNameDB(sqlnamestr)
- params := fsion.Get("params").Array()
- s_params := make([]interface{}, 0)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- if sql != "" {
- queryData, err := execDataBySql(sql, s_params)
- if picname != "" {
- // Destination
- distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
- err := os.Remove(distPath) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!")
- //输出错误详细信息
- fmt.Printf("%s", err)
- } else {
- //如果删除成功则输出 file remove OK!
- fmt.Print("file remove OK!")
- }
- distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
- err = os.Remove(distPath) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!")
- //输出错误详细信息
- fmt.Printf("%s", err)
- } else {
- //如果删除成功则输出 file remove OK!
- fmt.Print("file remove OK!")
- }
- }
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // @Summary 删除文件
- // @Tags RemoveFileByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func RemoveFileByName(c *gin.Context) {
- appG := app.Gin{C: c}
- id := c.Param("id")
- logging.Info("DownloadFile ", c.Keys, id)
- eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
- if eqdoc == nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
- err = os.Remove(distPath) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!")
- //输出错误详细信息
- fmt.Printf("%s", err)
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
- appG.Response(http.StatusOK, e.SUCCESS, "OK")
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDataByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func UpdateDataRelation(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- tablename := fsion.Get("name").ValueStr()
- dataname := fsion.Get("dataname").ValueStr()
- datavalue := fsion.Get("datavalue").ValueStr()
- valuename := fsion.Get("valuename").ValueStr()
- logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
- values := fsion.Get("values").Array()
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
- " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
- d_params := make([]interface{}, 4)
- d_params[0] = datavalue
- s_params := ""
- for _, v_values := range values {
- d_params[1] = v_values.ValueStr()
- if s_params == "" {
- s_params = v_values.ValueStr()
- } else {
- s_params = s_params + "," + v_values.ValueStr()
- }
- d_params[2] = d_params[1]
- d_params[3] = d_params[0]
- _, err := execDataBySqlT(insertSqlstr, d_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- break
- }
- }
- if s_params != "" {
- deleteSqlstr := "delete from " + tablename + " " +
- " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
- queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else if err == nil {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- deleteSqlstr := "delete from " + tablename + " " +
- " where " + dataname + " = " + datavalue
- queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else if err == nil {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDatasByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDatasByName [POST]
- func PostDataByNames(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlParams := fsion.Get("array").Array()
- queryData := make(map[string]interface{})
- for _, v := range sqlParams {
- fsion2 := gofasion.NewFasion(v.Json())
- ss := fsion2.Get("name")
- aa := fsion2.Get("params")
- fmt.Println(ss, aa)
- logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
- sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
- if sql == "" {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = "sql没有找到"
- errorm["param"] = ""
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- } else if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion2.HasKey("parammaps") {
- parammaps := fsion2.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion2.HasKey("params") {
- params := fsion2.Get("params").Array()
- //ids,err := setting.SnowIds.NextId()
- //if err !=nil{
- // ids = time.Now().UnixNano()
- // logging.Info("create SnowIds err",err)
- //}
- //s_params = append(s_params, ids)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- _, err := execDataBySql(sql, s_params)
- if err != nil {
- logging.Error("PostDataByName err: ", err)
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = err.Error()
- errorm["param"] = s_params
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- } else {
- errorm := make(map[string]interface{})
- errorm["code"] = e.SUCCESS
- errorm["message"] = "success"
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- }
- } else {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = "NO SQL"
- errorm["param"] = ""
- queryData[fsion2.Get("name").ValueStr()] = errorm
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
- if offset > 0 {
- offset = offset - 1
- }
- //if pagecount == 0 {
- // pagecount = setting.AppSetting.PageSize
- //}else if pagecount>setting.AppSetting.PageSize{
- // pagecount = setting.AppSetting.PageSize
- //}
- if returntype == "list" {
- queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
- return queryData, err
- } else if returntype == "listlist" {
- queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
- return queryData, err
- } else {
- queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
- return queryData, err
- }
- }
- func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
- if offset > 0 {
- offset = offset - 1
- }
- //if pagecount == 0 {
- // pagecount = setting.AppSetting.PageSize
- //}else if pagecount>setting.AppSetting.PageSize{
- // pagecount = setting.AppSetting.PageSize
- //}
- if returntype == "list" {
- queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
- return queryData, err
- } else if returntype == "listlist" {
- queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
- return queryData, err
- } else {
- fmt.Println(params)
- queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
- return queryData, err
- }
- }
- func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
- paramslist := strings.Split(Params, ",")
- s_params := make([]interface{}, 0)
- if isList {
- for _, v_params := range thisParams["params"].([]interface{}) {
- s_params = append(s_params, v_params)
- }
- } else {
- paramslist := strings.Split(Params, ",")
- if len(paramslist) > 0 && Params != "" {
- for _, value := range paramslist {
- s_params = append(s_params, thisParams[strings.Trim(value, " ")])
- }
- }
- }
- queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
- for _, queryData_ := range queryData {
- if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
- if isList {
- if queryData_[idname] != nil {
- thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
- }
- } else {
- if queryData_[idname] != nil {
- thisParams[idname] = queryData_[idname].(interface{})
- }
- if len(paramslist) > 0 && Params != "" {
- s_params = make([]interface{}, 0)
- for _, value := range paramslist {
- s_params = append(s_params, thisParams[strings.Trim(value, " ")])
- }
- }
- }
- queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
- } else {
- }
- }
- return queryData, err
- }
- func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
- queryData, err := restful.ExecQuery(sqlstr, params)
- return queryData, err
- }
- func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
- queryData, err := restful.ExecQueryT(sqlstr, params, tx)
- return queryData, err
- }
- func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
- queryData, err := restful.ExecQuery(sqlstr, params)
- return queryData, err
- }
- // @Summary 导入excel文件到数据库,excel第一行作为参数
- // @Tags ImportExcel
- // @Accept json
- // @Produce json
- // @Param file query string true "文件名"
- // @Param name header string true "执行sql的名字"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/ImportExcel [POST]
- func ImportExcel(c *gin.Context) {
- appG := app.Gin{C: c}
- inputdata := ""
- c.Request.ParseForm()
- params := c.Request.Form
- file, _, err := c.Request.FormFile("file")
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- sqlnamestrs := params.Get("name")
- sheetname := params.Get("sheetname")
- pastureid := params.Get("pastureid")
- //importParams := params.Get("importParams")
- logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
- // 必输项参数 (字符串格式 "field1,field2,field3")
- requiredParams := params.Get("requiredParams")
- // 日期参数
- dateParams := params.Get("dateParams")
- // 数字参数
- numParams := params.Get("numParams")
- //将字符串分割开
- dateParamslist := strings.Split(dateParams, ",")
- requiredParamslist := strings.Split(requiredParams, ",")
- numParamslist := strings.Split(numParams, ",")
- queryData := make([]interface{}, 0)
- sqlslist := strings.Split(sqlnamestrs, ",")
- xlsx1, err := excelize.OpenReader(file)
- if err != nil {
- fmt.Println(err)
- return
- }
- ok := 0
- error := 0
- isdone := true
- rows := xlsx1.GetRows(sheetname)
- // 限制10000条,多余的截取掉
- if len(rows) > 10000 {
- rows = rows[:10000]
- }
- for i, row := range rows {
- if i > 0 {
- entry := make(map[string]interface{})
- outentry := make(map[string]interface{})
- for j, colCell := range rows[0] {
- for k, colCell1 := range row {
- if j == k {
- outentry[colCell] = colCell1
- entry[colCell] = colCell1
- }
- }
- }
- inputdata = ""
- a := ""
- fmt.Println(outentry, entry)
- //校验日期格式
- for _, v := range dateParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; ok {
- dtime, err := TransfTime(d.(string))
- if err != nil {
- a = strings.Trim(v, " ")
- break
- }
- outentry[strings.Trim(v, " ")] = dtime
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验必填格式
- for _, v := range requiredParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
- a = strings.Trim(v, " ")
- break
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 未填或格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验数字格式
- for _, v := range numParamslist {
- if v == "" {
- continue
- }
- d, ok := outentry[strings.Trim(v, " ")]
- if !ok || d == "" {
- outentry[strings.Trim(v, " ")] = 0
- } else {
- var fl float64
- switch d.(type) {
- case string:
- fl, err = strconv.ParseFloat(d.(string), 64)
- }
- if err != nil || fl < 0 {
- a = strings.Trim(v, " ")
- break
- }
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 为数值类型且不可为负数"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- for _, sqlnamestr := range sqlslist {
- sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
- paramslist := strings.Split(paramslists, ",")
- if len(paramslist) > 0 {
- s_params := make([]interface{}, 0)
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
- s_params = append(s_params, pastureid)
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if outentry[strings.Trim(value, " ")] == nil {
- s_params = append(s_params, "")
- } else {
- s_params = append(s_params, outentry[strings.Trim(value, " ")])
- }
- }
- }
- outentry["input"] = inputdata
- fmt.Println(sql, s_params)
- returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
- if err != nil {
- if tx != nil {
- tx.Rollback()
- }
- if tx != nil {
- tx.Close()
- }
- msg := geterrmsg(err.Error())
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- } else {
- if len(returnmsgmap1) > 0 {
- if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
- if tx != nil {
- tx.Rollback()
- }
- if tx != nil {
- tx.Close()
- }
- msg := geterrmsg(va.(string))
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- }
- }
- isdone = false
- }
- }
- }
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }
- if !isdone {
- ok++
- isdone = true
- }
- }
- data := make(map[string]interface{})
- data["result"] = queryData
- data["success"] = ok
- data["err_count"] = error
- appG.Response(http.StatusOK, e.SUCCESS, data)
- }
- func TransfTime(timestr string) (string, error) {
- if timestr == "" {
- return time.Now().Format("2006-01-02"), nil
- }
- days, err := strconv.Atoi(timestr)
- if err != nil {
- if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
- return "20" + timestr[6:] + "-" + timestr[:5], nil
- }
- _, err := time.Parse("2006-01-02", timestr)
- if err != nil {
- t, err := time.Parse("2006/01/02", timestr)
- if err != nil {
- t, err := time.Parse("2006.01.02", timestr)
- if err != nil {
- return "", err
- } else {
- return t.Format("2006-01-02"), nil
- }
- } else {
- return t.Format("2006-01-02"), nil
- }
- } else {
- return timestr, nil
- }
- }
- times, _ := time.Parse("2006-01-02", "1899-12-30")
- times = times.AddDate(0, 0, days)
- return times.Format("2006-01-02"), nil
- }
- func Createchart(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- chart_name := fsion.Get("chart_name").ValueStr()
- desc := fsion.Get("desc").ValueStr()
- pastureid := fsion.Get("pastureid").ValueStr()
- source_id := fsion.Get("source_id").ValueStr()
- emp := fsion.Get("emp").ValueStr()
- content := fsion.Get("content").Json()
- var mapResult map[string]interface{}
- err1 := json.Unmarshal([]byte(content), &mapResult)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err1)
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
- ids, pastureid, chart_name, 0, emp, desc, source_id)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec)
- }
- }
- func Updatedashboard(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- dashboard_id := fsion.Get("dashboard_id").ValueStr()
- pastureid := fsion.Get("pastureid").ValueStr()
- content := fsion.Get("content").Json()
- var mapResult map[string]interface{}
- err1 := json.Unmarshal([]byte(content), &mapResult)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err1)
- }
- layout := mapResult["layout"]
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
- if err != nil {
- println("2", err.Error())
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- if exec != nil {
- if exec[0]["content"] == nil {
- mapR := make(map[string]interface{})
- mapR["layout"] = layout
- mjson, _ := json.Marshal(mapR)
- mString := string(mjson)
- exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
- if err3 != nil {
- println("3", err3.Error())
- appG.Response(http.StatusOK, e.ERROR, err3.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec1)
- }
- } else {
- var mapR map[string]interface{}
- err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err2)
- }
- mapR["layout"] = layout
- mjson, _ := json.Marshal(mapR)
- mString := string(mjson)
- exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
- if err3 != nil {
- println("3", err3.Error())
- appG.Response(http.StatusOK, e.ERROR, err3.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec1)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
- }
- }
- }
- func ExecSQL(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- content := fsion.Get("content").Json()
- pastureid := fsion.Get("pastureid").ValueStr()
- var mapResult map[string]interface{}
- err1 := json.Unmarshal([]byte(content), &mapResult)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err1)
- }
- sqlstr := "select "
- groupstr := " GROUP BY "
- for _, value := range mapResult["selectedDimension"].([]interface{}) {
- sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
- groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
- }
- for _, value := range mapResult["selectedCalcul"].([]interface{}) {
- if value.(map[string]interface{})["calculFunc"].(string) == "none" {
- sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
- groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
- } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
- tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
- tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- } else {
- tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- }
- }
- if _, ok := mapResult["selectedCalcul2"]; ok {
- for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
- if value.(map[string]interface{})["calculFunc"].(string) == "none" {
- sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
- groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
- } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
- tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
- tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- } else {
- tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- }
- }
- }
- sqlstr = sqlstr[0 : len(sqlstr)-1]
- sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
- sqlstr = sqlstr + " where pastureid=" + pastureid
- if len(mapResult["filters"].([]interface{})) > 0 {
- sqlstr = sqlstr + " and "
- }
- println(len(mapResult["filters"].([]interface{})), sqlstr)
- for _, value := range mapResult["filters"].([]interface{}) {
- switch value.(map[string]interface{})["filterOperator"].(string) {
- case ">", "=", "<", ">=", "<=", "!=", "like":
- 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 "
- case "IN":
- sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
- for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
- sqlstr = sqlstr + value1.(string) + ","
- }
- sqlstr = sqlstr[0 : len(sqlstr)-1]
- sqlstr = sqlstr + ")" + " AND "
- case "BETWEEN":
- 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 "
- }
- }
- if len(mapResult["filters"].([]interface{})) > 0 {
- sqlstr = sqlstr[0 : len(sqlstr)-4]
- }
- //
- groupstr = groupstr[0 : len(groupstr)-1]
- sqlstr = sqlstr + groupstr + " "
- if len(mapResult["orderByStrs"].([]interface{})) > 0 {
- sqlstr = sqlstr + " order by "
- }
- //
- for key, value := range mapResult["orderByStrs"].([]interface{}) {
- if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
- sqlstr = sqlstr + value.(string) + " "
- } else {
- sqlstr = sqlstr + value.(string) + ","
- }
- }
- //
- sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- exec, err := tx.SQL(sqlstr).Query().List()
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec)
- }
- }
- func Dashboards(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- //sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- //paramslist1 := strings.Split(p1, ",")
- dids := make([]interface{}, 0)
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- var mapResult map[string]interface{}
- dids = append(dids, value["dashboard_id"])
- if value["content"] != nil {
- err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
- if err1 != nil {
- println("JsonToMapDemo1 err: ", err1)
- }
- temap := make(map[string]interface{})
- tem := mapResult["layout"].([]interface{})
- if v, ok := value["chartids"]; ok {
- chartids := strings.Split(v.(string), ",")
- for _, va := range chartids {
- a := false
- for _, v2 := range tem {
- if v2.(map[string]interface{})["id"].(string) == va {
- a = true
- //println("va1======",va)
- }
- }
- if !a {
- laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
- va + "\",\"id\":\"" + va +
- "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
- var mapTem map[string]interface{}
- err1 := json.Unmarshal([]byte(laytem), &mapTem)
- if err1 != nil {
- println("JsonToMapDemo err: ", err1)
- }
- tem = append(tem, mapTem)
- }
- }
- temap["layout"] = tem
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
- }
- } else {
- temap := make(map[string]interface{})
- tem := make([]interface{}, 0)
- if v, ok := value["chartids"]; ok {
- chartids := strings.Split(v.(string), ",")
- for _, va := range chartids {
- laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
- va + "\",\"id\":\"" + va +
- "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
- var mapTem map[string]interface{}
- err1 := json.Unmarshal([]byte(laytem), &mapTem)
- if err1 != nil {
- println("JsonToMapDemo err: ", err1)
- }
- tem = append(tem, mapTem)
- }
- temap["layout"] = tem
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
- }
- }
- }
- queryData.(map[string]interface{})["order"] = dids
- queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
- fsion := gofasion.NewFasion(parammaps)
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- body := []byte("")
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- body, _ = json.Marshal(queryData)
- }
- }
- }
- bs := bytes.NewBuffer(body)
- client := &http.Client{}
- //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
- req, err := http.NewRequest(RequestMethod,
- url,
- bs,
- )
- if err != nil {
- }
- req.Header.Set("Content-Type", "application/json;charset=utf-8")
- req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
- if err != nil {
- // handle error
- }
- resp, err := client.Do(req)
- if err != nil {
- return ""
- }
- defer resp.Body.Close()
- result_body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return ""
- }
- fmt.Println(string(result_body))
- return ""
- }
- func GetSummary(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- parammaps := fsion.Get("parammaps")
- status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
- genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
- isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
- tx := restful.Engine.NewSession()
- defer tx.Close()
- sqlnamestr := ""
- if genre == "0" {
- if status == "0" {
- sqlnamestr = "getAccuracyJSY"
- } else if status == "1" {
- sqlnamestr = "getAccuracyHFT"
- } else if status == "2" {
- sqlnamestr = "getAccuracyHNS"
- } else if status == "3" {
- sqlnamestr = "getAccuracyHSC"
- } else if status == "4" {
- sqlnamestr = "getAccuracyHCC"
- } else if status == "5" {
- sqlnamestr = "getAccuracyMC"
- } else if status == "6" {
- sqlnamestr = "getAccuracyFeedHL"
- } else if status == "7" {
- sqlnamestr = "getAccuracyRT"
- }
- } else {
- if status == "0" {
- sqlnamestr = "getAccuracySCCJSY"
- } else if status == "1" {
- sqlnamestr = "getAccuracySFT"
- } else if status == "2" {
- sqlnamestr = "getAccuracySNS"
- } else if status == "3" {
- sqlnamestr = "getAccuracySSC"
- } else if status == "4" {
- sqlnamestr = "getAccuracySCC"
- } else if status == "5" {
- sqlnamestr = "getAccuracySLCL"
- } else if status == "7" {
- sqlnamestr = "getAccuracySCCRT"
- }
- }
- if isDate == "1" {
- sqlnamestr += "Date"
- }
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- // fmt.Println(sqlnamestr, sql)
- if sql != "" {
- s_params := make([]interface{}, 0)
- // if fsion.HasKey("parammaps") {
- fmt.Println(s_params, "222", p)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // type lpplanStruct struct {
- // Id int64 `xorm:"id"`
- // Tmrname string `xorm:"tmrname"`
- // Tmrid int64 `xorm:"tmrid"`
- // Sort int64 `xorm:"sort"`
- // Sel int64 `xorm:"sel"`
- // Times int64 `xorm:"times"`
- // Ftname string `xorm:"ftname"`
- // Ftid int64 `xorm:"ftid"`
- // Maxweight float64 `xorm:"maxweight"`
- // Sumweight float64 `xorm:"sumweight"`
- // Sumcowcount int64 `xorm:"sumcowcount"`
- // Pastureid string `xorm:"pastureid"`
- // Display string `xorm:"display"`
- // Issplit int64 `xorm:"issplit"`
- // BeginTime string `xorm:"begintime"`
- // }
- func UpdateFTdetail(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- tempval_ := make(map[string]interface{})
- tempCommon := make(map[string]interface{})
- tempval := make([]map[string]interface{}, 0)
- fTChange := make(map[string]interface{}, 0)
- fpdOldDataList := make([]map[string]interface{}, 0)
- fpdDataList := make([]map[string]interface{}, 0)
- fsion := gofasion.NewFasion(string(dataByte))
- // parammaps := fsion.Get("parammaps")
- createdate := time.Now().Format("2006-01-02 15:04:05")
- err := json.Unmarshal(dataByte, &tempval_)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- tx := restful.Engine.NewSession()
- if v, ok := tempval_["data"].([]interface{}); ok {
- for _, Tvalue := range v {
- if v1, ok := Tvalue.(map[string]interface{}); ok {
- if v1["name"] == "updateFPbyFTChange" {
- fTChange = v1
- continue
- }
- tempval = append(tempval, v1)
- }
- }
- }
- parammaps := fTChange["parammaps"].(map[string]interface{})
- // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- err = tx.Begin()
- if err != nil {
- logging.Error("tx.Begin 事务启动失败__error:", err)
- }
- defer func() {
- if err != nil {
- if tx != nil {
- tx.Rollback()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- if err != nil {
- } else {
- if v, ok := tempval_["common"].(map[string]interface{}); ok {
- tempCommon = v
- }
- 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 ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
- UNION
- 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 ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
- order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
- if err == nil {
- if tempv, exists := c.Get("jwt_username"); exists {
- tempCommon["jwt_username"] = tempv.(string)
- }
- for _, paramvalue := range tempval {
- if _, ok := paramvalue["resultname"]; !ok {
- paramvalue["resultname"] = paramvalue["name"]
- }
- _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
- if err != nil {
- logging.Error("ExecDataParam error:", err)
- break
- }
- }
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- }
- }
- tx.Commit()
- // go func() {
- if fTChange != nil {
- parammaps := fTChange["parammaps"].(map[string]interface{})
- if parammaps["type"].(float64) == 1 {
- _, err = tx.SQL(`UPDATE feedp fp
- set
- ccountratio = ccount *(ratio /100 ),
- fp.ftweight= IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
- ),0),fp.feedweight = IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
- ),0) +ifnull(fp.supplyweight,0)
- WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
- _, err = tx.SQL(`UPDATE fpdetail fpd
- INNER JOIN feedp fp
- ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
- SET fpd.weight = fp.feedweight*fpd.tratio/100
- WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
- } else {
- _, err = tx.SQL(`UPDATE feedp fp
- SET ccountratio = ccount *(ratio /100 ),
- fp.supplyweight= IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
- ),0),fp.feedweight = IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
- ),0) +ifnull(fp.supplyweight,0)
- WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
- _, err = tx.SQL(`UPDATE fpdetail fpd
- INNER JOIN feedp fp
- ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
- SET fpd.weight = fp.feedweight*fpd.tratio/100
- WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
- }
- 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 ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
- UNION
- 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 ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
- order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
- lpplanList := make([]*lpplanStruct, 0)
- err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
- if err != nil {
- logs.Error(err, 1)
- return
- }
- lppidlist := []string{}
- for _, lpp := range lpplanList {
- lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
- }
- if len(lppidlist) <= 0 {
- appG.Response(http.StatusOK, e.SUCCESS, true)
- return
- }
- lpplandtl1AllList := make([]*lpplandtl1, 0)
- err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
- order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
- if err != nil {
- // tx.Rollback()
- logs.Error(err, 2, parammaps["pastureid"])
- return
- }
- var wg sync.WaitGroup
- for _, old := range fpdOldDataList {
- for _, fpd := range fpdDataList {
- wg.Add(1)
- go func(old, fpd map[string]interface{}) {
- updateLppandList := make([]*lpplandtl1, 0)
- defer wg.Done()
- if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
- fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
- weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
- // if weight > oldweight {
- // return
- // }
- var w float64
- var status int
- if weight < oldweight {
- if weight >= 0 {
- return
- }
- w = weight
- status = 0
- } else {
- if oldweight > 0 {
- return
- }
- w = weight
- status = 1
- }
- // fweight = w
- for _, lpp := range lpplanList {
- var fweight float64
- var lweight float64
- lpplandtl1List := make([]*lpplandtl1, 0)
- fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
- for _, lppland := range lpplandtl1AllList {
- if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
- lpplandtl1List = append(lpplandtl1List, lppland)
- }
- }
- if len(lpplandtl1List) == 0 {
- continue
- }
- for _, lppland := range lpplandtl1List {
- lweight += lppland.Lweight
- }
- if status == 0 {
- if lweight <= 0 {
- continue
- }
- } else {
- if lpp.Maxweight <= lweight {
- continue
- }
- }
- for _, lppland := range lpplandtl1List {
- if fpdid == lppland.Fpdid {
- if status == 1 {
- // if w <= lppland.Lweight {
- if lpp.Maxweight <= lweight {
- continue
- }
- if w+lweight <= lpp.Maxweight {
- lppland.Lweight += w
- lweight += w
- fweight += w
- w = 0
- } else {
- w = w - (lpp.Maxweight - lweight)
- n := (lpp.Maxweight - lweight)
- lppland.Lweight = lppland.Lweight + n
- lweight += n
- fweight += n
- }
- } else {
- if lppland.Lweight == 0 {
- continue
- }
- if w+lppland.Lweight >= 0 {
- lppland.Lweight = lppland.Lweight + w
- lweight = lweight + w
- fweight = fweight + w
- w = 0
- } else {
- w = w + lppland.Lweight
- lweight = lweight - lppland.Lweight
- fweight = fweight - lppland.Lweight
- lppland.Lweight = 0
- }
- }
- updateLppandList = append(updateLppandList, lppland)
- break
- }
- }
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
- ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
- if err != nil {
- // tx.Rollback()
- logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
- return
- }
- for _, lppland := range updateLppandList {
- fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
- _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
- if err != nil {
- fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
- // tx.Rollback()
- logs.Error(err, 3)
- return
- }
- // defer wg.Done()
- }
- updateLppandList = []*lpplandtl1{}
- if w == 0 {
- break
- }
- }
- }
- }(old, fpd)
- }
- }
- wg.Wait()
- }
- newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- now := createdate
- // for _, oldFpd := range oldFpdDataList {
- for _, newFpd := range newFpdDataList {
- // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
- // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
- // go func() {
- _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
- newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
- newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- // }()
- }
- // break
- // }
- // }
- // }
- // for _, oldLpplandtl1 := range oldLpplandtl1List {
- for _, newLpplandtl1 := range newLpplandtl1List {
- // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
- // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
- // go func() {
- _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
- background,cowcount,ccountradio,lweighthis,createdate,userId)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
- newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
- newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
- newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
- newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- // }()
- // }
- // break
- // }
- // }
- }
- // for _, oldFeedp := range oldFeedpList {
- for _, newFeedp := range newFeedpList {
- // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
- // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
- // go func() {
- _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
- ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
- newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
- newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
- newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
- newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- type lpplandtlInfo struct {
- Id int64 `xorm:"id"`
- Pastureid int64 `xorm:"pastureid"`
- Lppid int64 `xorm:"lppid"`
- Barid int64 `xorm:"barid"`
- Barname string `xorm:"barname"`
- Fpdid int64 `xorm:"fpdid"`
- Fttype int64 `xorm:"fttype"`
- Lweight float64 `xorm:"lweight"`
- Sort int64 `xorm:"sort"`
- Tmrid int64 `xorm:"tmrid"`
- Tmrname string `xorm:"tmrname"`
- Cowcount int64 `xorm:"cowcount"`
- Ccountradio float64 `xorm:"ccountradio"`
- Background string `xorm:"background"`
- Lweighthis float64 `xorm:"lweighthis"`
- Maxweight float64 `xorm:"maxweight"`
- }
- func UpdateFpdetailBar(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- pastureid := fsion.Get("pastureid").ValueStr()
- id := fsion.Get("id").ValueStr()
- tx := restful.Engine.NewSession()
- tx.Begin()
- 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 `,
- pastureid, id).Query().List()
- if err != nil {
- logs.Error(err)
- }
- for _, fpd := range fpdList {
- lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
- where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
- pastureid, fpd["id"]).Query().List()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- var lweight float64
- for _, lppland := range lpplandList {
- lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- lweight += lweight1
- }
- fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
- if fpdweight >= ptuse && lweight == ptuse {
- continue
- } else {
- if lweight <= fpdweight {
- _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- } else {
- weight := fpdweight - lweight
- for _, lppland := range lpplandList {
- lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- if weight >= lpplandlweight {
- weight = weight - lpplandlweight
- _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- } else {
- // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
- // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- weight = 0
- break
- }
- }
- }
- }
- }
- fsionData := fsion.Get("data").Array()
- for _, list := range fsionData {
- ftmap := make(map[string]interface{})
- ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
- ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
- ftmap["times"] = list.Get("times").ValueInt64()
- ftmap["ptid"] = list.Get("ptid").ValueStr()
- ftmap["ptsid"] = list.Get("ptsid").ValueStr()
- // fmt.Println(ftmap)
- fpdDataList, err := tx.SQL(`
- 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 ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
- // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- for _, fpd := range fpdDataList {
- if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
- fttype := -1
- if fpd["fttype"].(string) == "1" {
- fttype = 1
- }
- var fweight float64
- var lweight float64
- lpplandtl1List := make([]*lpplandtlInfo, 0)
- err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
- join lpplandtl1 lppland on lpp.id = lppland.lppid
- join tmr t on t.id = lpp.tmrid
- where lppland.fpdid =?
- and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
- fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- var w float64
- var status int
- fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
- if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
- if weight >= 0 {
- continue
- }
- w = weight
- status = 0
- } else {
- // continue
- if weight <= 0 {
- continue
- }
- w = weight
- status = 1
- }
- // for _, lppland := range lpplandtl1List {
- // lweight += lppland.Lweight
- // }
- for _, lppland := range lpplandtl1List {
- lpplandInfo := new(lpplandtlInfo)
- err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
- lweight = lpplandInfo.Lweight
- if status == 1 {
- // if w <= lppland.Lweight {
- if lppland.Maxweight <= lweight {
- continue
- }
- if w+lweight <= lppland.Maxweight {
- lppland.Lweight += w
- lweight += w
- fweight += w
- w = 0
- } else {
- w = w - (lppland.Maxweight - lweight)
- n := (lppland.Maxweight - lweight)
- lppland.Lweight = lppland.Lweight + n
- lweight += n
- fweight += n
- }
- } else {
- if lppland.Lweight == 0 {
- continue
- }
- if w+lppland.Lweight >= 0 {
- lppland.Lweight = lppland.Lweight + w
- lweight = lweight + w
- fweight = fweight + w
- w = 0
- } else {
- w = w + lppland.Lweight
- lweight = lweight - lppland.Lweight
- fweight = fweight - lppland.Lweight
- lppland.Lweight = 0
- }
- }
- if lppland.Lweight > 0 {
- _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return
- }
- } else {
- _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return
- }
- }
- if w == 0 {
- break
- }
- // break
- }
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
- ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- if w == 0 {
- break
- }
- }
- }
- }
- tx.Commit()
- now := time.Now()
- newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- for _, newLpplandtl1 := range newLpplandtl1List {
- _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
- background,cowcount,ccountradio,lweighthis,createdate,userId)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
- newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
- newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
- newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
- newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetProcessAnalysis(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- parammaps := fsion.Get("parammaps")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- s_params := make([]interface{}, 0)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- tmrtnameStr := ""
- for _, tmr := range parammaps.Get("tmrtname").Array() {
- if len(tmrtnameStr) == 0 {
- tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
- } else {
- tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
- }
- }
- if len(tmrtnameStr) > 0 {
- sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
- }
- sql += " ORDER BY d.intime"
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- func UpdateFeedtempletStatus(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- tx := restful.Engine.NewSession()
- tx.Begin()
- _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- tx.Commit()
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func AddFtdry(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- s_params := make([]interface{}, 0)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- parammaps := fsion.Get("parammaps")
- logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- var actweight float64
- actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
- where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
- and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
- where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
- and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
- group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
- 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()
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- if len(actweightList) > 0 {
- for _, item := range actweightList {
- fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- actweight = fl
- }
- } else {
- dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
- where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
- parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- for _, item := range dryList {
- dry, err := strconv.ParseFloat(item["dry"].(string), 64)
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- actweight += parammaps.Get("freshweight").ValueFloat64() * dry
- }
- }
- if sqlnamestr == "insertFtdry" {
- s_params = append(s_params, actweight)
- } else if sqlnamestr == "updateFtdry" {
- sql = fmt.Sprintf(sql, actweight)
- }
- queryData, err := execDataBySqlT(sql, s_params, tx)
- if err != nil {
- logging.Error("AddFtdry err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func CheckDates(c *gin.Context) {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- tempval_ := make(map[string]interface{})
- tempCommon := make(map[string]interface{})
- tempval := make([]map[string]interface{}, 0)
- err := json.Unmarshal(dataByte, &tempval_)
- logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- if err != nil {
- } else {
- if v, ok := tempval_["common"].(map[string]interface{}); ok {
- tempCommon = v
- }
- if v, ok := tempval_["data"].([]interface{}); ok {
- for _, Tvalue := range v {
- if v1, ok := Tvalue.(map[string]interface{}); ok {
- tempval = append(tempval, v1)
- }
- }
- }
- if err == nil {
- if tempv, exists := c.Get("jwt_username"); exists {
- tempCommon["jwt_username"] = tempv.(string)
- }
- for _, paramvalue := range tempval {
- if _, ok := paramvalue["resultname"]; !ok {
- paramvalue["resultname"] = paramvalue["name"]
- }
- _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
- if err != nil {
- logging.Error("ExecDataParam error:", err)
- }
- }
- if err == nil {
- vmsg := ""
- for _, item := range tempval {
- for _, list := range item["resultmaps"].(map[string]interface{}) {
- for _, childrenList := range list.([]interface{}) {
- for k, children := range childrenList.(map[string]interface{}) {
- if k != "children" {
- continue
- }
- for _, v := range children.([]map[string]interface{}) {
- for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
- if k1 == "list" {
- for _, v2 := range v1.([]map[string]interface{}) {
- if v2["vmsg"].(string) != "1" {
- if len(vmsg) == 0 {
- vmsg = v2["vmsg"].(string)
- } else {
- vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- if len(vmsg) > 0 {
- appG.Response(http.StatusOK, e.SUCCESS, vmsg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- } else {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusInternalServerError, e.ERROR, msg)
- }
- }
- }
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- }
- 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) {
- sqlname := fasion["name"].(string)
- sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
- if v, ok := fasion["type"]; ok {
- sqltype = v.(string)
- }
- sql := ""
- p := ""
- s_params := make([]interface{}, 0)
- if sqltype != "" {
- sql, p = restful.GetSqlByName(sqlname, tx)
- //sqlApi, _ := models.GetApisqlByName(sqlname)
- if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- ss := ""
- if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if ss == "" && CommonParamMap != nil {
- if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
- ss = valuestring
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
- if CommonParamMap[valuestring[tempstre+1:]] != nil {
- ss = CommonParamMap[valuestring[tempstre+1:]].(string)
- }
- } else {
- ss = ""
- }
- }
- }
- if ss == "" && ParentParamMap != nil {
- ss = getParamValue_(v, value, ParentParamMap)
- }
- if ss == "" && sameParamMap != nil {
- ss = getParamValue(v, value, sameParamMap)
- }
- if ss == "" && ParamMap != nil {
- ss = getParamValue(v, value, ParamMap)
- }
- s_params = append(s_params, ss)
- }
- }
- }
- }
- }
- if sql == "" {
- sqltype = ""
- }
- if sql != "" {
- tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
- if err != nil {
- return nil, err
- }
- // fmt.Println(tempValParam)
- return tempValParam.(map[string]interface{}), nil
- } else {
- if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
- err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return nil, err
- }
- }
- return nil, nil
- }
- func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
- var err error
- subarray, ok := fasion["children"]
- if ok {
- for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
- tempVal_arrary := make([]map[string]interface{}, 0)
- for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
- tempVal_ := make(map[string]interface{})
- if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
- } else {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
- }
- tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
- if err != nil {
- return err
- }
- tempVal_arrary = append(tempVal_arrary, tempVal_)
- }
- v.(map[string]interface{})["children"] = tempVal_arrary
- }
- }
- return nil
- }
- func FpdImportExcel(c *gin.Context) {
- appG := app.Gin{C: c}
- inputdata := ""
- c.Request.ParseForm()
- params := c.Request.Form
- file, _, err := c.Request.FormFile("file")
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- sqlnamestrs := params.Get("name")
- sheetname := params.Get("sheetname")
- pastureid := params.Get("pastureid")
- // importParams := params.Get("importParams")
- logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
- // 必输项参数 (字符串格式 "field1,field2,field3")
- requiredParams := params.Get("requiredParams")
- // 日期参数
- dateParams := params.Get("dateParams")
- // 数字参数
- numParams := params.Get("numParams")
- //将字符串分割开
- dateParamslist := strings.Split(dateParams, ",")
- requiredParamslist := strings.Split(requiredParams, ",")
- numParamslist := strings.Split(numParams, ",")
- queryData := make([]interface{}, 0)
- sqlslist := strings.Split(sqlnamestrs, ",")
- xlsx1, err := excelize.OpenReader(file)
- if err != nil {
- fmt.Println(err)
- return
- }
- ok := 0
- error := 0
- isdone := true
- tx := restful.Engine.NewSession()
- defer tx.Close()
- 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
- join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- rows := xlsx1.GetRows(sheetname)
- // 限制10000条,多余的截取掉
- if len(rows) > 10000 {
- rows = rows[:10000]
- }
- dataList := make(map[string][]*upFpdetail, 0)
- for i, row := range rows {
- if i > 0 {
- entry := make(map[string]interface{})
- outentry := make(map[string]interface{})
- for j, colCell := range rows[0] {
- for k, colCell1 := range row {
- if j == k {
- outentry[colCell] = colCell1
- entry[colCell] = colCell1
- }
- }
- }
- inputdata = ""
- a := ""
- // fmt.Println(outentry, entry, "aaaaaaaaaaa")
- //校验日期格式
- for _, v := range dateParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; ok {
- dtime, err := TransfTime(d.(string))
- if err != nil {
- a = strings.Trim(v, " ")
- break
- }
- outentry[strings.Trim(v, " ")] = dtime
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验必填格式
- for _, v := range requiredParamslist {
- if v == "" {
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
- a = strings.Trim(v, " ")
- break
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 未填或格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- //校验数字格式
- for _, v := range numParamslist {
- if v == "" {
- continue
- }
- d, ok := outentry[strings.Trim(v, " ")]
- if !ok || d == "" {
- outentry[strings.Trim(v, " ")] = 0
- } else {
- var fl float64
- switch d.(type) {
- case string:
- fl, err = strconv.ParseFloat(d.(string), 64)
- }
- if err != nil || fl < 0 {
- a = strings.Trim(v, " ")
- break
- }
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 为数值类型且不可为负数"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- errExist := false
- for _, sqlnamestr := range sqlslist {
- sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
- paramslist := strings.Split(paramslists, ",")
- if len(paramslist) > 0 {
- s_params := make([]interface{}, 0)
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
- s_params = append(s_params, pastureid)
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if outentry[strings.Trim(value, " ")] == nil {
- s_params = append(s_params, "")
- } else {
- s_params = append(s_params, outentry[strings.Trim(value, " ")])
- }
- }
- }
- outentry["input"] = inputdata
- returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
- if err != nil {
- errExist = true
- // if tx != nil {
- // tx.Rollback()
- // }
- // if tx != nil {
- // tx.Close()
- // }
- msg := geterrmsg(err.Error())
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- } else {
- if len(returnmsgmap1) > 0 {
- if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
- // if tx != nil {
- // tx.Rollback()
- // }
- // if tx != nil {
- // tx.Close()
- // }
- msg := geterrmsg(va.(string))
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- }
- }
- isdone = false
- }
- }
- }
- if !errExist {
- dataexcel := make(map[string]interface{}, 0)
- if _, ok := outentry["栏舍名称"]; ok {
- dataexcel["barname"] = outentry["栏舍名称"]
- }
- if _, ok := outentry["实际牛头数"]; ok {
- dataexcel["ccount"] = outentry["实际牛头数"]
- }
- if _, ok := outentry["系数(%)"]; ok {
- dataexcel["ratio"] = outentry["系数(%)"]
- }
- if _, ok := outentry["配方模板"]; ok {
- dataexcel["ftname"] = outentry["配方模板"]
- }
- if _, ok := outentry["补料配方"]; ok {
- dataexcel["ptsfname"] = outentry["补料配方"]
- }
- if _, ok := outentry["第一班比例(%)"]; ok {
- dataexcel["1"] = outentry["第一班比例(%)"]
- }
- if _, ok := outentry["第二班比例(%)"]; ok {
- dataexcel["2"] = outentry["第二班比例(%)"]
- }
- if _, ok := outentry["第三班比例(%)"]; ok {
- dataexcel["3"] = outentry["第三班比例(%)"]
- }
- if _, ok := outentry["第四班比例(%)"]; ok {
- dataexcel["4"] = outentry["第四班比例(%)"]
- }
- if _, ok := outentry["第五班比例(%)"]; ok {
- dataexcel["5"] = outentry["第五班比例(%)"]
- }
- if _, ok := outentry["第六班比例(%)"]; ok {
- dataexcel["6"] = outentry["第六班比例(%)"]
- }
- existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !existbar {
- continue
- }
- _, 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()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- _, 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()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
- return
- }
- if !existft {
- continue
- }
- ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !ftexist {
- fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
- tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist {
- _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- var feedpargs []interface{}
- upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
- if _, ok := dataexcel["ftname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
- upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- }
- if _, ok := dataexcel["ptsfname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
- upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- }
- upFeedpSql += " where barname = ? and pastureid = ? "
- feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
- _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist1 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist2 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist3 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist4 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist5 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist6 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
- ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- and pastureid = ? and times = ?`
- var fpdargs1 []interface{}
- fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var fpdargs2 []interface{}
- fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs3 []interface{}
- fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs4 []interface{}
- fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs5 []interface{}
- fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs6 []interface{}
- fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- 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()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- upFpdetailList := make([]*upFpdetail, 0)
- for _, newfpd := range newList {
- for _, oldfpd := range oldFpdList {
- if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- var oldweight, newweight float64
- if oldfpd["weight"] != nil {
- oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- }
- if newfpd["weight"] != nil {
- newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- }
- fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- upFpdetailList = append(upFpdetailList, &upFpdetail{
- Old: oldweight,
- New: newweight,
- Times: newfpd["times"].(int64),
- Ptid: newfpd["ptid"].(int64),
- Fweight: fweight,
- Id: oldfpd["id"].(int64),
- })
- break
- }
- }
- }
- // fmt.Println(dataexcel["barname"])
- dataList[dataexcel["barname"].(string)] = upFpdetailList
- // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
- }
- }
- if !isdone {
- ok++
- isdone = true
- }
- }
- for barname, v := range dataList {
- updateFpdetailByBar(pastureid, barname, v)
- }
- data := make(map[string]interface{})
- data["result"] = queryData
- data["success"] = ok
- data["err_count"] = error
- appG.Response(http.StatusOK, e.SUCCESS, data)
- }
- type upFpdetail struct {
- Old float64
- New float64
- Times int64
- Ptid int64
- Fweight float64
- Id int64
- // Ptsid string
- }
- func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- 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 `,
- pastureid, barname).Query().List()
- if err != nil {
- logs.Error(err)
- }
- for _, fpd := range fpdList {
- lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
- where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
- pastureid, fpd["id"], fpd["times"]).Query().List()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- var lweight float64
- for _, lppland := range lpplandList {
- lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- lweight += lweight1
- }
- fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
- if fpdweight >= ptuse && lweight == ptuse {
- continue
- } else {
- if lweight <= fpdweight {
- _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- } else {
- weight := lweight - fpdweight
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
- WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- for _, lppland := range lpplandList {
- lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- if weight >= lpplandlweight {
- weight = weight - lpplandlweight
- _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- } else {
- lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- weight = 0
- break
- }
- }
- }
- }
- }
- for _, list := range dataList {
- ftmap := make(map[string]interface{})
- ftmap["old"] = list.Old
- ftmap["new"] = list.New
- ftmap["times"] = list.Times
- ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
- ftmap["ptsid"] = ""
- // fmt.Println(ftmap)
- // 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 ,
- // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
- // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
- // UNION
- fpdDataList, err := tx.SQL(`
- 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 ,
- (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
- // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- for _, fpd := range fpdDataList {
- if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
- // fttype := -1
- // if fpd["fttype"].(string) == "1" {
- fttype := 1
- // }
- var fweight float64
- var lweight float64
- lpplandtl1List := make([]*lpplandtlInfo, 0)
- err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
- join lpplandtl1 lppland on lpp.id = lppland.lppid
- join tmr t on t.id = lpp.tmrid
- where lppland.fpdid =?
- and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
- fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
- // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
- // 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
- weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- var w float64
- var status int
- if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
- if weight >= 0 {
- continue
- }
- w = weight
- status = 0
- } else {
- // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
- // continue
- // }
- w = weight
- status = 1
- }
- // for _, lppland := range lpplandtl1List {
- // lweight += lppland.Lweight
- // }
- for _, lppland := range lpplandtl1List {
- lpplandInfo := new(lpplandtlInfo)
- err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
- lweight = lpplandInfo.Lweight
- if status == 1 {
- // if w <= lppland.Lweight {
- if lppland.Maxweight <= lweight {
- continue
- }
- if w+lweight <= lppland.Maxweight {
- lppland.Lweight += w
- lweight += w
- fweight += w
- w = 0
- } else {
- w = w - (lppland.Maxweight - lweight)
- n := (lppland.Maxweight - lweight)
- lppland.Lweight = lppland.Lweight + n
- lweight += n
- fweight += n
- }
- } else {
- if lppland.Lweight == 0 {
- continue
- }
- if w+lppland.Lweight >= 0 {
- lppland.Lweight = lppland.Lweight + w
- lweight = lweight + w
- fweight = fweight + w
- w = 0
- } else {
- w = w + lppland.Lweight
- lweight = lweight - lppland.Lweight
- fweight = fweight - lppland.Lweight
- lppland.Lweight = 0
- }
- }
- if lppland.Lweight > 0 {
- _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- } else {
- _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- }
- if w == 0 {
- break
- }
- }
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
- ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- if w == 0 {
- break
- }
- }
- }
- }
- // for _, data := range dataList {
- // fttype := -1
- // if data.Ptid != -1 {
- // fttype = 1
- // }
- // var fweight float64
- // var lweight float64
- // lpplandtl1List := make([]*lpplandtlInfo, 0)
- // err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
- // join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
- // and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
- // data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // return err
- // }
- // weight := data.Fweight
- // // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- // var w float64
- // var status int
- // if data.New < data.Old {
- // if weight >= 0 {
- // continue
- // }
- // w = weight
- // status = 0
- // } else {
- // // if weight-(data.New-data.Old) > 0 {
- // // continue
- // // }
- // w = data.New - data.Old
- // status = 1
- // }
- // for _, lppland := range lpplandtl1List {
- // var lppdata lpplandtlInfo
- // tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
- // lppland.Lppid, pastureid).GetFirst(&lppdata)
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // return err
- // }
- // lweight = lppdata.Lweight
- // if status == 1 {
- // // if w <= lppland.Lweight {
- // if lppland.Maxweight <= lweight {
- // continue
- // }
- // if w+lweight <= lppland.Maxweight {
- // lppland.Lweight += w
- // lweight += w
- // fweight += w
- // w = 0
- // } else {
- // w = w - (lppland.Maxweight - lweight)
- // n := (lppland.Maxweight - lweight)
- // lppland.Lweight = lppland.Lweight + n
- // lweight += n
- // fweight += n
- // }
- // } else {
- // if lppland.Lweight == 0 {
- // continue
- // }
- // if w+lppland.Lweight >= 0 {
- // lppland.Lweight = lppland.Lweight + w
- // lweight = lweight + w
- // fweight = fweight + w
- // w = 0
- // } else {
- // w = w + lppland.Lweight
- // lweight = lweight - lppland.Lweight
- // fweight = fweight - lppland.Lweight
- // lppland.Lweight = 0
- // }
- // }
- // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // return err
- // }
- // break
- // }
- // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
- // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- // WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
- // if err != nil {
- // tx.Rollback()
- // logs.Error(err)
- // return err
- // }
- // // if w == 0 {
- // // break
- // // }
- // // }
- // }
- err = tx.Commit()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- return err
- }
- now := time.Now()
- newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- return nil
- }
- newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- return nil
- }
- newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- return nil
- }
- for _, newLpplandtl1 := range newLpplandtl1List {
- _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
- background,cowcount,ccountradio,lweighthis,createdate)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
- newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
- newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
- newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
- newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
- if err != nil {
- logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- return err
- }
- }
- for _, newFpd := range newFpdDataList {
- _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
- newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
- newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
- if err != nil {
- logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- return err
- }
- }
- for _, newFeedp := range newFeedpList {
- _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
- ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
- newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
- newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
- newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
- newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
- if err != nil {
- logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- return err
- }
- }
- return nil
- }
- func DeleteFTdetail(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- ftid := parammaps.Get("ftid").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- if parammaps.Get("type").ValueStr() == "1" {
- _, err := tx.SQL(`UPDATE feedp fp
- set
- fp.ftweight= IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
- ),0),fp.feedweight = IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
- ),0) +ifnull(fp.supplyweight,0)
- WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // UPDATE fpdetail SET ptuse=0 ,weight = 0
- _, err = tx.SQL(`
- UPDATE fpdetail fpd
- INNER JOIN feedp fp
- ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
- SET fpd.weight = fp.feedweight*fpd.tratio/100,
- ptuse= 0
- WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err := tx.SQL(`UPDATE feedp fp
- SET
- fp.supplyweight= IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
- ),0),fp.feedweight = IFNULL(IF(
- (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
- IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
- ),0) + ifnull(fp.supplyweight,0)
- WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- _, err = tx.SQL(`
- UPDATE fpdetail fpd
- INNER JOIN feedp fp
- ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
- SET fpd.weight = fp.feedweight*fpd.tratio/100,
- ptsrate = 0
- WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- err = tx.Commit()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func DeleteSpillageAll(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- times := parammaps.Get("times").ValueStr()
- barid := parammaps.Get("barid").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- now := time.Now()
- for _, item := range lpplandtl1List {
- go func(item map[string]interface{}) {
- _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
- background,cowcount,ccountradio,lweighthis,createdate)
- values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- item["pastureid"], item["lppid"], item["barid"],
- item["barname"], item["fpdid"], item["fttype"],
- item["lweight"], item["sort"], item["tmrid"],
- item["tmrname"], item["background"], item["cowcount"],
- item["ccountradio"], item["lweighthis"], now).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, false)
- return
- }
- }(item)
- }
- tx.Begin()
- _, 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()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- err = tx.Commit()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetTMRListEnableTypeAll(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL(`SELECT
- eqcode,
- tname,
- datacaptureno,
- trim(tclassid) tclassid,
- concat(tname,' / ',eqcode) tmrmix,
- d.label tclassname,
- maxstirfeed,
- remark,
- tmr.enable,
- TRIM(tmr.id) id,
- TRIM(tmr.pastureid)pastureid
- FROM
- tmr
- left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
- WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
- ORDER BY id DESC`, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var carNum int64
- for _, sysopt := range sysoptData {
- if sysopt["inforvalue"] == nil {
- carNum = 1
- } else {
- carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
- }
- }
- id := 200
- n := 0
- for i := carNum; i > 0; i-- {
- id++
- n++
- data := make(map[string]interface{}, 0)
- data["eqcode"] = fmt.Sprintf("任意车%d", n)
- data["tname"] = fmt.Sprintf("任意车%d", n)
- data["datacaptureno"] = -2
- data["tclassid"] = -2
- data["tmrmix"] = fmt.Sprintf("任意车%d", n)
- data["tclassname"] = fmt.Sprintf("任意车%d", n)
- data["maxstirfeed"] = 100000
- data["remark"] = fmt.Sprintf("任意车%d", n)
- data["enable"] = 1
- data["id"] = fmt.Sprintf("%d", id)
- data["pastureid"] = pastureid
- dataList = append(dataList, data)
- }
- // UNION ALL
- // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
- appG.Response(http.StatusOK, e.SUCCESS, dataList)
- }
- func GetFeedpHistory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- // parammaps := fsion.Get("parammaps")
- bar := fsion.Get("barname").ValueStr()
- startDate := fsion.Get("startDate").ValueStr()
- endDate := fsion.Get("endDate").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
- DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
- and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
- (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
- and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, feedp := range feedpList {
- // LastftList, err := tx.SQL(` select tname ,id
- // from feedtemplethistory where id = ?
- // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // return
- // }
- nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
- DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
- and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var ftname interface{}
- ftnamestatus := 0
- ftname = feedp["ftname"]
- var lastftid int64
- if len(nextfeedpList) > 0 {
- for _, ft := range nextfeedpList {
- if ft["ftname"].(string) != feedp["ftname"].(string) {
- ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
- lastftid = ft["ftid"].(int64)
- ftnamestatus = 1
- break
- }
- }
- }
- for i, fpd := range fpdList {
- if feedp["createdate"].(string) == fpd["createdate"].(string) {
- fpd["weightstatus"] = 0
- fpd["tratiostatus"] = 0
- fpd["ftnamestatus"] = ftnamestatus
- for k, fpd2 := range fpdList {
- if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
- if fpd["weight"].(string) != fpd2["weight"].(string) {
- fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
- fpd["weightstatus"] = 1
- }
- if fpd["tratio"].(string) != fpd2["tratio"].(string) {
- fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
- fpd["tratiostatus"] = 1
- }
- break
- }
- }
- fpd["barid"] = feedp["barid"]
- fpd["barname"] = feedp["barname"]
- fpd["ccount"] = feedp["ccount"]
- fpd["ratio"] = feedp["ratio"]
- fpd["ccountratio"] = feedp["ccountratio"]
- fpd["ftid"] = feedp["ftid"]
- fpd["ftname"] = ftname
- fpd["ccountstatus"] = 0
- fpd["ccountratiostatus"] = 0
- fpd["ratiostatus"] = 0
- fpd["ftnamestatus"] = 0
- fpd["lastftid"] = lastftid
- for _, next := range nextfeedpList {
- if next["ccount"].(int64) != fpd["ccount"].(int64) {
- fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
- fpd["ccountstatus"] = 1
- }
- if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
- fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
- fpd["ccountratiostatus"] = 1
- }
- if next["ratio"].(string) != fpd["ratio"].(string) {
- fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
- fpd["ratiostatus"] = 1
- }
- // if next["ftname"].(string) != fpd["ftname"].(string) {
- // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
- // fpd["ftnamestatus"] = 1
- // }
- }
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, fpdList)
- }
- // func GetLpplandtl1History(c *gin.Context) {
- // appG := app.Gin{C: c}
- // dataByte, _ := ioutil.ReadAll(c.Request.Body)
- // fsion := gofasion.NewFasion(string(dataByte))
- // // parammaps := fsion.Get("parammaps")
- // barid := fsion.Get("barid").ValueStr()
- // startDate := fsion.Get("startDate").ValueStr()
- // endDate := fsion.Get("endDate").ValueStr()
- // tx := restful.Engine.NewSession()
- // defer tx.Close()
- // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
- // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
- // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
- // // if err != nil {
- // // logs.Error(err)
- // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
- // // return
- // // }
- // // for _, feedp := range feedpList {
- // // fmt.Println(feedp)
- // // for i, fpd := range fpdList {
- // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
- // // for k, fpd2 := range fpdList {
- // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
- // // if fpd["weight"].(string) != fpd2["weight"].(string) {
- // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
- // // }
- // // break
- // // }
- // // }
- // // fpd["barid"] = feedp["barid"]
- // // fpd["barname"] = feedp["barname"]
- // // fpd["ccount"] = feedp["ccount"]
- // // fpd["ratio"] = feedp["ratio"]
- // // fpd["ccountratio"] = feedp["ccountratio"]
- // // fpd["ftid"] = feedp["ftid"]
- // // fpd["ftname"] = feedp["ftname"]
- // // }
- // // }
- // // }
- // appG.Response(http.StatusOK, e.SUCCESS, nil)
- // }
- func GetRemind(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // pastureid = "3"
- resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- defer resp.Body.Close()
- buf := bytes.NewBuffer(make([]byte, 0, 512))
- buf.ReadFrom(resp.Body)
- fmt.Println(string(buf.Bytes()))
- respMap := make(map[string]interface{}, 0)
- err = json.Unmarshal(buf.Bytes(), &respMap)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, data := range dataList {
- r := make(map[string]interface{}, 0)
- r["sys_name"] = ""
- r["service_id"] = ""
- r["pasture_id"] = ""
- r["type_name"] = ""
- r["remind_type_id"] = ""
- r["remind_type"] = ""
- r["push_date"] = ""
- r["push_time"] = ""
- r["interval_time"] = ""
- r["push_limit"] = ""
- r["template_id"] = ""
- r["roles_id"] = ""
- r["users_id"] = ""
- r["date_type"] = ""
- r["cycle_type"] = ""
- data["data"] = r
- for _, resp := range respMap["data"].([]interface{}) {
- resp1 := resp.(map[string]interface{})
- if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
- if resp1["push_time"] == nil {
- resp1["push_time"] = ""
- }
- data["data"] = resp1
- break
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, dataList)
- }
- type NoticeMsgtype struct {
- SysName string `json:"sys_name"`
- PastureId int64 `json:"pasture_id"`
- ServiceId int64 `json:"service_id"`
- TypeName string `json:"type_name"`
- RemindType int64 `json:"remind_type"`
- PushDate int64 `json:"push_date"`
- PushTime string `json:"push_time"`
- IntervalTime int64 `json:"interval_time"`
- PushLimit int64 `json:"push_limit"`
- TemplateId string `json:"template_id"`
- UsersId string `json:"users_id"`
- DateType int64 `json:"date_type"`
- CycleType int64 `json:"cycle_type"`
- DelayTime int64 `json:"delay_time"`
- Status int64 `json:"status"`
- }
- func UpdateRemind(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- // parammaps := fsion.Get("parammaps")
- // user := parammaps.Get("user").ValueStr()
- id := parammaps.Get("id").ValueInt64()
- noticeMsgtype := new(NoticeMsgtype)
- noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
- noticeMsgtype.ServiceId = id
- noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
- noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
- // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
- noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
- noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
- noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
- noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
- noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
- // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
- noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
- // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
- noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
- noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
- noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
- noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
- //TODO
- noticeMsgtype.SysName = "tmrWatch"
- userList := parammaps.Get("user").Array()
- var userstr []string
- for _, user := range userList {
- userstr = append(userstr, user.ValueStr())
- }
- tx := restful.Engine.NewSession()
- defer tx.Close()
- _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // var jsonStr = []byte(noticeMsgtype
- noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
- fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
- req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
- req.Header.Set("Content-Type", "application/json")
- client := &http.Client{}
- resp, err := client.Do(req)
- if err != nil {
- logs.Error(err)
- }
- defer resp.Body.Close()
- body, _ := ioutil.ReadAll(resp.Body)
- fmt.Println("response Body:", string(body))
- getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- defer getresp.Body.Close()
- buf := bytes.NewBuffer(make([]byte, 0, 512))
- buf.ReadFrom(getresp.Body)
- // fmt.Println(string(buf.Bytes()))
- respMap := make(map[string]interface{}, 0)
- err = json.Unmarshal(buf.Bytes(), &respMap)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, resp := range respMap["data"].([]interface{}) {
- resp1 := resp.(map[string]interface{})
- _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetSpillageallHistory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- barname := parammaps.Get("barname").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- startdate := parammaps.Get("startDate").ValueStr()
- enddate := parammaps.Get("endDate").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- historyList, err := tx.SQL(` select lpp.id,lpp.times,lppland.lweight,lppland.tmrid,lppland.tmrname,lpp.sort,DATE_FORMAT(lppland.createdate,'%Y-%m-%d %H:%i:%s') as createdate from lpplandtl1history lppland
- join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
- order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- respMap := make([]map[string]interface{}, 0)
- data := make(map[interface{}]interface{})
- for _, history := range historyList {
- data[history["createdate"]] = history["createdate"]
- }
- createList := []string{}
- for _, v := range data {
- createList = append(createList, v.(string))
- }
- // sort.Sort()
- // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
- sort.Slice(createList, func(i, j int) bool {
- return createList[i] > createList[j]
- })
- for _, v := range createList {
- a := make(map[string]interface{})
- a["createdate"] = data[v]
- // createList = append(createList, v.(string))
- respMap = append(respMap, a)
- }
- number := 0
- dataMap := make([]interface{}, 0)
- for k, resp := range respMap {
- createdate := resp["createdate"].(string)
- var nextcreatedate string
- if len(respMap) > k+1 {
- nextcreatedate = respMap[k+1]["createdate"].(string)
- }
- // dataList := make(map[string][]interface{})
- // list := make(map[string]interface{})
- times := make(map[interface{}]int)
- for _, history := range historyList {
- // List := make(map[interface{}][]interface{})
- i := 0
- if history["createdate"].(string) == createdate {
- times[history["times"]]++
- data := make(map[string]interface{})
- data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
- // exist := false
- if nextcreatedate != "" {
- for _, history1 := range historyList {
- if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
- history1["times"].(int64) == history["times"].(int64) {
- data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
- break
- // exist = true
- }
- }
- }
- // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
- i++
- // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
- // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
- // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
- // resp["times"] = history["times"]
- // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
- data1 := make(map[string]interface{})
- data1["times"] = history["times"]
- data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
- data1["createdate"] = resp["createdate"]
- // fmt.Println(dataList)
- dataMap = append(dataMap, data1)
- }
- if i > number {
- number = i
- }
- // respMap = append(respMap, dataList)
- }
- // for k, data := range dataList {
- // resp[k] = data
- // }
- // resp["data"] = dataList
- }
- // resp := make(map[string]interface{})
- // sort.Strings(createList)
- //
- // for _, create := range createList {
- // for _, r := range respMap {
- // if create == r["createdate"].(string) {
- // resp[create] = r
- // break
- // }
- // }
- // }
- sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
- var trainsList []interface{}
- for i := 0; i < number; i++ {
- trains := make(map[string]interface{})
- trains["label"] = fmt.Sprintf("第%s车", sz[i])
- trains["prop"] = fmt.Sprintf("a%d", i+1)
- trainsList = append(trainsList, trains)
- }
- respdata := make(map[string]interface{})
- respdata["data"] = dataMap
- respdata["trains"] = trainsList
- appG.Response(http.StatusOK, e.SUCCESS, respdata)
- }
- func GetRecipeTemplateRecordHistory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- ftid := parammaps.Get("ftid").ValueInt64()
- lastftid := parammaps.Get("lastftid").ValueInt64()
- pastureid := parammaps.Get("pastureid").ValueInt64()
- // createdate := parammaps.Get("createdate").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- data := make(map[string]interface{})
- feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
- and fthis.pastureId = ?`, ftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- feedtemplet := make(map[string]interface{})
- for _, f := range feedtempletList {
- feedtemplet = f
- }
- fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- feedtemplet["fit"] = fitList
- data["current"] = feedtemplet
- lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
- and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- lastfeedtemplet := make(map[string]interface{})
- for _, f := range lastfeedtempletList {
- lastfeedtemplet = f
- }
- lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- lastfeedtemplet["fit"] = lastfitList
- data["last"] = lastfeedtemplet
- appG.Response(http.StatusOK, e.SUCCESS, data)
- }
- func GetFeedtempletHistory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- ftid := parammaps.Get("ftid").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueInt64()
- start := parammaps.Get("startdate").ValueStr()
- end := parammaps.Get("enddate").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- 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 ?
- and id = ? and pastureid = ? order by createdate desc `,
- start, end, ftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
- ftid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
- for i, ft := range ftList {
- fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
- ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
- (select empname from user where id = fit.userId) empname,
-
- 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
- where fit.fitid = ?
- and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
- and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- ft["createdate"] = ft["createdate1"]
- // data["tname"] = ft["tname"]
- // data["tcode"] = ft["tcode"]
- // data["tcolor"] = ft["tcolor"]
- // data["fttype"] = ft["fttype"]
- // data["ccname"] = ft["ccname"]
- // data["source"] = ft["source"]
- // data["version"] = ft["version"]
- // data["remark"] = ft["remark"]
- for n, ft2 := range ftList {
- if i < n {
- if ft["tname"].(string) != ft2["tname"].(string) {
- ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
- }
- if _, ok := ft["tcode"]; ok {
- if _, ok := ft2["tcode"]; ok {
- if ft["tcode"].(string) != ft2["tcode"].(string) {
- ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
- }
- }
- }
- if _, ok := ft["tcolor"]; ok {
- if _, ok := ft2["tcolor"]; ok {
- if ft["tcolor"].(string) != ft2["tcolor"].(string) {
- ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
- }
- }
- }
- if _, ok := ft["fttype"]; ok {
- if _, ok := ft2["fttype"]; ok {
- if ft["fttype"].(string) != ft2["fttype"].(string) {
- ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
- }
- }
- }
- if _, ok := ft["ccname"]; ok {
- if _, ok := ft2["ccname"]; ok {
- if ft["ccname"].(string) != ft2["ccname"].(string) {
- ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
- }
- }
- }
- if _, ok := ft["source"]; ok {
- if _, ok := ft2["source"]; ok {
- if ft["source"].(string) != ft2["source"].(string) {
- ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
- }
- }
- }
- if _, ok := ft["version"]; ok {
- if _, ok := ft2["version"]; ok {
- if ft["version"].(int64) != ft2["version"].(int64) {
- ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
- }
- }
- }
- if _, ok := ft["remark"]; ok {
- if _, ok := ft2["remark"]; ok {
- if ft["remark"].(string) != ft2["remark"].(string) {
- ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
- }
- }
- }
- break
- }
- }
- dataList := make([]map[string]interface{}, 0)
- if len(fithisList) > 0 {
- for _, fit := range fithisList {
- data := make(map[string]interface{})
- data["feedgroup"] = fit["feedgroup"]
- data["fname"] = fit["fname"]
- data["empname"] = fit["empname"]
- if fit["Eweight"] != nil {
- if fit["Eweight"].(string) != fit["weight"].(string) {
- data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
- } else {
- data["fweight"] = fit["Eweight"]
- }
- data["fweightstatus"] = 1
- } else {
- data["fweight"] = fit["weight"]
- data["fweightstatus"] = 0
- }
- data["autosecond"] = fit["autosecond"]
- // data["tname"] = ft["tname"]
- // data["tcode"] = ft["tcode"]
- // data["tcolor"] = ft["tcolor"]
- // data["fttype"] = ft["fttype"]
- // data["ccname"] = ft["ccname"]
- // data["source"] = ft["source"]
- // data["version"] = ft["version"]
- // data["remark"] = ft["remark"]
- // data["createdate"] = ft["createdate1"]
- // ft["fit"] = data
- dataList = append(dataList, data)
- }
- } else {
- for _, fit := range ftdetailList {
- data := make(map[string]interface{})
- data["feedgroup"] = fit["feedgroup"]
- data["fname"] = fit["fname"]
- // if fit["Eweight"] != nil {
- // data["weight"] = fit["Eweight"]
- // } else {
- data["fweight"] = fit["fweight"]
- // }
- data["autosecond"] = fit["autosecond"]
- // ft["fit"] = data
- dataList = append(dataList, data)
- }
- }
- ft["fit"] = dataList
- }
- appG.Response(http.StatusOK, e.SUCCESS, ftList)
- }
- func UpdateMaterialTMR(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- tmrid := parammaps.Get("tmrid").ValueStr()
- tmrtype := parammaps.Get("tmrtype").ValueStr()
- lppid := parammaps.Get("lppid").ValueStr()
- times := parammaps.Get("times").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
- // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
- status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- if tmrid != "1000" {
- tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var maxstirfeed float64
- for _, tmr := range tmrList {
- maxstirfeed += float64(tmr["maxstirfeed"].(int64))
- }
- if status == 0 {
- lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var lweight float64
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- lweight += fl
- }
- if lweight > maxstirfeed {
- lweight = lweight - maxstirfeed
- } else {
- lweight = 0
- }
- if lweight > 0 {
- lweight1 := lweight / float64(len(lpplandtl1List))
- number := 0
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if lweight1 >= fl {
- number++
- }
- }
- lweight := lweight / float64((len(lpplandtl1List) - number))
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if lweight1 >= fl {
- continue
- }
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- } else {
- for _, item := range lpplandtl1List {
- // 自走式
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- }
- } else if status == 1 {
- lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var lweight float64
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- lweight += fl
- }
- if lweight > maxstirfeed {
- lweight = lweight - maxstirfeed
- } else {
- lweight = 0
- }
- for _, item := range lpplandtl1List {
- if lweight > 0 {
- // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if fl >= lweight {
- item["lweight"] = fl - lweight
- lweight = 0
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- } else {
- lweight = lweight - fl
- _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- } else {
- // 自走式
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- }
- } else {
- lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, item := range lpplandtl1List {
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- if status == 2 {
- lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, item := range lpplandtl1List {
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- err := tx.Commit()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func UpdateMaterialTMRDate(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- tmrid := parammaps.Get("tmrid").ValueStr()
- tmrtype := parammaps.Get("tmrtype").ValueStr()
- lppid := parammaps.Get("lppid").ValueStr()
- times := parammaps.Get("times").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- date := parammaps.Get("date").ValueStr()
- // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
- status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- if tmrid != "1000" {
- tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var maxstirfeed float64
- for _, tmr := range tmrList {
- maxstirfeed += float64(tmr["maxstirfeed"].(int64))
- }
- if status == 0 {
- 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var lweight float64
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- lweight += fl
- }
- if lweight > maxstirfeed {
- lweight = lweight - maxstirfeed
- } else {
- lweight = 0
- }
- if lweight > 0 {
- lweight1 := lweight / float64(len(lpplandtl1List))
- number := 0
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if lweight1 >= fl {
- number++
- }
- }
- lweight := lweight / float64((len(lpplandtl1List) - number))
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if lweight1 >= fl {
- continue
- }
- if tmrtype == "1" {
- _, 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- } else {
- for _, item := range lpplandtl1List {
- // 自走式
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- }
- } else if status == 1 {
- 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- var lweight float64
- for _, item := range lpplandtl1List {
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- lweight += fl
- }
- if lweight > maxstirfeed {
- lweight = lweight - maxstirfeed
- } else {
- lweight = 0
- }
- for _, item := range lpplandtl1List {
- if lweight > 0 {
- // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
- fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
- if fl >= lweight {
- item["lweight"] = fl - lweight
- lweight = 0
- if tmrtype == "1" {
- _, 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- } else {
- lweight = lweight - fl
- _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- } else {
- // 自走式
- if tmrtype == "1" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else if tmrtype == "2" {
- _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- }
- } else {
- lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, item := range lpplandtl1List {
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- _, 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()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- if status == 2 {
- lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- for _, item := range lpplandtl1List {
- if item["fttype"].(int64) == 0 {
- _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- } else {
- _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- }
- }
- err := tx.Commit()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func Decimal(value float64) float64 {
- value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
- return value
- }
- func UpdateDailyData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- pid := parammaps.Get("pid").ValueDefaultStr("0")
- weight := parammaps.Get("weight").ValueDefaultFloat64(0)
- sort := parammaps.Get("sort").ValueDefaultStr("0")
- location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
- date := parammaps.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-0:", err)
- appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
- return
- }
- if count > 0 {
- appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
- return
- }
- tx.Begin()
- if location == 0 {
- fid := parammaps.Get("fid").ValueStr()
- downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
- if err != nil {
- logs.Error("UpdateDailyData-error-1:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
- if err != nil {
- logs.Error("UpdateDailyData-error-1:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- actualWeight := weight - num
- _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-2:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-3:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-4:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-5:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
- downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
- and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
- lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- // actual := actualWeight / float64(len(downloadedplanList))
- for _, item := range downloadedplanList {
- itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- actual := itemLweight / lweight * actualWeight
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-6:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-7:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-8:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-9:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- }
- } else {
- downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
- and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
- // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
- // if err != nil {
- // fmt.Println("Error:", err)
- // return
- // }
- for _, item := range downloadedplanList {
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-6:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
- item["lweight"], actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-7:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-8:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-9:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- }
- }
- } else {
- fbarid := parammaps.Get("fbarid").ValueStr()
- downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
- if err != nil {
- logs.Error("UpdateDailyData-error-10:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
- if err != nil {
- logs.Error("UpdateDailyData-error-1:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- actualWeight := weight - num
- _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-11:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
- downloadedplan[0]["lweight"], actualWeight, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-12:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
- where pid = ? `, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-13:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-14:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
- return
- }
- if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
- downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
- and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
- lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- for _, item := range downloadedplanList {
- itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
- if err != nil {
- fmt.Println("Error:", err)
- return
- }
- actual := itemLweight / lweight * actualWeight
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-6:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-7:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-8:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-9:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- }
- } else {
- downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
- and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
- for _, item := range downloadedplanList {
- // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
- // if err != nil {
- // fmt.Println("Error:", err)
- // return
- // }
- _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-6:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
- item["lweight"], actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-7:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, 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()
- if err != nil {
- logs.Error("UpdateDailyData-error-8:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
- if err != nil {
- logs.Error("UpdateDailyData-error-9:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
- return
- }
- }
- }
- }
- err = tx.Commit()
- if err != nil {
- logs.Error("UpdateDailyData-error-20:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetFormulaStatistics(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- parammaps := gofasion.NewFasion(string(dataByte))
- startTime := parammaps.Get("startTime").ValueStr()
- endTime := parammaps.Get("endTime").ValueStr()
- pastureId := parammaps.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
- if err != nil {
- logs.Error("GetFormulaStatistics-error-1:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
- return
- }
- var feedtemplet, dateList []string
- for _, f := range feedtempletList {
- feedtemplet = append(feedtemplet, f["tname"].(string))
- }
- layout := "2006-01-02"
- // s := "2023-05-01"
- // e := "2023-05-23"
- start, err := time.Parse(layout, startTime)
- if err != nil {
- fmt.Println(err)
- return
- }
- end, err := time.Parse(layout, endTime)
- if err != nil {
- fmt.Println(err)
- return
- }
- end = end.AddDate(0, 0, 1)
- for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
- dateList = append(dateList, d.Format("2006-01-02"))
- }
- downloadedplanList, err := tx.SQL(`select count(1) total,ft.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
- join feedtempletdate ft on ft.id = d.tempid and ft.date = d.mydate where d.mydate between ? and ? and d.lpplantype in(0,1) and d.iscompleted = 1 and d.pastureId= ?
- group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
- if err != nil {
- logs.Error("GetFormulaStatistics-error-2:", err)
- tx.Rollback()
- appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
- return
- }
- var data2 [][]interface{}
- for _, f := range feedtemplet {
- var data1 []interface{}
- for _, date := range dateList {
- exist := false
- for _, item := range downloadedplanList {
- if date == item["mydate"].(string) && f == item["tname"].(string) {
- data1 = append(data1, item["total"])
- exist = true
- break
- }
- }
- if !exist {
- data1 = append(data1, 0)
- }
- }
- data2 = append(data2, data1)
- }
- //前端让加的
- feedtemplet = append(feedtemplet, "")
- {
- var data1 []interface{}
- for _, f := range dateList {
- // f = f + "\n"
- fmt.Println(f)
- data1 = append(data1, 0)
- }
- data2 = append(data2, data1)
- }
- resp := make(map[string]interface{}, 0)
- resp["xdata"] = dateList
- resp["data1"] = feedtemplet
- resp["data2"] = data2
- appG.Response(http.StatusOK, e.SUCCESS, resp)
- }
- func GetPlanData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("plancount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
- for _, item := range arr {
- trgaddressList := []string{}
- if _, ok := item["trgaddress"]; ok {
- trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
- for _, str := range trgaddressList1 {
- if str != "" {
- trgaddressList = append(trgaddressList, str)
- }
- }
- }
- item["trgaddressList"] = trgaddressList
- }
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- }
- // var wg sync.WaitGroup
- // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- // wg.Add(1)
- // go func(value map[string]interface{}) {
- // defer wg.Done()
- // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
- // }(value)
- // }
- // wg.Wait()
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func PostPlanData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- logging.Info("PostRJSBData err: ", string(dataByte))
- s_params := make([]interface{}, 0)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
- if !fsion.HasKey("parammaps") {
- appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- return
- }
- parammaps := fsion.Get("parammaps")
- // paramslist := strings.Split(p, ",")
- // if len(paramslist) > 0 && p != "" {
- // for _, value := range paramslist {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- // }
- // _, err = tx.SQL(sql, s_params...).Execute()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- s_params = make([]interface{}, 0)
- paramslist := strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- // if value == "ID" {
- // id := parammaps.Get("ID").ValueStr()
- // pastureid := parammaps.Get("pastureid").ValueStr()
- // 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
- // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- // for _, item := range datalist {
- // id = item["id"]
- // }
- // s_params = append(s_params, id)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- if value == "ID" {
- id := parammaps.Get("ID").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- 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
- d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- for _, item := range datalist {
- id = item["id"]
- }
- s_params = append(s_params, id)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func CheckFeedTrgaddress(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- fclassid := fsion.Get("fclassid").ValueStr()
- feedId := fsion.Get("feedId").ValueStr()
- backup1 := fsion.Get("backup1").ValueStr()
- backup1List := strings.Split(backup1, ",")
- tx := restful.Engine.NewSession()
- defer tx.Close()
- // if backup1 != "" {
- feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
- for _, feed := range feedList {
- if feed["backup1"] == "" {
- continue
- }
- feedbackupList := strings.Split(feed["backup1"], ",")
- for _, feedbackup := range feedbackupList {
- for _, backup := range backup1List {
- if feedbackup == backup {
- appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
- return
- }
- }
- }
- }
- // }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func ThiGetDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- if sqlnamestr == "getHomepageStr" {
- parammaps := fsion.Get("parammaps")
- pastureid := parammaps.Get("pastureid").ValueStr()
- var montimeList []float64
- var montime float64
- var wg sync.WaitGroup
- now := time.Now()
- for i := 0; i < 30; i++ {
- wg.Add(1)
- nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
- go func(nowstr string) {
- defer wg.Done()
- sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
- slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
- m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
- montimeList = append(montimeList, m)
- }(nowstr)
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- wg.Wait()
- for _, m := range montimeList {
- montime += m
- }
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- return
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- if sqlnamestr == "getFeedTrgaddressList" {
- for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
- trgaddressList := []string{}
- for _, str := range trgaddressList1 {
- if str != "" {
- trgaddressList = append(trgaddressList, str)
- }
- }
- item["trgaddressList"] = trgaddressList
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // func ToggleCcount(c *gin.Context) {
- // appG := app.Gin{C: c}
- // dataByte, _ := ioutil.ReadAll(c.Request.Body)
- // fsion := gofasion.NewFasion(string(dataByte))
- // // 0 实际 1 软件
- // status := fsion.Get("status").ValueDefaultInt64(0)
- // pastureId := fsion.Get("pastureId").ValueStr()
- // tx := restful.Engine.NewSession()
- // err := tx.Begin()
- // defer func() {
- // switch {
- // case err != nil:
- // logging.Error("tx.Begin 事务启动失败__error:", err)
- // if tx != nil {
- // tx.Rollback()
- // }
- // default:
- // if tx != nil {
- // err = tx.Commit()
- // }
- // }
- // if tx != nil {
- // tx.Close()
- // }
- // }()
- // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // for _, bar := range barList {
- // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist {
- // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // }
- // if status == 0 {
- // tx.Exec(`update feedp set ccount = actualcount `)
- // }else{
- // tx.Exec(`update feedp set ccount = softccount `)
- // }
- // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // for _, feedpData :=range feedpList{
- // var feedpargs []interface{}
- // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
- // if _, ok := feedpData["ftname"]; ok {
- // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
- // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
- // } else {
- // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- // }
- // if _, ok := feedpData["ptsfname"]; ok {
- // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
- // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
- // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
- // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
- // } else {
- // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- // }
- // upFeedpSql += " where barname = ? and pastureid = ? "
- // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
- // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist1 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist2 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist3 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist4 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist5 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // if !exist6 {
- // _, 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) `,
- // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // }
- // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
- // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
- // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- // and pastureid = ? and times = ?`
- // var fpdargs1 []interface{}
- // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs2 []interface{}
- // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs3 []interface{}
- // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs4 []interface{}
- // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs5 []interface{}
- // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // var fpdargs6 []interface{}
- // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
- // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- // 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()
- // if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- // return
- // }
- // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- // upFpdetailList := make([]*upFpdetail, 0)
- // for _, newfpd := range newList {
- // for _, oldfpd := range oldFpdList {
- // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- // var oldweight, newweight float64
- // if oldfpd["weight"] != nil {
- // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- // }
- // if newfpd["weight"] != nil {
- // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- // }
- // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- // upFpdetailList = append(upFpdetailList, &upFpdetail{
- // Old: oldweight,
- // New: newweight,
- // Times: newfpd["times"].(int64),
- // Ptid: newfpd["ptid"].(int64),
- // Fweight: fweight,
- // Id: oldfpd["id"].(int64),
- // })
- // break
- // }
- // }
- // }
- // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
- // }
- // appG.Response(http.StatusOK, e.SUCCESS, nil)
- // }
- func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
- feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
- if err != nil {
- return err
- }
- for _, item := range feedpList {
- // if item["ftid"].(string) != data["ftid"].(string) {
- _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
- if err != nil {
- return err
- }
- _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
- WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
- if err != nil {
- return err
- }
- // }
- }
- return nil
- }
- func PostPlanDatas(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- logging.Info("PostRJSBDatas err: ", string(dataByte))
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- pastureId := fsions.Get("pastureid").ValueStr()
- // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
- // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
- // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
- // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
- for _, parammaps := range fsions.Get("arrList").Array() {
- fmt.Println(parammaps.Json())
- if parammaps.Json() == "null" {
- continue
- }
- // if !fsion.HasKey("arrList") {
- // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- // return
- // continue
- // }
- // parammaps := fsion.Get("arrList")
- s_params := make([]interface{}, 0)
- // paramslist := strings.Split(p, ",")
- // if len(paramslist) > 0 && p != "" {
- // for _, value := range paramslist {
- // if value == "pastureid" {
- // s_params = append(s_params, pastureId)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- // }
- // }
- // _, err = tx.SQL(sql, s_params...).Execute()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- s_params = make([]interface{}, 0)
- paramslist := strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- // if value == "ID" {
- // id := parammaps.Get("ID").ValueStr()
- // pastureid := parammaps.Get("pastureid").ValueStr()
- // 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
- // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- // if err != nil {
- // logging.Error("PostRJSBData err: ", err)
- // msg := geterrmsg(err.Error())
- // appG.Response(http.StatusOK, e.ERROR, msg)
- // return
- // }
- // for _, item := range datalist {
- // id = item["id"]
- // }
- // s_params = append(s_params, id)
- // } else {
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- // }
- if value == "pastureid" {
- s_params = append(s_params, pastureId)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- if value == "ID" {
- id := parammaps.Get("ID").ValueStr()
- pastureid := parammaps.Get("pastureid").ValueStr()
- 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
- d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
- if err != nil {
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- for _, item := range datalist {
- id = item["id"]
- }
- s_params = append(s_params, id)
- } else if value == "pastureid" {
- s_params = append(s_params, pastureId)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- if value == "pastureid" {
- s_params = append(s_params, pastureId)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func FpdBatchEdit(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- barList := fsions.Get("barList").Array()
- pastureid := fsions.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- 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
- join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- for _, barFsions := range barList {
- dataexcel := make(map[string]interface{}, 0)
- dataexcel["barname"] = barFsions.Get("barname").ValueStr()
- dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
- dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
- dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
- dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
- if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
- continue
- }
- dataexcel["1"] = barFsions.Get("times1").ValueStr()
- dataexcel["2"] = barFsions.Get("times2").ValueStr()
- dataexcel["3"] = barFsions.Get("times3").ValueStr()
- dataexcel["4"] = barFsions.Get("times4").ValueStr()
- dataexcel["5"] = barFsions.Get("times5").ValueStr()
- dataexcel["6"] = barFsions.Get("times6").ValueStr()
- ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !ftexist {
- fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
- tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist {
- _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- var feedpargs []interface{}
- upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
- if _, ok := dataexcel["ftname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
- upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
- upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- }
- if _, ok := dataexcel["ptsfname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
- upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
- upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- }
- upFeedpSql += " where barname = ? and pastureid = ? "
- feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
- _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist1 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist2 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist3 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist4 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist5 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- if !exist6 {
- _, 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) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- }
- upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
- where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
- ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
- and pastureid = ? and times = ?`
- var fpdargs1 []interface{}
- fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
- _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs2 []interface{}
- fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
- _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs3 []interface{}
- fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
- _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs4 []interface{}
- fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
- _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs5 []interface{}
- fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
- _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var fpdargs6 []interface{}
- fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
- dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
- dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
- _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
- 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()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
- // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
- upFpdetailList := make([]*upFpdetail, 0)
- for _, newfpd := range newList {
- for _, oldfpd := range oldFpdList {
- if oldfpd["id"].(int64) == newfpd["id"].(int64) {
- var oldweight, newweight float64
- if oldfpd["weight"] != nil {
- oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
- }
- if newfpd["weight"] != nil {
- newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
- }
- fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
- upFpdetailList = append(upFpdetailList, &upFpdetail{
- Old: oldweight,
- New: newweight,
- Times: newfpd["times"].(int64),
- Ptid: newfpd["ptid"].(int64),
- Fweight: fweight,
- Id: oldfpd["id"].(int64),
- })
- break
- }
- }
- }
- updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdBarSync(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- gm.UdBarSync(pastureid, pastureinfo.Werks)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdFeedSync(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- gm.UdFeedSync(pastureid, pastureinfo.Werks)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdFeedtempletPush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdUtirPush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdBarFeedRemainPush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func UdMaterialIssuePush(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- pastureid := fsions.Get("pastureId").ValueStr()
- date := fsions.Get("date").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return
- }
- gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func DelFeedTemplet(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- ftId := fsions.Get("ftId").ValueStr()
- // userId := fsions.Get("userId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
- return
- }
- // barIdList, err := tx.SQL(`select barid from feedp where ftid = ? `, ftId).QueryString()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
- // return
- // }
- _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
- return
- }
- _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
- return
- }
- count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
- if count > 0 {
- _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
- return
- }
- }
- _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
- return
- }
- // var barIdStr []string
- // for _, bar := range barIdList {
- // barIdStr = append(barIdStr, bar["barid"])
- // }
- // if len(barIdStr) > 0 {
- // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
- // return
- // }
- // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
- // return
- // }
- // now := time.Now()
- // for _, newFpd := range newFpdDataList {
- // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
- // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
- // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
- // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- // }
- // for _, newFeedp := range newFeedpList {
- // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
- // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
- // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
- // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
- // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
- // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
- // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
- // if err != nil {
- // logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- // return
- // }
- // }
- // }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
- data := fasion["parammaps"].(map[string]interface{})
- plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(0,1,2) ").Count()
- fmt.Println(err)
- plancount1, err := tx.SQL(`SELECT
- count( 1 )
- FROM
- (
- SELECT
- d.id
- FROM
- downloadedplan d
- JOIN downloadplandtl1 d1 ON d1.pid = d.id
- JOIN downloadplandtl1_exec d1e ON d1e.pid = d.id
- JOIN downloadplandtl2 d2 ON d2.pid = d.id
- WHERE
- d.mydate = ?
- AND d.havebutton = 0
- AND lpplantype IN ( 0, 1, 2 )
- AND ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id ) =
- ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.pid and (select count(1) from downloadplandtl2 where pid = dd2.pid and fname = dd2.fname ) = 1 )
- GROUP BY
- d.id
- ) d
- `,
- data["startTime"]).Count()
- fmt.Println(err)
- if plancount != plancount1 && number < 10 {
- number++
- ExecDataParam(fasion, CommonParamMap, ParamMap, nil, nil, tx)
- checkPlan(tx, fasion, CommonParamMap, ParamMap, number)
- }
- }
- func EditPlanSort(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- planIdStr := fsions.Get("planId").ValueStr()
- mydate := fsions.Get("mydate").ValueStr()
- sort := fsions.Get("sort").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- type downloadedplan struct {
- Id int64 `xorm:"id"`
- Sort int `xorm:"sort"`
- Pid int64 `xorm:"pid"`
- }
- planInfo := new(downloadedplan)
- err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- sort1, _ := strconv.Atoi(sort)
- if sort1 == planInfo.Sort {
- appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
- tx.Rollback()
- return
- }
- 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()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- if count1 == 0 {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
- return
- }
- 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()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- if count > 0 {
- tx.Rollback()
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
- return
- }
- if planInfo.Sort > sort1 {
- 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()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- var minSort, pidCount int
- for _, sort := range minSortList {
- minSort, _ = strconv.Atoi(sort["sort"])
- }
- planList := make([]*downloadedplan, 0)
- 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)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- planPid := planInfo.Pid
- planList1 := make([]*downloadedplan, 0)
- planList2 := make([]*downloadedplan, 0)
- for _, plan := range planList {
- if plan.Pid == planPid {
- pidCount++
- planList1 = append(planList1, plan)
- } else {
- planList2 = append(planList2, plan)
- }
- }
- planList1 = append(planList1, planList2...)
- for i, plan := range planList1 {
- _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- }
- } else {
- 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()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- var maxSort int
- for _, sort := range maxSortList {
- maxSort, _ = strconv.Atoi(sort["sort"])
- }
- planList := make([]*downloadedplan, 0)
- 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)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- planPid := planInfo.Pid
- planList1 := make([]*downloadedplan, 0)
- planList2 := make([]*downloadedplan, 0)
- for _, plan := range planList {
- if plan.Pid == planPid {
- // pidCount++
- planList1 = append(planList1, plan)
- } else {
- planList2 = append(planList2, plan)
- }
- }
- planList2 = append(planList2, planList1...)
- for i, plan := range planList2 {
- _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- }
- }
- err = tx.Commit()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
- tx.Rollback()
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func EditDownloadedplanArtificial(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte))
- planIdStr := fsions.Get("planId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- planIdList := strings.Split(planIdStr, ",")
- for _, planId := range planIdList {
- _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? and havebutton != 1`, planId)
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
- tx.Rollback()
- return
- }
- }
- err := tx.Commit()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
- tx.Rollback()
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- type PlanRFID struct {
- RFID string `json:"RFID"`
- Lweight string `json:"lweight"`
- Gear string `json:"gear"`
- Speed string `json:"speed"`
- }
- func GetPlanRFID(c *gin.Context) {
- appG := app.Gin{C: c}
- RFIDStr := c.Query("RFID")
- planRFIDList := make([]*PlanRFID, 0)
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "1411.1",
- Gear: "1",
- Speed: "10",
- })
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "1322.1",
- Gear: "1",
- Speed: "10",
- })
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "1904.1",
- Gear: "1",
- Speed: "10",
- })
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "1870.1",
- Gear: "1",
- Speed: "10",
- })
- planRFIDList = append(planRFIDList, &PlanRFID{
- RFID: RFIDStr,
- Lweight: "2041.1",
- Gear: "1",
- Speed: "10",
- })
- appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
- }
- type tmrEquipmentMuster struct {
- A string
- N string
- }
- func GetTmrEquipmentMuster(c *gin.Context) {
- appG := app.Gin{C: c}
- id := c.Query("id")
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
- if err != nil {
- logs.Error(err)
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
- for _, data := range dataList {
- json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
- for _, g := range tmrEquipmentMusterList {
- a, _ := strconv.ParseFloat(g.A, 64)
- n, _ := strconv.ParseFloat(g.N, 64)
- a1, n1 := ddmmtoddd(a, n)
- g.A = fmt.Sprintf("%f", n1)
- g.N = fmt.Sprintf("%f", a1)
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
- }
- func ddmmtoddd(lng, lat float64) (float64, float64) {
- lngDegree := fmt.Sprintf("%f", lng/100)
- lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
- lngDegreeInt := int(lngDegreefloat * 1000000)
- dd := lngDegreeInt / 100 * 100 / 60
- fmt.Println(dd)
- lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
- latDegree := fmt.Sprintf("%f", lat/100)
- // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
- latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
- latDegreeInt := int(latDegreefloat * 1000000)
- latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
- a, _ := strconv.ParseFloat(lngStr, 64)
- b, _ := strconv.ParseFloat(latStr, 64)
- return coordtransform.WGS84toGCJ02(b, a)
- }
|