ops.go 231 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "path"
  12. "regexp"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. "tmr-watch/conf/setting"
  19. "tmr-watch/http/handle/restful"
  20. "tmr-watch/module"
  21. "tmr-watch/pkg/app"
  22. "tmr-watch/pkg/e"
  23. "tmr-watch/pkg/logging"
  24. "github.com/360EntSecGroup-Skylar/excelize"
  25. "github.com/Anderson-Lu/gofasion/gofasion"
  26. "github.com/astaxie/beego/logs"
  27. "github.com/gin-gonic/gin"
  28. "github.com/tealeg/xlsx"
  29. "github.com/xormplus/xorm"
  30. )
  31. // @Summary 根据SQL执行得到数据集
  32. // @Tags getData
  33. // @Accept json
  34. // @Produce json
  35. // @Param sql query string true "sql"
  36. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  37. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  38. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  39. // @Router /data/getdata [POST]
  40. func GetData(c *gin.Context) {
  41. appG := app.Gin{C: c}
  42. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  43. fsion := gofasion.NewFasion(string(dataByte))
  44. sqlstr := fsion.Get("sql").ValueStr()
  45. offset := fsion.Get("offset").ValueDefaultInt(0)
  46. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  47. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  48. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  49. if err != nil {
  50. appG.Response(http.StatusOK, e.ERROR, err.Error())
  51. } else {
  52. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  53. }
  54. }
  55. func Testpartitions(c *gin.Context) {
  56. appG := app.Gin{C: c}
  57. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  58. fsion := gofasion.NewFasion(string(dataByte))
  59. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  60. user := fsion.Get("user").ValueStr() //获取新数据库用户
  61. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  62. host := fsion.Get("host").ValueStr() //获取新数据库名称
  63. port := fsion.Get("port").ValueStr() //获取新数据库名称
  64. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  65. if sqls == nil || err1 != nil {
  66. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  67. }
  68. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  69. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  70. mydb, err := sql.Open("mysql", connecting) //连接新连接
  71. if err != nil {
  72. println("err1", err.Error())
  73. }
  74. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  75. if err != nil {
  76. println("err2", err.Error())
  77. }
  78. mydb.Close()
  79. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  80. mydb, err = sql.Open("mysql", connecting)
  81. if err != nil {
  82. println("err3", err.Error())
  83. }
  84. defer mydb.Close()
  85. if err == nil {
  86. mydb.SetMaxOpenConns(10)
  87. mydb.SetMaxIdleConns(10)
  88. }
  89. errmsg := ""
  90. if err == nil {
  91. //tx ,_ :=mydb.Begin()
  92. for _, sqlstr := range sqlstrs {
  93. //println("sqlstr---",sqlstr)
  94. if sqlstr == "" {
  95. continue
  96. }
  97. _, err = mydb.Exec(sqlstr)
  98. if err != nil {
  99. println("err4", err.Error())
  100. errmsg = err.Error()
  101. //err1 :=tx.Rollback()
  102. }
  103. }
  104. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  105. //err =tx.Commit()
  106. }
  107. if errmsg == "" {
  108. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  109. } else {
  110. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  111. }
  112. }
  113. func TestData(c *gin.Context) {
  114. appG := app.Gin{C: c}
  115. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  116. fsion := gofasion.NewFasion(string(dataByte))
  117. sqlstr := fsion.Get("sql").ValueStr()
  118. token := ""
  119. if tempv, exists := c.Get("jwt_username"); exists {
  120. token = tempv.(string)
  121. }
  122. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  123. }
  124. // @Summary 根据APISQL表中SQL执行得到数据集
  125. // @Tags GetDataByName
  126. // @Accept json
  127. // @Produce json
  128. // @Param sqlname body string true "sqlname"
  129. // @Param offset body int true "offset"
  130. // @Param pagecount body int true "pagecount"
  131. // @Param returntype body string true "returntype"
  132. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  133. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  134. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  135. // @Router /data/GetDataByName [POST]
  136. func GetDataByName(c *gin.Context) {
  137. appG := app.Gin{C: c}
  138. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  139. fsion := gofasion.NewFasion(string(dataByte))
  140. sqlnamestr := fsion.Get("name").ValueStr()
  141. offset := fsion.Get("offset").ValueDefaultInt(0)
  142. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  143. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  144. tx := restful.Engine.NewSession()
  145. err := tx.Begin()
  146. defer func() {
  147. switch {
  148. case err != nil:
  149. logging.Error("tx.Begin 事务启动失败__error:", err)
  150. if tx != nil {
  151. tx.Rollback()
  152. }
  153. default:
  154. if tx != nil {
  155. err = tx.Commit()
  156. }
  157. }
  158. if tx != nil {
  159. tx.Close()
  160. }
  161. }()
  162. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  163. if sql != "" {
  164. s_params := make([]interface{}, 0)
  165. if fsion.HasKey("parammaps") {
  166. parammaps := fsion.Get("parammaps")
  167. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  168. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  169. }
  170. paramslist := strings.Split(p, ",")
  171. if len(paramslist) > 0 && p != "" {
  172. for _, value := range paramslist {
  173. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  174. if tempv, exists := c.Get("jwt_username"); exists {
  175. s_params = append(s_params, tempv.(string))
  176. } else {
  177. s_params = append(s_params, "")
  178. }
  179. } else {
  180. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  181. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  182. // tmrNameList := []string{}
  183. // for _, tmr := range tmrArray {
  184. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  185. // }
  186. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  187. // } else {
  188. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  189. // }
  190. }
  191. }
  192. }
  193. } else if fsion.HasKey("params") {
  194. params := fsion.Get("params").Array()
  195. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  196. for _, v_params := range params {
  197. s_params = append(s_params, v_params.ValueStr())
  198. }
  199. }
  200. if returntype == "xlsx" {
  201. var xlsxfile *xlsx.File
  202. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  203. //c.File("c:/dd.xlsx")
  204. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  205. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  206. c.Header("Content-Transfer-Encoding", "binary")
  207. _ = xlsxfile.Write(c.Writer)
  208. } else {
  209. if sqlnamestr == "getHomepageStr" {
  210. parammaps := fsion.Get("parammaps")
  211. pastureid := parammaps.Get("pastureid").ValueStr()
  212. var montimeList []float64
  213. var montime float64
  214. var wg sync.WaitGroup
  215. now := time.Now()
  216. for i := 0; i < 30; i++ {
  217. wg.Add(1)
  218. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  219. go func(nowstr string) {
  220. defer wg.Done()
  221. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  222. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  223. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  224. montimeList = append(montimeList, m)
  225. }(nowstr)
  226. }
  227. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  228. if err != nil {
  229. logging.Error("GetDataByName err: ", err)
  230. msg := geterrmsg(err.Error())
  231. appG.Response(http.StatusOK, e.ERROR, msg)
  232. }
  233. wg.Wait()
  234. for _, m := range montimeList {
  235. montime += m
  236. }
  237. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  238. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  239. return
  240. }
  241. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  242. if err != nil {
  243. logging.Error("GetDataByName err: ", err)
  244. msg := geterrmsg(err.Error())
  245. appG.Response(http.StatusOK, e.ERROR, msg)
  246. } else {
  247. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  248. }
  249. }
  250. } else {
  251. appG.Response(http.StatusOK, e.SUCCESS, nil)
  252. }
  253. }
  254. // @Summary 根据APISQL表中SQL执行得到数据集
  255. // @Tags GetDataByName
  256. // @Accept json
  257. // @Produce json
  258. // @Param sqlname body string true "sqlname"
  259. // @Param offset body int true "offset"
  260. // @Param pagecount body int true "pagecount"
  261. // @Param returntype body string true "returntype"
  262. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  263. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  264. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  265. // @Router /data/GetDataByName [POST]
  266. func GetDataBySqlIN(c *gin.Context) {
  267. appG := app.Gin{C: c}
  268. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  269. fsion := gofasion.NewFasion(string(dataByte))
  270. sqlnamestr := fsion.Get("name").ValueStr()
  271. offset := fsion.Get("offset").ValueDefaultInt(0)
  272. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  273. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  274. tx := restful.Engine.NewSession()
  275. err := tx.Begin()
  276. defer func() {
  277. switch {
  278. case err != nil:
  279. logging.Error("tx.Begin 事务启动失败__error:", err)
  280. if tx != nil {
  281. tx.Rollback()
  282. }
  283. default:
  284. if tx != nil {
  285. err = tx.Commit()
  286. }
  287. }
  288. if tx != nil {
  289. tx.Close()
  290. }
  291. }()
  292. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  293. if sql != "" {
  294. s_params := make([]interface{}, 0)
  295. if fsion.HasKey("parammaps") {
  296. parammaps := fsion.Get("parammaps")
  297. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  298. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  299. }
  300. paramslist := strings.Split(p, ",")
  301. if len(paramslist) > 0 && p != "" {
  302. for _, value := range paramslist {
  303. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  304. if tempv, exists := c.Get("jwt_username"); exists {
  305. s_params = append(s_params, tempv.(string))
  306. } else {
  307. s_params = append(s_params, "")
  308. }
  309. } else {
  310. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  311. }
  312. }
  313. }
  314. } else if fsion.HasKey("params") {
  315. params := fsion.Get("params").Array()
  316. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  317. for _, v_params := range params {
  318. s_params = append(s_params, v_params.ValueStr())
  319. }
  320. }
  321. if returntype == "xlsx" {
  322. var xlsxfile *xlsx.File
  323. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  324. //c.File("c:/dd.xlsx")
  325. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  326. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  327. c.Header("Content-Transfer-Encoding", "binary")
  328. _ = xlsxfile.Write(c.Writer)
  329. } else {
  330. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  331. if err != nil {
  332. logging.Error("GetDataByName err: ", err)
  333. msg := geterrmsg(err.Error())
  334. appG.Response(http.StatusOK, e.ERROR, msg)
  335. } else {
  336. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  337. }
  338. }
  339. } else {
  340. appG.Response(http.StatusOK, e.SUCCESS, nil)
  341. }
  342. }
  343. // 错误处理
  344. // 将报错信息处理成汉字
  345. func geterrmsg(errstr string) (msgstr string) {
  346. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  347. rs := []rune(errstr)
  348. if hzRegexp.MatchString(string(rs[0])) {
  349. msgstr = errstr
  350. return
  351. }
  352. if strings.Contains(errstr, "Duplicate entry") {
  353. strs := strings.Split(errstr, ` key '`)
  354. if len(strs) > 1 {
  355. if len(strs[len(strs)-1]) > 1 {
  356. errstr = "Duplicate entry :" + strs[len(strs)-1]
  357. }
  358. }
  359. }
  360. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  361. if err != nil {
  362. msgstr = errstr
  363. return
  364. }
  365. if msg == nil || len(msg) == 0 {
  366. var param []interface{}
  367. param = append(param, errstr, errstr)
  368. go func() {
  369. tx := restful.Engine.NewSession()
  370. err := tx.Begin()
  371. defer func() {
  372. switch {
  373. case err != nil:
  374. logging.Error("tx.Begin 事务启动失败__error:", err)
  375. if tx != nil {
  376. tx.Rollback()
  377. }
  378. default:
  379. if tx != nil {
  380. err = tx.Commit()
  381. }
  382. }
  383. if tx != nil {
  384. tx.Close()
  385. }
  386. }()
  387. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  388. if err != nil {
  389. logging.Error("insert into err_msg(err,msg) err", err)
  390. }
  391. }()
  392. msgstr = errstr
  393. } else {
  394. msgstr = msg[0]["msg"]
  395. }
  396. return
  397. }
  398. // @Summary 根据APISQL表中SQL执行得到数据集
  399. // @Tags GetDataByNameForm
  400. // @Accept json
  401. // @Produce json
  402. // @Param sqlname body json true "sqlname"
  403. // @Param offset query int true "offset"
  404. // @Param pagecount query int true "pagecount"
  405. // @Param returntype query string true "returntype"
  406. // @Param s formData json true "ss"
  407. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  408. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  409. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  410. // @Router /data/GetDataByNameForm [POST]
  411. func GetDataByNameForm(c *gin.Context) {
  412. appG := app.Gin{C: c}
  413. //sqlnamestr := c.PostForm("measureNumber")
  414. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  415. //fsion := gofasion.NewFasion(string(dataByte))
  416. //sqlnamestr := fsion.Get("name").ValueStr()
  417. //offset := fsion.Get("offset").ValueInt()
  418. //pagecount := fsion.Get("pagecount").ValueInt()
  419. //returntype := fsion.Get("returntype").ValueStr()
  420. //params := fsion.Get("params").Array()
  421. c.Request.ParseForm()
  422. params := c.Request.Form
  423. offset := 0
  424. pageSize_ := 0
  425. returntype := params.Get("page")
  426. if returntype == "" {
  427. returntype = "0"
  428. }
  429. if tempv, exists := c.Get("jwt_username"); exists {
  430. params.Set("JwtUserName", tempv.(string))
  431. } else {
  432. params.Set("JwtUserName", "")
  433. }
  434. sqlnamestr := params.Get("name")
  435. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  436. s_params := make([]interface{}, 0)
  437. if returntype == "1" {
  438. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  439. if error != nil {
  440. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  441. }
  442. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  443. if error != nil {
  444. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  445. }
  446. pageSize_ = pageSize
  447. offset = pageNum
  448. }
  449. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  450. paramslist := strings.Split(p, ",")
  451. if len(paramslist) > 0 && p != "" {
  452. for _, value := range paramslist {
  453. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  454. }
  455. }
  456. if sql != "" {
  457. if returntype == "xlsx" {
  458. var xlsxfile *xlsx.File
  459. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  460. c.Header("Content-Type", "application/octet-stream")
  461. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  462. c.Header("Content-Transfer-Encoding", "binary")
  463. _ = xlsxfile.Write(c.Writer)
  464. } else {
  465. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  466. if err != nil {
  467. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  468. } else {
  469. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  470. }
  471. }
  472. } else {
  473. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  474. }
  475. }
  476. // @Summary 递归获取所有
  477. // @Tags menu
  478. // @Accept json
  479. // @Produce json
  480. // @Param Ton query string true "Ton"
  481. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  482. // @Router /authdata/GetRoleMenus [GET]
  483. func GetRecuDataByName(c *gin.Context) {
  484. appG := app.Gin{C: c}
  485. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  486. fsion := gofasion.NewFasion(string(dataByte))
  487. sqlnamestr := fsion.Get("name").ValueStr()
  488. parentidname := fsion.Get("idname").ValueStr()
  489. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  490. params := make(map[string]interface{})
  491. s_params := make([]interface{}, 0)
  492. if fsion.HasKey("params") {
  493. for _, v_params := range fsion.Get("params").Array() {
  494. s_params = append(s_params, v_params.ValueStr())
  495. }
  496. params["params"] = s_params
  497. } else {
  498. jparams := fsion.Get("parammaps")
  499. paramslist := strings.Split(p, ",")
  500. if len(paramslist) > 0 && p != "" {
  501. for _, value := range paramslist {
  502. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  503. if tempv, exists := c.Get("jwt_username"); exists {
  504. params[value] = tempv.(string)
  505. } else {
  506. params[value] = ""
  507. }
  508. } else {
  509. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  510. }
  511. }
  512. }
  513. }
  514. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  515. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  516. if err != nil {
  517. appG.Response(http.StatusOK, e.ERROR, err.Error())
  518. }
  519. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  520. }
  521. // @Summary 根据APISQL表中SQL执行得到数据集
  522. // @Tags GetDataByNames
  523. // @Accept json
  524. // @Produce json
  525. // @RequestBody sqlname query string true "sqlname"
  526. // @Param offset query int true "offset"
  527. // @Param pagecount query int true "pagecount"
  528. // @Param returntype query string true "returntype"
  529. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  530. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  531. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  532. // @Router /data/GetDataByNames [POST]
  533. func GetDataByNames(c *gin.Context) {
  534. appG := app.Gin{C: c}
  535. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  536. fsion := gofasion.NewFasion(string(dataByte))
  537. sqlParams := fsion.Array()
  538. queryData := make(map[string]interface{})
  539. for _, v := range sqlParams {
  540. fsion2 := gofasion.NewFasion(v.Json())
  541. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  542. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  543. if sql == "" {
  544. errorm := make(map[string]interface{})
  545. errorm["code"] = e.ERROR
  546. errorm["message"] = "sql没找到"
  547. queryData[fsion2.Get("name").ValueStr()] = errorm
  548. continue
  549. } else if sql != "" {
  550. offset := fsion2.Get("offset").ValueInt()
  551. pagecount := fsion2.Get("pagecount").ValueInt()
  552. returntype := fsion2.Get("returntype").ValueStr()
  553. s_params := make([]interface{}, 0)
  554. if fsion2.HasKey("parammaps") {
  555. parammaps := fsion2.Get("parammaps")
  556. paramslist := strings.Split(p, ",")
  557. if len(paramslist) > 0 && p != "" {
  558. for _, value := range paramslist {
  559. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  560. if tempv, exists := c.Get("jwt_username"); exists {
  561. s_params = append(s_params, tempv.(string))
  562. } else {
  563. s_params = append(s_params, "")
  564. }
  565. } else {
  566. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  567. }
  568. }
  569. }
  570. } else if fsion2.HasKey("params") {
  571. params := fsion2.Get("params").Array()
  572. for _, v_params := range params {
  573. s_params = append(s_params, v_params.ValueStr())
  574. }
  575. }
  576. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  577. if err != nil {
  578. errorm := make(map[string]interface{})
  579. errorm["code"] = e.ERROR
  580. errorm["message"] = err.Error()
  581. queryData[fsion2.Get("name").ValueStr()] = errorm
  582. logging.Error("GetDataByNames err: ", err)
  583. continue
  584. } else {
  585. queryData[fsion2.Get("name").ValueStr()] = queryData1
  586. }
  587. }
  588. }
  589. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  590. }
  591. // @Summary 根据APISQL表中SQL执行得到数据集
  592. // @Tags PostDataByNameForm
  593. // @Accept json
  594. // @Produce json
  595. // @Param sqlname query string true "sqlname"
  596. // @Param offset query int true "offset"
  597. // @Param pagecount query int true "pagecount"
  598. // @Param returntype query string true "returntype"
  599. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  600. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  601. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  602. // @Router /data/PostDataByNameForm [POST]
  603. func PostDataByNameForm(c *gin.Context) {
  604. appG := app.Gin{C: c}
  605. c.Request.ParseForm()
  606. params := c.Request.Form
  607. sqlnamestr := params.Get("name")
  608. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  609. s_params := make([]interface{}, 0)
  610. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  611. paramslist := strings.Split(p, ",")
  612. if len(paramslist) > 0 {
  613. for _, value := range paramslist {
  614. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  615. }
  616. }
  617. if sql != "" {
  618. queryData, err := execDataBySql(sql, s_params)
  619. if err != nil {
  620. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  621. } else {
  622. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  623. }
  624. } else {
  625. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  626. }
  627. }
  628. // GetReportform 将数据集转换格式
  629. // @Tags PostDataByNameForm
  630. // @Accept json
  631. // @Produce json
  632. // @Param sqlname query string true "sqlname"
  633. // @Param offset query int true "offset"
  634. // @Param pagecount query int true "pagecount"
  635. // @Param returntype query string true "returntype"
  636. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  637. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  638. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  639. func GetReportform(c *gin.Context) {
  640. appG := app.Gin{C: c}
  641. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  642. fsion := gofasion.NewFasion(string(dataByte))
  643. sqlnamestr := fsion.Get("name").ValueStr()
  644. checked := fsion.Get("checked").ValueStr()
  645. offset := fsion.Get("offset").ValueDefaultInt(0)
  646. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  647. parammaps := fsion.Get("parammaps")
  648. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  649. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  650. tx := restful.Engine.NewSession()
  651. err := tx.Begin()
  652. defer func() {
  653. switch {
  654. case err != nil:
  655. if tx != nil {
  656. tx.Rollback()
  657. }
  658. default:
  659. if tx != nil {
  660. err = tx.Commit()
  661. }
  662. }
  663. if tx != nil {
  664. tx.Close()
  665. }
  666. }()
  667. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea)
  668. if err != nil {
  669. appG.Response(http.StatusOK, e.ERROR, err.Error())
  670. } else {
  671. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  672. }
  673. }
  674. // GetUpkeepPlan 保养计划
  675. func GetUpkeepPlan(c *gin.Context) {
  676. appG := app.Gin{C: c}
  677. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  678. fsion := gofasion.NewFasion(string(dataByte))
  679. sqlnamestr := fsion.Get("name").ValueStr()
  680. offset := fsion.Get("offset").ValueDefaultInt(0)
  681. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  682. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  683. month := fsion.Get("month").ValueDefaultStr("map")
  684. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  685. tx := restful.Engine.NewSession()
  686. err := tx.Begin()
  687. defer func() {
  688. switch {
  689. case err != nil:
  690. if tx != nil {
  691. tx.Rollback()
  692. }
  693. default:
  694. if tx != nil {
  695. err = tx.Commit()
  696. }
  697. }
  698. if tx != nil {
  699. tx.Close()
  700. }
  701. }()
  702. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  703. if sql != "" {
  704. s_params := make([]interface{}, 0)
  705. if fsion.HasKey("parammaps") {
  706. parammaps := fsion.Get("parammaps")
  707. paramslist := strings.Split(p, ",")
  708. if len(paramslist) > 0 && p != "" {
  709. for _, value := range paramslist {
  710. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  711. if tempv, exists := c.Get("jwt_username"); exists {
  712. s_params = append(s_params, tempv.(string))
  713. } else {
  714. s_params = append(s_params, "")
  715. }
  716. } else {
  717. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  718. }
  719. }
  720. }
  721. } else if fsion.HasKey("params") {
  722. params := fsion.Get("params").Array()
  723. for _, v_params := range params {
  724. s_params = append(s_params, v_params.ValueStr())
  725. }
  726. }
  727. if returntype == "xlsx" {
  728. var xlsxfile *xlsx.File
  729. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  730. //c.File("c:/dd.xlsx")
  731. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  732. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  733. c.Header("Content-Transfer-Encoding", "binary")
  734. _ = xlsxfile.Write(c.Writer)
  735. } else {
  736. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  737. if err != nil {
  738. appG.Response(http.StatusOK, e.ERROR, err.Error())
  739. } else {
  740. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  741. if v, ok := value["id"]; ok {
  742. //month = "2020-03"
  743. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  744. if seviceplans != nil {
  745. for _, va := range seviceplans { //根据保养计划获取保养单
  746. //day,_ :=strconv.Atoi(va["day"])
  747. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  748. //buk := make(map[string]map[string]string)
  749. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  750. jstr := ""
  751. if bu["plantime"][8:9] == "0" {
  752. jstr = "m" + bu["plantime"][9:]
  753. } else {
  754. jstr = "m" + bu["plantime"][8:]
  755. }
  756. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  757. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  758. } else {
  759. if bu["flowCompeleted"] >= "2" {
  760. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  761. } else {
  762. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  763. }
  764. }
  765. }
  766. }
  767. }
  768. }
  769. }
  770. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  771. }
  772. }
  773. } else {
  774. appG.Response(http.StatusOK, e.SUCCESS, nil)
  775. }
  776. }
  777. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  778. // todo 优化性能 children统一查询
  779. // @Tags PostDataByNameForm
  780. // @Accept json
  781. // @Produce json
  782. // @Param sqlname query string true "sqlname"
  783. // @Param offset query int true "offset"
  784. // @Param pagecount query int true "pagecount"
  785. // @Param returntype query string true "returntype"
  786. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  787. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  788. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  789. func GetArrList(c *gin.Context) {
  790. appG := app.Gin{C: c}
  791. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  792. fsion := gofasion.NewFasion(string(dataByte))
  793. sqlnamestr := fsion.Get("name").ValueStr()
  794. sqlnamestr1 := fsion.Get("name1").ValueStr()
  795. offset := fsion.Get("offset").ValueDefaultInt(0)
  796. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  797. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  798. month := fsion.Get("month").ValueDefaultStr("map")
  799. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  800. tx := restful.Engine.NewSession()
  801. err := tx.Begin()
  802. defer func() {
  803. switch {
  804. case err != nil:
  805. if tx != nil {
  806. tx.Rollback()
  807. }
  808. default:
  809. if tx != nil {
  810. err = tx.Commit()
  811. }
  812. }
  813. if tx != nil {
  814. tx.Close()
  815. }
  816. }()
  817. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  818. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  819. if sql != "" {
  820. s_params := make([]interface{}, 0)
  821. if fsion.HasKey("parammaps") {
  822. parammaps := fsion.Get("parammaps")
  823. paramslist := strings.Split(p, ",")
  824. if len(paramslist) > 0 && p != "" {
  825. for _, value := range paramslist {
  826. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  827. if tempv, exists := c.Get("jwt_username"); exists {
  828. s_params = append(s_params, tempv.(string))
  829. } else {
  830. s_params = append(s_params, "")
  831. }
  832. } else {
  833. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  834. }
  835. }
  836. }
  837. }
  838. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  839. if err != nil {
  840. appG.Response(http.StatusOK, e.ERROR, err.Error())
  841. } else {
  842. paramslist1 := strings.Split(p1, ",")
  843. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  844. s_params1 := make([]interface{}, 0)
  845. if len(paramslist1) > 0 && p1 != "" {
  846. for _, v := range paramslist1 {
  847. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  848. }
  849. }
  850. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  851. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  852. }
  853. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  854. }
  855. } else {
  856. appG.Response(http.StatusOK, e.SUCCESS, nil)
  857. }
  858. }
  859. func GetAccount(c *gin.Context) {
  860. appG := app.Gin{C: c}
  861. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  862. fsion := gofasion.NewFasion(string(dataByte))
  863. sqlnamestr := fsion.Get("name").ValueStr()
  864. offset := fsion.Get("offset").ValueDefaultInt(0)
  865. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  866. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  867. tx := restful.Engine.NewSession()
  868. err := tx.Begin()
  869. defer func() {
  870. switch {
  871. case err != nil:
  872. logging.Error("tx.Begin 事务启动失败__error:", err)
  873. if tx != nil {
  874. tx.Rollback()
  875. }
  876. default:
  877. if tx != nil {
  878. err = tx.Commit()
  879. }
  880. }
  881. if tx != nil {
  882. tx.Close()
  883. }
  884. }()
  885. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  886. if sql != "" {
  887. s_params := make([]interface{}, 0)
  888. if fsion.HasKey("parammaps") {
  889. parammaps := fsion.Get("parammaps")
  890. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  891. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  892. }
  893. paramslist := strings.Split(p, ",")
  894. if len(paramslist) > 0 && p != "" {
  895. for _, value := range paramslist {
  896. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  897. if tempv, exists := c.Get("jwt_username"); exists {
  898. s_params = append(s_params, tempv.(string))
  899. } else {
  900. s_params = append(s_params, "")
  901. }
  902. } else {
  903. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  904. }
  905. }
  906. }
  907. } else if fsion.HasKey("params") {
  908. params := fsion.Get("params").Array()
  909. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  910. for _, v_params := range params {
  911. s_params = append(s_params, v_params.ValueStr())
  912. }
  913. }
  914. if returntype == "xlsx" {
  915. var xlsxfile *xlsx.File
  916. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  917. //c.File("c:/dd.xlsx")
  918. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  919. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  920. c.Header("Content-Transfer-Encoding", "binary")
  921. _ = xlsxfile.Write(c.Writer)
  922. } else {
  923. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  924. if err != nil {
  925. logging.Error("GetDataByName err: ", err)
  926. msg := geterrmsg(err.Error())
  927. appG.Response(http.StatusOK, e.ERROR, msg)
  928. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  929. } else {
  930. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  931. }
  932. }
  933. } else {
  934. appG.Response(http.StatusOK, e.SUCCESS, nil)
  935. }
  936. }
  937. // PostDataByName 根据APISQL表中SQL执行得到数据集
  938. // @Accept json
  939. // @Produce json
  940. // @Param sqlname query string true "sqlname"
  941. // @Param offset query int true "offset"
  942. // @Param pagecount query int true "pagecount"
  943. // @Param returntype query string true "returntype"
  944. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  945. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  946. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  947. // @Router /data/PostDataByName [POST]
  948. func PostDataByName(c *gin.Context) {
  949. appG := app.Gin{C: c}
  950. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  951. fsion := gofasion.NewFasion(string(dataByte))
  952. var err error
  953. queryData, err := module.PostDataByName(c, fsion)
  954. if err != nil {
  955. appG.Response(http.StatusOK, e.ERROR, err)
  956. return
  957. }
  958. var (
  959. keyWord string
  960. )
  961. switch fsion.Get("name").ValueStr() {
  962. case "insertFeedclass", "deleteFeedclass":
  963. keyWord = "feed"
  964. err = module.GroupCategorySync(keyWord, fsion)
  965. case "insertCowclass", "deleteCowclass":
  966. keyWord = "cow"
  967. err = module.GroupCategorySync(keyWord, fsion)
  968. default:
  969. }
  970. if err != nil {
  971. logging.Error(keyWord, err)
  972. }
  973. if queryData != nil {
  974. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  975. return
  976. }
  977. appG.Response(http.StatusOK, e.SUCCESS, nil)
  978. }
  979. //人脸识别/格润富德接口
  980. func GetRJSBData(c *gin.Context) {
  981. appG := app.Gin{C: c}
  982. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  983. fsion := gofasion.NewFasion(string(dataByte))
  984. sqlnamestr := fsion.Get("name").ValueStr()
  985. sqlnamestr1 := fsion.Get("name1").ValueStr()
  986. offset := fsion.Get("offset").ValueDefaultInt(0)
  987. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  988. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  989. month := fsion.Get("month").ValueDefaultStr("map")
  990. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  991. tx := restful.Engine.NewSession()
  992. err := tx.Begin()
  993. defer func() {
  994. switch {
  995. case err != nil:
  996. if tx != nil {
  997. tx.Rollback()
  998. }
  999. default:
  1000. if tx != nil {
  1001. err = tx.Commit()
  1002. }
  1003. }
  1004. if tx != nil {
  1005. tx.Close()
  1006. }
  1007. }()
  1008. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1009. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1010. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1011. if sql != "" {
  1012. s_params := make([]interface{}, 0)
  1013. if fsion.HasKey("parammaps") {
  1014. parammaps := fsion.Get("parammaps")
  1015. paramslist := strings.Split(p, ",")
  1016. if len(paramslist) > 0 && p != "" {
  1017. for _, value := range paramslist {
  1018. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1019. if tempv, exists := c.Get("jwt_username"); exists {
  1020. s_params = append(s_params, tempv.(string))
  1021. } else {
  1022. s_params = append(s_params, "")
  1023. }
  1024. } else {
  1025. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1026. }
  1027. }
  1028. }
  1029. }
  1030. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1031. if err != nil {
  1032. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1033. } else {
  1034. paramslist1 := strings.Split(p1, ",")
  1035. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1036. s_params1 := make([]interface{}, 0)
  1037. if len(paramslist1) > 0 && p1 != "" {
  1038. for _, v := range paramslist1 {
  1039. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1040. }
  1041. }
  1042. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1043. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1044. }
  1045. // var wg sync.WaitGroup
  1046. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1047. // wg.Add(1)
  1048. // go func(value map[string]interface{}) {
  1049. // defer wg.Done()
  1050. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1051. // }(value)
  1052. // }
  1053. // wg.Wait()
  1054. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1055. }
  1056. } else {
  1057. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1058. }
  1059. }
  1060. func PostRJSBData(c *gin.Context) {
  1061. appG := app.Gin{C: c}
  1062. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1063. fsion := gofasion.NewFasion(string(dataByte))
  1064. logging.Info("PostRJSBData err: ", string(dataByte))
  1065. s_params := make([]interface{}, 0)
  1066. tx := restful.Engine.NewSession()
  1067. err := tx.Begin()
  1068. defer func() {
  1069. switch {
  1070. case err != nil:
  1071. if tx != nil {
  1072. tx.Rollback()
  1073. }
  1074. default:
  1075. if tx != nil {
  1076. err = tx.Commit()
  1077. }
  1078. }
  1079. if tx != nil {
  1080. tx.Close()
  1081. }
  1082. }()
  1083. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1084. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1085. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1086. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1087. if !fsion.HasKey("parammaps") {
  1088. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1089. return
  1090. }
  1091. parammaps := fsion.Get("parammaps")
  1092. paramslist := strings.Split(p, ",")
  1093. if len(paramslist) > 0 && p != "" {
  1094. for _, value := range paramslist {
  1095. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1096. }
  1097. }
  1098. _, err = tx.SQL(sql, s_params...).Execute()
  1099. if err != nil {
  1100. logging.Error("PostRJSBData err: ", err)
  1101. msg := geterrmsg(err.Error())
  1102. appG.Response(http.StatusOK, e.ERROR, msg)
  1103. return
  1104. }
  1105. s_params = make([]interface{}, 0)
  1106. paramslist = strings.Split(p1, ",")
  1107. if len(paramslist) > 0 && p1 != "" {
  1108. for _, value := range paramslist {
  1109. // if value == "ID" {
  1110. // id := parammaps.Get("ID").ValueStr()
  1111. // pastureid := parammaps.Get("pastureid").ValueStr()
  1112. // 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
  1113. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1114. // if err != nil {
  1115. // logging.Error("PostRJSBData err: ", err)
  1116. // msg := geterrmsg(err.Error())
  1117. // appG.Response(http.StatusOK, e.ERROR, msg)
  1118. // return
  1119. // }
  1120. // for _, item := range datalist {
  1121. // id = item["id"]
  1122. // }
  1123. // s_params = append(s_params, id)
  1124. // } else {
  1125. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1126. // }
  1127. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1128. }
  1129. }
  1130. _, err = tx.SQL(sql1, s_params...).Execute()
  1131. if err != nil {
  1132. logging.Error("PostRJSBData1 err: ", err)
  1133. msg := geterrmsg(err.Error())
  1134. appG.Response(http.StatusOK, e.ERROR, msg)
  1135. return
  1136. }
  1137. s_params = make([]interface{}, 0)
  1138. paramslist = strings.Split(p2, ",")
  1139. if len(paramslist) > 0 && p2 != "" {
  1140. for _, value := range paramslist {
  1141. if value == "ID" {
  1142. id := parammaps.Get("ID").ValueStr()
  1143. pastureid := parammaps.Get("pastureid").ValueStr()
  1144. 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
  1145. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1146. if err != nil {
  1147. logging.Error("PostRJSBData err: ", err)
  1148. msg := geterrmsg(err.Error())
  1149. appG.Response(http.StatusOK, e.ERROR, msg)
  1150. return
  1151. }
  1152. for _, item := range datalist {
  1153. id = item["id"]
  1154. }
  1155. s_params = append(s_params, id)
  1156. } else {
  1157. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1158. }
  1159. }
  1160. }
  1161. _, err = tx.SQL(sql2, s_params...).Execute()
  1162. if err != nil {
  1163. logging.Error("PostRJSBData2 err: ", err)
  1164. msg := geterrmsg(err.Error())
  1165. appG.Response(http.StatusOK, e.ERROR, msg)
  1166. return
  1167. }
  1168. s_params = make([]interface{}, 0)
  1169. paramslist = strings.Split(p3, ",")
  1170. if len(paramslist) > 0 && p3 != "" {
  1171. for _, value := range paramslist {
  1172. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1173. }
  1174. }
  1175. _, err = tx.SQL(sql3, s_params...).Execute()
  1176. if err != nil {
  1177. logging.Error("PostRJSBData3 err: ", err)
  1178. msg := geterrmsg(err.Error())
  1179. appG.Response(http.StatusOK, e.ERROR, msg)
  1180. return
  1181. }
  1182. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1183. }
  1184. func PostRJSBDatas(c *gin.Context) {
  1185. appG := app.Gin{C: c}
  1186. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1187. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1188. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1189. tx := restful.Engine.NewSession()
  1190. err := tx.Begin()
  1191. defer func() {
  1192. switch {
  1193. case err != nil:
  1194. if tx != nil {
  1195. tx.Rollback()
  1196. }
  1197. default:
  1198. if tx != nil {
  1199. err = tx.Commit()
  1200. }
  1201. }
  1202. if tx != nil {
  1203. tx.Close()
  1204. }
  1205. }()
  1206. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1207. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1208. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1209. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1210. for _, fsion := range fsions {
  1211. if !fsion.HasKey("parammaps") {
  1212. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1213. return
  1214. }
  1215. parammaps := fsion.Get("parammaps")
  1216. s_params := make([]interface{}, 0)
  1217. paramslist := strings.Split(p, ",")
  1218. if len(paramslist) > 0 && p != "" {
  1219. for _, value := range paramslist {
  1220. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1221. }
  1222. }
  1223. _, err = tx.SQL(sql, s_params...).Execute()
  1224. if err != nil {
  1225. logging.Error("PostRJSBData err: ", err)
  1226. msg := geterrmsg(err.Error())
  1227. appG.Response(http.StatusOK, e.ERROR, msg)
  1228. return
  1229. }
  1230. s_params = make([]interface{}, 0)
  1231. paramslist = strings.Split(p1, ",")
  1232. if len(paramslist) > 0 && p1 != "" {
  1233. for _, value := range paramslist {
  1234. // if value == "ID" {
  1235. // id := parammaps.Get("ID").ValueStr()
  1236. // pastureid := parammaps.Get("pastureid").ValueStr()
  1237. // 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
  1238. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1239. // if err != nil {
  1240. // logging.Error("PostRJSBData err: ", err)
  1241. // msg := geterrmsg(err.Error())
  1242. // appG.Response(http.StatusOK, e.ERROR, msg)
  1243. // return
  1244. // }
  1245. // for _, item := range datalist {
  1246. // id = item["id"]
  1247. // }
  1248. // s_params = append(s_params, id)
  1249. // } else {
  1250. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1251. // }
  1252. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1253. }
  1254. }
  1255. _, err = tx.SQL(sql1, s_params...).Execute()
  1256. if err != nil {
  1257. logging.Error("PostRJSBData1 err: ", err)
  1258. msg := geterrmsg(err.Error())
  1259. appG.Response(http.StatusOK, e.ERROR, msg)
  1260. return
  1261. }
  1262. s_params = make([]interface{}, 0)
  1263. paramslist = strings.Split(p2, ",")
  1264. if len(paramslist) > 0 && p2 != "" {
  1265. for _, value := range paramslist {
  1266. if value == "ID" {
  1267. id := parammaps.Get("ID").ValueStr()
  1268. pastureid := parammaps.Get("pastureid").ValueStr()
  1269. 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
  1270. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1271. if err != nil {
  1272. logging.Error("PostRJSBData err: ", err)
  1273. msg := geterrmsg(err.Error())
  1274. appG.Response(http.StatusOK, e.ERROR, msg)
  1275. return
  1276. }
  1277. for _, item := range datalist {
  1278. id = item["id"]
  1279. }
  1280. s_params = append(s_params, id)
  1281. } else {
  1282. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1283. }
  1284. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1285. }
  1286. }
  1287. _, err = tx.SQL(sql2, s_params...).Execute()
  1288. if err != nil {
  1289. logging.Error("PostRJSBData2 err: ", err)
  1290. msg := geterrmsg(err.Error())
  1291. appG.Response(http.StatusOK, e.ERROR, msg)
  1292. return
  1293. }
  1294. s_params = make([]interface{}, 0)
  1295. paramslist = strings.Split(p3, ",")
  1296. if len(paramslist) > 0 && p3 != "" {
  1297. for _, value := range paramslist {
  1298. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1299. }
  1300. }
  1301. _, err = tx.SQL(sql3, s_params...).Execute()
  1302. if err != nil {
  1303. logging.Error("PostRJSBData3 err: ", err)
  1304. msg := geterrmsg(err.Error())
  1305. appG.Response(http.StatusOK, e.ERROR, msg)
  1306. return
  1307. }
  1308. }
  1309. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1310. }
  1311. // @Summary 根据APISQL表中SQL执行得到数据集
  1312. // @Tags ExecDataByConfig
  1313. // @Accept json
  1314. // @Produce json
  1315. // @Param sqlname query string true "sqlname"
  1316. // @Param offset query int true "offset"
  1317. // @Param pagecount query int true "pagecount"
  1318. // @Param returntype query string true "returntype"
  1319. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1320. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1321. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1322. // @Router /data/PostDataByName [POST]
  1323. func ExecDataByConfig(c *gin.Context) {
  1324. appG := app.Gin{C: c}
  1325. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1326. tempval_ := make(map[string]interface{})
  1327. tempCommon := make(map[string]interface{})
  1328. tempval := make([]map[string]interface{}, 0)
  1329. err := json.Unmarshal(dataByte, &tempval_)
  1330. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1331. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1332. if err != nil {
  1333. } else {
  1334. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1335. tempCommon = v
  1336. }
  1337. if v, ok := tempval_["data"].([]interface{}); ok {
  1338. for _, Tvalue := range v {
  1339. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1340. tempval = append(tempval, v1)
  1341. }
  1342. }
  1343. }
  1344. tx := restful.Engine.NewSession()
  1345. err := tx.Begin()
  1346. if err != nil {
  1347. logging.Error("tx.Begin 事务启动失败__error:", err)
  1348. }
  1349. defer func() {
  1350. switch {
  1351. case err != nil:
  1352. if tx != nil {
  1353. tx.Rollback()
  1354. }
  1355. default:
  1356. if tx != nil {
  1357. err = tx.Commit()
  1358. }
  1359. }
  1360. if tx != nil {
  1361. tx.Close()
  1362. }
  1363. }()
  1364. if err == nil {
  1365. if tempv, exists := c.Get("jwt_username"); exists {
  1366. tempCommon["jwt_username"] = tempv.(string)
  1367. }
  1368. for _, paramvalue := range tempval {
  1369. if _, ok := paramvalue["resultname"]; !ok {
  1370. paramvalue["resultname"] = paramvalue["name"]
  1371. }
  1372. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1373. if err != nil {
  1374. logging.Error("ExecDataParam error:", err)
  1375. break
  1376. }
  1377. }
  1378. if err == nil {
  1379. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1380. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1381. } else {
  1382. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1383. }
  1384. } else {
  1385. msg := geterrmsg(err.Error())
  1386. appG.Response(http.StatusOK, e.ERROR, msg)
  1387. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1388. }
  1389. }
  1390. }
  1391. if err != nil {
  1392. msg := geterrmsg(err.Error())
  1393. appG.Response(http.StatusOK, e.ERROR, msg)
  1394. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1395. }
  1396. }
  1397. func interfacetostring(val interface{}) string {
  1398. switch val.(type) {
  1399. case string:
  1400. ss := val.(string)
  1401. return ss
  1402. break
  1403. case int:
  1404. ss := val.(int)
  1405. return strconv.Itoa(ss)
  1406. break
  1407. case int64:
  1408. ss := val.(int64)
  1409. return strconv.FormatInt(ss, 10)
  1410. break
  1411. case float64:
  1412. ss := val.(float64)
  1413. return strconv.FormatFloat(ss, 'E', -1, 32)
  1414. break
  1415. }
  1416. return ""
  1417. }
  1418. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1419. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1420. tempstrb := strings.IndexAny(valuestring, "@")
  1421. tempstre := strings.IndexAny(valuestring, ".")
  1422. if tempstrb > -1 && tempstre > -1 {
  1423. for _, ParamMapList := range ParamMap {
  1424. if v, ok := ParamMapList["resultname"]; ok {
  1425. if v == valuestring[tempstrb+1:tempstre] {
  1426. if v1, ok := ParamMapList["resultmaps"]; ok {
  1427. if newA, ok := v1.([]map[string]interface{}); ok {
  1428. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1429. } else if newA, ok := v1.(map[string]interface{}); ok {
  1430. return interfacetostring(newA[valuestring[tempstre+1:]])
  1431. }
  1432. }
  1433. }
  1434. }
  1435. }
  1436. } else {
  1437. return valuestring
  1438. }
  1439. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1440. return strconv.FormatInt(int64(valuestring), 10)
  1441. }
  1442. return ""
  1443. }
  1444. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1445. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1446. tempstrb := strings.IndexAny(valuestring, "@")
  1447. tempstre := strings.IndexAny(valuestring, ".")
  1448. if tempstrb > -1 && tempstre > -1 {
  1449. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1450. if s, ok := v.(string); ok {
  1451. return s
  1452. } else if s, ok := v.(float64); ok {
  1453. return strconv.FormatFloat(s, 'f', -1, 64)
  1454. // return strconv.FormatInt(int64(s), 10)
  1455. }
  1456. }
  1457. }
  1458. }
  1459. return ""
  1460. }
  1461. 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) {
  1462. sqlname := fasion["name"].(string)
  1463. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1464. if v, ok := fasion["type"]; ok {
  1465. sqltype = v.(string)
  1466. }
  1467. sql := ""
  1468. p := ""
  1469. s_params := make([]interface{}, 0)
  1470. if sqltype != "" {
  1471. sql, p = restful.GetSqlByName(sqlname, tx)
  1472. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1473. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1474. paramslist := strings.Split(p, ",")
  1475. if len(paramslist) > 0 && p != "" {
  1476. for _, value := range paramslist {
  1477. ss := ""
  1478. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1479. ids, err := setting.SnowIds.NextId()
  1480. if err != nil {
  1481. ids = time.Now().UnixNano()
  1482. logging.Info("create SnowIds err", err)
  1483. }
  1484. s_params = append(s_params, ids)
  1485. } else {
  1486. if ss == "" && CommonParamMap != nil {
  1487. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1488. ss = valuestring
  1489. tempstrb := strings.IndexAny(valuestring, "@")
  1490. tempstre := strings.IndexAny(valuestring, ".")
  1491. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1492. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1493. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1494. }
  1495. } else {
  1496. ss = ""
  1497. }
  1498. }
  1499. }
  1500. if ss == "" && ParentParamMap != nil {
  1501. ss = getParamValue_(v, value, ParentParamMap)
  1502. }
  1503. if ss == "" && sameParamMap != nil {
  1504. ss = getParamValue(v, value, sameParamMap)
  1505. }
  1506. if ss == "" && ParamMap != nil {
  1507. ss = getParamValue(v, value, ParamMap)
  1508. }
  1509. s_params = append(s_params, ss)
  1510. }
  1511. }
  1512. }
  1513. }
  1514. }
  1515. if sql == "" {
  1516. sqltype = ""
  1517. }
  1518. if sqltype == "s1" {
  1519. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1520. if v, ok := tempValParam.(map[string]interface{}); ok {
  1521. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1522. }
  1523. if err != nil {
  1524. return nil, err
  1525. }
  1526. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1527. if err != nil {
  1528. return nil, err
  1529. }
  1530. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1531. } else if sqltype == "sm" {
  1532. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1533. if v, ok := tempValParam.(map[string]interface{}); ok {
  1534. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1535. } else {
  1536. }
  1537. if err != nil {
  1538. return nil, err
  1539. }
  1540. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1541. if err != nil {
  1542. return nil, err
  1543. }
  1544. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1545. } else if sqltype == "v" {
  1546. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1547. if v, ok := tempValParam.(map[string]interface{}); ok {
  1548. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1549. } else {
  1550. }
  1551. if err != nil {
  1552. return nil, err
  1553. }
  1554. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1555. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1556. }
  1557. } else if sqltype == "e" {
  1558. tempVal_arrary := make([]map[string]interface{}, 0)
  1559. tempVal_map := make(map[string]interface{})
  1560. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1561. if err == nil {
  1562. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1563. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1564. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1565. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1566. return tempVal_arrary, err
  1567. }
  1568. return nil, err
  1569. } else {
  1570. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1571. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1572. if err != nil {
  1573. return nil, err
  1574. }
  1575. return nil, err
  1576. }
  1577. }
  1578. return nil, nil
  1579. }
  1580. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1581. var err error
  1582. subarray, ok := fasion["children"]
  1583. if ok {
  1584. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1585. tempVal_arrary := make([]map[string]interface{}, 0)
  1586. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1587. tempVal_ := make(map[string]interface{})
  1588. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1589. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1590. } else {
  1591. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1592. }
  1593. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1594. if err != nil {
  1595. return err
  1596. }
  1597. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1598. }
  1599. v.(map[string]interface{})["children"] = tempVal_arrary
  1600. }
  1601. }
  1602. return nil
  1603. }
  1604. // @Summary 删除图片
  1605. // @Tags RemovePicByName
  1606. // @Accept json
  1607. // @Produce json
  1608. // @Param sqlname query string true "sqlname"
  1609. // @Param offset query int true "offset"
  1610. // @Param pagecount query int true "pagecount"
  1611. // @Param returntype query string true "returntype"
  1612. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1613. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1614. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1615. // @Router /data/PostDataByName [POST]
  1616. func RemovePicByName(c *gin.Context) {
  1617. logging.Info("RemovePicByName ", c.Keys)
  1618. appG := app.Gin{C: c}
  1619. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1620. fsion := gofasion.NewFasion(string(dataByte))
  1621. sqlnamestr := fsion.Get("name").ValueStr()
  1622. picname := fsion.Get("picname").ValueStr()
  1623. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1624. params := fsion.Get("params").Array()
  1625. s_params := make([]interface{}, 0)
  1626. for _, v_params := range params {
  1627. s_params = append(s_params, v_params.ValueStr())
  1628. }
  1629. if sql != "" {
  1630. queryData, err := execDataBySql(sql, s_params)
  1631. if picname != "" {
  1632. // Destination
  1633. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1634. err := os.Remove(distPath) //删除文件test.txt
  1635. if err != nil {
  1636. //如果删除失败则输出 file remove Error!
  1637. fmt.Println("file remove Error!")
  1638. //输出错误详细信息
  1639. fmt.Printf("%s", err)
  1640. } else {
  1641. //如果删除成功则输出 file remove OK!
  1642. fmt.Print("file remove OK!")
  1643. }
  1644. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1645. err = os.Remove(distPath) //删除文件test.txt
  1646. if err != nil {
  1647. //如果删除失败则输出 file remove Error!
  1648. fmt.Println("file remove Error!")
  1649. //输出错误详细信息
  1650. fmt.Printf("%s", err)
  1651. } else {
  1652. //如果删除成功则输出 file remove OK!
  1653. fmt.Print("file remove OK!")
  1654. }
  1655. }
  1656. if err != nil {
  1657. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1658. } else {
  1659. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1660. }
  1661. } else {
  1662. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1663. }
  1664. }
  1665. // @Summary 删除文件
  1666. // @Tags RemoveFileByName
  1667. // @Accept json
  1668. // @Produce json
  1669. // @Param sqlname query string true "sqlname"
  1670. // @Param offset query int true "offset"
  1671. // @Param pagecount query int true "pagecount"
  1672. // @Param returntype query string true "returntype"
  1673. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1674. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1675. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1676. // @Router /data/PostDataByName [POST]
  1677. func RemoveFileByName(c *gin.Context) {
  1678. appG := app.Gin{C: c}
  1679. id := c.Param("id")
  1680. logging.Info("DownloadFile ", c.Keys, id)
  1681. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1682. if eqdoc == nil {
  1683. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1684. return
  1685. }
  1686. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1687. err = os.Remove(distPath) //删除文件test.txt
  1688. if err != nil {
  1689. //如果删除失败则输出 file remove Error!
  1690. fmt.Println("file remove Error!")
  1691. //输出错误详细信息
  1692. fmt.Printf("%s", err)
  1693. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1694. return
  1695. }
  1696. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1697. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1698. }
  1699. // @Summary 根据APISQL表中SQL执行得到数据集
  1700. // @Tags PostDataByName
  1701. // @Accept json
  1702. // @Produce json
  1703. // @Param sqlname query string true "sqlname"
  1704. // @Param offset query int true "offset"
  1705. // @Param pagecount query int true "pagecount"
  1706. // @Param returntype query string true "returntype"
  1707. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1708. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1709. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1710. // @Router /data/PostDataByName [POST]
  1711. func UpdateDataRelation(c *gin.Context) {
  1712. appG := app.Gin{C: c}
  1713. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1714. fsion := gofasion.NewFasion(string(dataByte))
  1715. tablename := fsion.Get("name").ValueStr()
  1716. dataname := fsion.Get("dataname").ValueStr()
  1717. datavalue := fsion.Get("datavalue").ValueStr()
  1718. valuename := fsion.Get("valuename").ValueStr()
  1719. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1720. values := fsion.Get("values").Array()
  1721. tx := restful.Engine.NewSession()
  1722. err := tx.Begin()
  1723. defer func() {
  1724. switch {
  1725. case err != nil:
  1726. if tx != nil {
  1727. tx.Rollback()
  1728. }
  1729. default:
  1730. if tx != nil {
  1731. err = tx.Commit()
  1732. }
  1733. }
  1734. if tx != nil {
  1735. tx.Close()
  1736. }
  1737. }()
  1738. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1739. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1740. d_params := make([]interface{}, 4)
  1741. d_params[0] = datavalue
  1742. s_params := ""
  1743. for _, v_values := range values {
  1744. d_params[1] = v_values.ValueStr()
  1745. if s_params == "" {
  1746. s_params = v_values.ValueStr()
  1747. } else {
  1748. s_params = s_params + "," + v_values.ValueStr()
  1749. }
  1750. d_params[2] = d_params[1]
  1751. d_params[3] = d_params[0]
  1752. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1753. if err != nil {
  1754. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1755. break
  1756. }
  1757. }
  1758. if s_params != "" {
  1759. deleteSqlstr := "delete from " + tablename + " " +
  1760. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1761. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1762. if err != nil {
  1763. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1764. } else if err == nil {
  1765. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1766. }
  1767. } else {
  1768. deleteSqlstr := "delete from " + tablename + " " +
  1769. " where " + dataname + " = " + datavalue
  1770. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1771. if err != nil {
  1772. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1773. } else if err == nil {
  1774. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1775. }
  1776. }
  1777. }
  1778. // @Summary 根据APISQL表中SQL执行得到数据集
  1779. // @Tags PostDatasByName
  1780. // @Accept json
  1781. // @Produce json
  1782. // @Param sqlname query string true "sqlname"
  1783. // @Param offset query int true "offset"
  1784. // @Param pagecount query int true "pagecount"
  1785. // @Param returntype query string true "returntype"
  1786. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1787. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1788. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1789. // @Router /data/PostDatasByName [POST]
  1790. func PostDataByNames(c *gin.Context) {
  1791. appG := app.Gin{C: c}
  1792. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1793. fsion := gofasion.NewFasion(string(dataByte))
  1794. sqlParams := fsion.Get("array").Array()
  1795. queryData := make(map[string]interface{})
  1796. for _, v := range sqlParams {
  1797. fsion2 := gofasion.NewFasion(v.Json())
  1798. ss := fsion2.Get("name")
  1799. aa := fsion2.Get("params")
  1800. fmt.Println(ss, aa)
  1801. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1802. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1803. if sql == "" {
  1804. errorm := make(map[string]interface{})
  1805. errorm["code"] = e.ERROR
  1806. errorm["message"] = "sql没有找到"
  1807. errorm["param"] = ""
  1808. queryData[fsion2.Get("name").ValueStr()] = errorm
  1809. continue
  1810. } else if sql != "" {
  1811. s_params := make([]interface{}, 0)
  1812. if fsion2.HasKey("parammaps") {
  1813. parammaps := fsion2.Get("parammaps")
  1814. paramslist := strings.Split(p, ",")
  1815. if len(paramslist) > 0 && p != "" {
  1816. for _, value := range paramslist {
  1817. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1818. if tempv, exists := c.Get("jwt_username"); exists {
  1819. s_params = append(s_params, tempv.(string))
  1820. } else {
  1821. s_params = append(s_params, "")
  1822. }
  1823. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1824. ids, err := setting.SnowIds.NextId()
  1825. if err != nil {
  1826. ids = time.Now().UnixNano()
  1827. logging.Info("create SnowIds err", err)
  1828. }
  1829. s_params = append(s_params, ids)
  1830. } else {
  1831. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1832. }
  1833. }
  1834. }
  1835. } else if fsion2.HasKey("params") {
  1836. params := fsion2.Get("params").Array()
  1837. //ids,err := setting.SnowIds.NextId()
  1838. //if err !=nil{
  1839. // ids = time.Now().UnixNano()
  1840. // logging.Info("create SnowIds err",err)
  1841. //}
  1842. //s_params = append(s_params, ids)
  1843. for _, v_params := range params {
  1844. s_params = append(s_params, v_params.ValueStr())
  1845. }
  1846. }
  1847. _, err := execDataBySql(sql, s_params)
  1848. if err != nil {
  1849. logging.Error("PostDataByName err: ", err)
  1850. errorm := make(map[string]interface{})
  1851. errorm["code"] = e.ERROR
  1852. errorm["message"] = err.Error()
  1853. errorm["param"] = s_params
  1854. queryData[fsion2.Get("name").ValueStr()] = errorm
  1855. continue
  1856. } else {
  1857. errorm := make(map[string]interface{})
  1858. errorm["code"] = e.SUCCESS
  1859. errorm["message"] = "success"
  1860. queryData[fsion2.Get("name").ValueStr()] = errorm
  1861. continue
  1862. }
  1863. } else {
  1864. errorm := make(map[string]interface{})
  1865. errorm["code"] = e.ERROR
  1866. errorm["message"] = "NO SQL"
  1867. errorm["param"] = ""
  1868. queryData[fsion2.Get("name").ValueStr()] = errorm
  1869. }
  1870. }
  1871. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1872. }
  1873. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1874. if offset > 0 {
  1875. offset = offset - 1
  1876. }
  1877. //if pagecount == 0 {
  1878. // pagecount = setting.AppSetting.PageSize
  1879. //}else if pagecount>setting.AppSetting.PageSize{
  1880. // pagecount = setting.AppSetting.PageSize
  1881. //}
  1882. if returntype == "list" {
  1883. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1884. return queryData, err
  1885. } else if returntype == "listlist" {
  1886. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1887. return queryData, err
  1888. } else {
  1889. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1890. return queryData, err
  1891. }
  1892. }
  1893. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1894. if offset > 0 {
  1895. offset = offset - 1
  1896. }
  1897. //if pagecount == 0 {
  1898. // pagecount = setting.AppSetting.PageSize
  1899. //}else if pagecount>setting.AppSetting.PageSize{
  1900. // pagecount = setting.AppSetting.PageSize
  1901. //}
  1902. if returntype == "list" {
  1903. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1904. return queryData, err
  1905. } else if returntype == "listlist" {
  1906. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1907. return queryData, err
  1908. } else {
  1909. fmt.Println(params)
  1910. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1911. return queryData, err
  1912. }
  1913. }
  1914. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1915. paramslist := strings.Split(Params, ",")
  1916. s_params := make([]interface{}, 0)
  1917. if isList {
  1918. for _, v_params := range thisParams["params"].([]interface{}) {
  1919. s_params = append(s_params, v_params)
  1920. }
  1921. } else {
  1922. paramslist := strings.Split(Params, ",")
  1923. if len(paramslist) > 0 && Params != "" {
  1924. for _, value := range paramslist {
  1925. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1926. }
  1927. }
  1928. }
  1929. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  1930. for _, queryData_ := range queryData {
  1931. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  1932. if isList {
  1933. if queryData_[idname] != nil {
  1934. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  1935. }
  1936. } else {
  1937. if queryData_[idname] != nil {
  1938. thisParams[idname] = queryData_[idname].(interface{})
  1939. }
  1940. if len(paramslist) > 0 && Params != "" {
  1941. s_params = make([]interface{}, 0)
  1942. for _, value := range paramslist {
  1943. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1944. }
  1945. }
  1946. }
  1947. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  1948. } else {
  1949. }
  1950. }
  1951. return queryData, err
  1952. }
  1953. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1954. queryData, err := restful.ExecQuery(sqlstr, params)
  1955. return queryData, err
  1956. }
  1957. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1958. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  1959. return queryData, err
  1960. }
  1961. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1962. queryData, err := restful.ExecQuery(sqlstr, params)
  1963. return queryData, err
  1964. }
  1965. // @Summary 导入excel文件到数据库,excel第一行作为参数
  1966. // @Tags ImportExcel
  1967. // @Accept json
  1968. // @Produce json
  1969. // @Param file query string true "文件名"
  1970. // @Param name header string true "执行sql的名字"
  1971. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1972. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1973. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1974. // @Router /data/ImportExcel [POST]
  1975. func ImportExcel(c *gin.Context) {
  1976. appG := app.Gin{C: c}
  1977. inputdata := ""
  1978. c.Request.ParseForm()
  1979. params := c.Request.Form
  1980. file, _, err := c.Request.FormFile("file")
  1981. if err != nil {
  1982. appG.Response(http.StatusOK, e.ERROR, err)
  1983. return
  1984. }
  1985. sqlnamestrs := params.Get("name")
  1986. sheetname := params.Get("sheetname")
  1987. pastureid := params.Get("pastureid")
  1988. //importParams := params.Get("importParams")
  1989. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  1990. // 必输项参数 (字符串格式 "field1,field2,field3")
  1991. requiredParams := params.Get("requiredParams")
  1992. // 日期参数
  1993. dateParams := params.Get("dateParams")
  1994. // 数字参数
  1995. numParams := params.Get("numParams")
  1996. //将字符串分割开
  1997. dateParamslist := strings.Split(dateParams, ",")
  1998. requiredParamslist := strings.Split(requiredParams, ",")
  1999. numParamslist := strings.Split(numParams, ",")
  2000. queryData := make([]interface{}, 0)
  2001. sqlslist := strings.Split(sqlnamestrs, ",")
  2002. xlsx1, err := excelize.OpenReader(file)
  2003. if err != nil {
  2004. fmt.Println(err)
  2005. return
  2006. }
  2007. ok := 0
  2008. error := 0
  2009. isdone := true
  2010. rows := xlsx1.GetRows(sheetname)
  2011. // 限制10000条,多余的截取掉
  2012. if len(rows) > 10000 {
  2013. rows = rows[:10000]
  2014. }
  2015. for i, row := range rows {
  2016. if i > 0 {
  2017. entry := make(map[string]interface{})
  2018. outentry := make(map[string]interface{})
  2019. for j, colCell := range rows[0] {
  2020. for k, colCell1 := range row {
  2021. if j == k {
  2022. outentry[colCell] = colCell1
  2023. entry[colCell] = colCell1
  2024. }
  2025. }
  2026. }
  2027. inputdata = ""
  2028. a := ""
  2029. fmt.Println(outentry, entry)
  2030. //校验日期格式
  2031. for _, v := range dateParamslist {
  2032. if v == "" {
  2033. continue
  2034. }
  2035. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2036. dtime, err := TransfTime(d.(string))
  2037. if err != nil {
  2038. a = strings.Trim(v, " ")
  2039. break
  2040. }
  2041. outentry[strings.Trim(v, " ")] = dtime
  2042. }
  2043. }
  2044. if a != "" {
  2045. outentry["error_msg"] = a + " 格式错误"
  2046. error++
  2047. queryData = append(queryData, outentry)
  2048. continue
  2049. }
  2050. a = ""
  2051. //校验必填格式
  2052. for _, v := range requiredParamslist {
  2053. if v == "" {
  2054. continue
  2055. }
  2056. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2057. a = strings.Trim(v, " ")
  2058. break
  2059. }
  2060. }
  2061. if a != "" {
  2062. outentry["error_msg"] = a + " 未填或格式错误"
  2063. error++
  2064. queryData = append(queryData, outentry)
  2065. continue
  2066. }
  2067. a = ""
  2068. //校验数字格式
  2069. for _, v := range numParamslist {
  2070. if v == "" {
  2071. continue
  2072. }
  2073. d, ok := outentry[strings.Trim(v, " ")]
  2074. if !ok || d == "" {
  2075. outentry[strings.Trim(v, " ")] = 0
  2076. } else {
  2077. var fl float64
  2078. switch d.(type) {
  2079. case string:
  2080. fl, err = strconv.ParseFloat(d.(string), 64)
  2081. }
  2082. if err != nil || fl < 0 {
  2083. a = strings.Trim(v, " ")
  2084. break
  2085. }
  2086. }
  2087. }
  2088. if a != "" {
  2089. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2090. error++
  2091. queryData = append(queryData, outentry)
  2092. continue
  2093. }
  2094. tx := restful.Engine.NewSession()
  2095. err := tx.Begin()
  2096. for _, sqlnamestr := range sqlslist {
  2097. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2098. paramslist := strings.Split(paramslists, ",")
  2099. if len(paramslist) > 0 {
  2100. s_params := make([]interface{}, 0)
  2101. for _, value := range paramslist {
  2102. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2103. if tempv, exists := c.Get("jwt_username"); exists {
  2104. s_params = append(s_params, tempv.(string))
  2105. } else {
  2106. s_params = append(s_params, "")
  2107. }
  2108. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2109. s_params = append(s_params, pastureid)
  2110. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2111. ids, err := setting.SnowIds.NextId()
  2112. if err != nil {
  2113. ids = time.Now().UnixNano()
  2114. logging.Info("create SnowIds err", err)
  2115. }
  2116. s_params = append(s_params, ids)
  2117. } else {
  2118. if outentry[strings.Trim(value, " ")] == nil {
  2119. s_params = append(s_params, "")
  2120. } else {
  2121. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2122. }
  2123. }
  2124. }
  2125. outentry["input"] = inputdata
  2126. fmt.Println(sql, s_params)
  2127. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2128. if err != nil {
  2129. if tx != nil {
  2130. tx.Rollback()
  2131. }
  2132. if tx != nil {
  2133. tx.Close()
  2134. }
  2135. msg := geterrmsg(err.Error())
  2136. outentry["error_msg"] = msg
  2137. error++
  2138. queryData = append(queryData, outentry)
  2139. isdone = true
  2140. break
  2141. } else {
  2142. if len(returnmsgmap1) > 0 {
  2143. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2144. if tx != nil {
  2145. tx.Rollback()
  2146. }
  2147. if tx != nil {
  2148. tx.Close()
  2149. }
  2150. msg := geterrmsg(va.(string))
  2151. outentry["error_msg"] = msg
  2152. error++
  2153. queryData = append(queryData, outentry)
  2154. isdone = true
  2155. break
  2156. }
  2157. }
  2158. isdone = false
  2159. }
  2160. }
  2161. }
  2162. switch {
  2163. case err != nil:
  2164. if tx != nil {
  2165. tx.Rollback()
  2166. }
  2167. default:
  2168. if tx != nil {
  2169. err = tx.Commit()
  2170. }
  2171. }
  2172. if tx != nil {
  2173. tx.Close()
  2174. }
  2175. }
  2176. if !isdone {
  2177. ok++
  2178. isdone = true
  2179. }
  2180. }
  2181. data := make(map[string]interface{})
  2182. data["result"] = queryData
  2183. data["success"] = ok
  2184. data["err_count"] = error
  2185. appG.Response(http.StatusOK, e.SUCCESS, data)
  2186. }
  2187. func TransfTime(timestr string) (string, error) {
  2188. if timestr == "" {
  2189. return time.Now().Format("2006-01-02"), nil
  2190. }
  2191. days, err := strconv.Atoi(timestr)
  2192. if err != nil {
  2193. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2194. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2195. }
  2196. _, err := time.Parse("2006-01-02", timestr)
  2197. if err != nil {
  2198. t, err := time.Parse("2006/01/02", timestr)
  2199. if err != nil {
  2200. t, err := time.Parse("2006.01.02", timestr)
  2201. if err != nil {
  2202. return "", err
  2203. } else {
  2204. return t.Format("2006-01-02"), nil
  2205. }
  2206. } else {
  2207. return t.Format("2006-01-02"), nil
  2208. }
  2209. } else {
  2210. return timestr, nil
  2211. }
  2212. }
  2213. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2214. times = times.AddDate(0, 0, days)
  2215. return times.Format("2006-01-02"), nil
  2216. }
  2217. func Createchart(c *gin.Context) {
  2218. appG := app.Gin{C: c}
  2219. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2220. fsion := gofasion.NewFasion(string(dataByte))
  2221. chart_name := fsion.Get("chart_name").ValueStr()
  2222. desc := fsion.Get("desc").ValueStr()
  2223. pastureid := fsion.Get("pastureid").ValueStr()
  2224. source_id := fsion.Get("source_id").ValueStr()
  2225. emp := fsion.Get("emp").ValueStr()
  2226. content := fsion.Get("content").Json()
  2227. var mapResult map[string]interface{}
  2228. err1 := json.Unmarshal([]byte(content), &mapResult)
  2229. if err1 != nil {
  2230. fmt.Println("JsonToMapDemo err: ", err1)
  2231. }
  2232. tx := restful.Engine.NewSession()
  2233. err := tx.Begin()
  2234. defer func() {
  2235. switch {
  2236. case err != nil:
  2237. logging.Error("tx.Begin 事务启动失败__error:", err)
  2238. if tx != nil {
  2239. tx.Rollback()
  2240. }
  2241. default:
  2242. if tx != nil {
  2243. err = tx.Commit()
  2244. }
  2245. }
  2246. if tx != nil {
  2247. tx.Close()
  2248. }
  2249. }()
  2250. ids, err := setting.SnowIds.NextId()
  2251. if err != nil {
  2252. ids = time.Now().UnixNano()
  2253. logging.Info("create SnowIds err", err)
  2254. }
  2255. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2256. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2257. if err != nil {
  2258. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2259. } else {
  2260. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2261. }
  2262. }
  2263. func Updatedashboard(c *gin.Context) {
  2264. appG := app.Gin{C: c}
  2265. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2266. fsion := gofasion.NewFasion(string(dataByte))
  2267. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2268. pastureid := fsion.Get("pastureid").ValueStr()
  2269. content := fsion.Get("content").Json()
  2270. var mapResult map[string]interface{}
  2271. err1 := json.Unmarshal([]byte(content), &mapResult)
  2272. if err1 != nil {
  2273. fmt.Println("JsonToMapDemo err: ", err1)
  2274. }
  2275. layout := mapResult["layout"]
  2276. tx := restful.Engine.NewSession()
  2277. err := tx.Begin()
  2278. defer func() {
  2279. switch {
  2280. case err != nil:
  2281. logging.Error("tx.Begin 事务启动失败__error:", err)
  2282. if tx != nil {
  2283. tx.Rollback()
  2284. }
  2285. default:
  2286. if tx != nil {
  2287. err = tx.Commit()
  2288. }
  2289. }
  2290. if tx != nil {
  2291. tx.Close()
  2292. }
  2293. }()
  2294. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2295. if err != nil {
  2296. println("2", err.Error())
  2297. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2298. } else {
  2299. if exec != nil {
  2300. if exec[0]["content"] == nil {
  2301. mapR := make(map[string]interface{})
  2302. mapR["layout"] = layout
  2303. mjson, _ := json.Marshal(mapR)
  2304. mString := string(mjson)
  2305. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2306. if err3 != nil {
  2307. println("3", err3.Error())
  2308. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2309. } else {
  2310. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2311. }
  2312. } else {
  2313. var mapR map[string]interface{}
  2314. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2315. if err1 != nil {
  2316. fmt.Println("JsonToMapDemo err: ", err2)
  2317. }
  2318. mapR["layout"] = layout
  2319. mjson, _ := json.Marshal(mapR)
  2320. mString := string(mjson)
  2321. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2322. if err3 != nil {
  2323. println("3", err3.Error())
  2324. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2325. } else {
  2326. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2327. }
  2328. }
  2329. } else {
  2330. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2331. }
  2332. }
  2333. }
  2334. func ExecSQL(c *gin.Context) {
  2335. appG := app.Gin{C: c}
  2336. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2337. fsion := gofasion.NewFasion(string(dataByte))
  2338. content := fsion.Get("content").Json()
  2339. pastureid := fsion.Get("pastureid").ValueStr()
  2340. var mapResult map[string]interface{}
  2341. err1 := json.Unmarshal([]byte(content), &mapResult)
  2342. if err1 != nil {
  2343. fmt.Println("JsonToMapDemo err: ", err1)
  2344. }
  2345. sqlstr := "select "
  2346. groupstr := " GROUP BY "
  2347. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2348. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2349. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2350. }
  2351. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2352. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2353. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2354. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2355. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2356. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2357. sqlstr = sqlstr + tem + ","
  2358. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2359. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2360. sqlstr = sqlstr + tem + ","
  2361. } else {
  2362. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2363. sqlstr = sqlstr + tem + ","
  2364. }
  2365. }
  2366. if _, ok := mapResult["selectedCalcul2"]; ok {
  2367. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2368. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2369. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2370. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2371. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2372. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2373. sqlstr = sqlstr + tem + ","
  2374. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2375. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2376. sqlstr = sqlstr + tem + ","
  2377. } else {
  2378. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2379. sqlstr = sqlstr + tem + ","
  2380. }
  2381. }
  2382. }
  2383. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2384. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2385. sqlstr = sqlstr + " where pastureid=" + pastureid
  2386. if len(mapResult["filters"].([]interface{})) > 0 {
  2387. sqlstr = sqlstr + " and "
  2388. }
  2389. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2390. for _, value := range mapResult["filters"].([]interface{}) {
  2391. switch value.(map[string]interface{})["filterOperator"].(string) {
  2392. case ">", "=", "<", ">=", "<=", "!=", "like":
  2393. 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 "
  2394. case "IN":
  2395. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2396. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2397. sqlstr = sqlstr + value1.(string) + ","
  2398. }
  2399. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2400. sqlstr = sqlstr + ")" + " AND "
  2401. case "BETWEEN":
  2402. 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 "
  2403. }
  2404. }
  2405. if len(mapResult["filters"].([]interface{})) > 0 {
  2406. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2407. }
  2408. //
  2409. groupstr = groupstr[0 : len(groupstr)-1]
  2410. sqlstr = sqlstr + groupstr + " "
  2411. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2412. sqlstr = sqlstr + " order by "
  2413. }
  2414. //
  2415. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2416. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2417. sqlstr = sqlstr + value.(string) + " "
  2418. } else {
  2419. sqlstr = sqlstr + value.(string) + ","
  2420. }
  2421. }
  2422. //
  2423. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2424. tx := restful.Engine.NewSession()
  2425. err := tx.Begin()
  2426. defer func() {
  2427. switch {
  2428. case err != nil:
  2429. logging.Error("tx.Begin 事务启动失败__error:", err)
  2430. if tx != nil {
  2431. tx.Rollback()
  2432. }
  2433. default:
  2434. if tx != nil {
  2435. err = tx.Commit()
  2436. }
  2437. }
  2438. if tx != nil {
  2439. tx.Close()
  2440. }
  2441. }()
  2442. exec, err := tx.SQL(sqlstr).Query().List()
  2443. if err != nil {
  2444. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2445. } else {
  2446. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2447. }
  2448. }
  2449. func Dashboards(c *gin.Context) {
  2450. appG := app.Gin{C: c}
  2451. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2452. fsion := gofasion.NewFasion(string(dataByte))
  2453. sqlnamestr := fsion.Get("name").ValueStr()
  2454. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2455. offset := fsion.Get("offset").ValueDefaultInt(0)
  2456. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2457. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2458. month := fsion.Get("month").ValueDefaultStr("map")
  2459. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2460. tx := restful.Engine.NewSession()
  2461. err := tx.Begin()
  2462. defer func() {
  2463. switch {
  2464. case err != nil:
  2465. if tx != nil {
  2466. tx.Rollback()
  2467. }
  2468. default:
  2469. if tx != nil {
  2470. err = tx.Commit()
  2471. }
  2472. }
  2473. if tx != nil {
  2474. tx.Close()
  2475. }
  2476. }()
  2477. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2478. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2479. if sql != "" {
  2480. s_params := make([]interface{}, 0)
  2481. if fsion.HasKey("parammaps") {
  2482. parammaps := fsion.Get("parammaps")
  2483. paramslist := strings.Split(p, ",")
  2484. if len(paramslist) > 0 && p != "" {
  2485. for _, value := range paramslist {
  2486. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2487. if tempv, exists := c.Get("jwt_username"); exists {
  2488. s_params = append(s_params, tempv.(string))
  2489. } else {
  2490. s_params = append(s_params, "")
  2491. }
  2492. } else {
  2493. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2494. }
  2495. }
  2496. }
  2497. }
  2498. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2499. if err != nil {
  2500. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2501. } else {
  2502. //paramslist1 := strings.Split(p1, ",")
  2503. dids := make([]interface{}, 0)
  2504. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2505. var mapResult map[string]interface{}
  2506. dids = append(dids, value["dashboard_id"])
  2507. if value["content"] != nil {
  2508. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2509. if err1 != nil {
  2510. println("JsonToMapDemo1 err: ", err1)
  2511. }
  2512. temap := make(map[string]interface{})
  2513. tem := mapResult["layout"].([]interface{})
  2514. if v, ok := value["chartids"]; ok {
  2515. chartids := strings.Split(v.(string), ",")
  2516. for _, va := range chartids {
  2517. a := false
  2518. for _, v2 := range tem {
  2519. if v2.(map[string]interface{})["id"].(string) == va {
  2520. a = true
  2521. //println("va1======",va)
  2522. }
  2523. }
  2524. if !a {
  2525. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2526. va + "\",\"id\":\"" + va +
  2527. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2528. var mapTem map[string]interface{}
  2529. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2530. if err1 != nil {
  2531. println("JsonToMapDemo err: ", err1)
  2532. }
  2533. tem = append(tem, mapTem)
  2534. }
  2535. }
  2536. temap["layout"] = tem
  2537. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2538. }
  2539. } else {
  2540. temap := make(map[string]interface{})
  2541. tem := make([]interface{}, 0)
  2542. if v, ok := value["chartids"]; ok {
  2543. chartids := strings.Split(v.(string), ",")
  2544. for _, va := range chartids {
  2545. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2546. va + "\",\"id\":\"" + va +
  2547. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2548. var mapTem map[string]interface{}
  2549. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2550. if err1 != nil {
  2551. println("JsonToMapDemo err: ", err1)
  2552. }
  2553. tem = append(tem, mapTem)
  2554. }
  2555. temap["layout"] = tem
  2556. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2557. }
  2558. }
  2559. }
  2560. queryData.(map[string]interface{})["order"] = dids
  2561. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2562. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2563. }
  2564. } else {
  2565. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2566. }
  2567. }
  2568. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2569. fsion := gofasion.NewFasion(parammaps)
  2570. sqlnamestr := fsion.Get("name").ValueStr()
  2571. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2572. offset := fsion.Get("offset").ValueDefaultInt(0)
  2573. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2574. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2575. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2576. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2577. body := []byte("")
  2578. if sql != "" {
  2579. s_params := make([]interface{}, 0)
  2580. if fsion.HasKey("parammaps") {
  2581. parammaps := fsion.Get("parammaps")
  2582. paramslist := strings.Split(p, ",")
  2583. if len(paramslist) > 0 && p != "" {
  2584. for _, value := range paramslist {
  2585. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2586. }
  2587. }
  2588. }
  2589. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2590. if err != nil {
  2591. } else {
  2592. paramslist1 := strings.Split(p1, ",")
  2593. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2594. s_params1 := make([]interface{}, 0)
  2595. if len(paramslist1) > 0 && p1 != "" {
  2596. for _, v := range paramslist1 {
  2597. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2598. }
  2599. }
  2600. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2601. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2602. body, _ = json.Marshal(queryData)
  2603. }
  2604. }
  2605. }
  2606. bs := bytes.NewBuffer(body)
  2607. client := &http.Client{}
  2608. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2609. req, err := http.NewRequest(RequestMethod,
  2610. url,
  2611. bs,
  2612. )
  2613. if err != nil {
  2614. }
  2615. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2616. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2617. if err != nil {
  2618. // handle error
  2619. }
  2620. resp, err := client.Do(req)
  2621. if err != nil {
  2622. return ""
  2623. }
  2624. defer resp.Body.Close()
  2625. result_body, err := ioutil.ReadAll(resp.Body)
  2626. if err != nil {
  2627. return ""
  2628. }
  2629. fmt.Println(string(result_body))
  2630. return ""
  2631. }
  2632. func GetSummary(c *gin.Context) {
  2633. appG := app.Gin{C: c}
  2634. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2635. fsion := gofasion.NewFasion(string(dataByte))
  2636. offset := fsion.Get("offset").ValueDefaultInt(0)
  2637. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2638. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2639. parammaps := fsion.Get("parammaps")
  2640. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2641. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2642. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2643. tx := restful.Engine.NewSession()
  2644. defer tx.Close()
  2645. sqlnamestr := ""
  2646. if genre == "0" {
  2647. if status == "0" {
  2648. sqlnamestr = "getAccuracyJSY"
  2649. } else if status == "1" {
  2650. sqlnamestr = "getAccuracyHFT"
  2651. } else if status == "2" {
  2652. sqlnamestr = "getAccuracyHNS"
  2653. } else if status == "3" {
  2654. sqlnamestr = "getAccuracyHSC"
  2655. } else if status == "4" {
  2656. sqlnamestr = "getAccuracyHCC"
  2657. } else if status == "5" {
  2658. sqlnamestr = "getAccuracyMC"
  2659. } else if status == "6" {
  2660. sqlnamestr = "getAccuracyFeedHL"
  2661. } else if status == "7" {
  2662. sqlnamestr = "getAccuracyRT"
  2663. }
  2664. } else {
  2665. if status == "0" {
  2666. sqlnamestr = "getAccuracySCCJSY"
  2667. } else if status == "1" {
  2668. sqlnamestr = "getAccuracySFT"
  2669. } else if status == "2" {
  2670. sqlnamestr = "getAccuracySNS"
  2671. } else if status == "3" {
  2672. sqlnamestr = "getAccuracySSC"
  2673. } else if status == "4" {
  2674. sqlnamestr = "getAccuracySCC"
  2675. } else if status == "5" {
  2676. sqlnamestr = "getAccuracySLCL"
  2677. } else if status == "7" {
  2678. sqlnamestr = "getAccuracySCCRT"
  2679. }
  2680. }
  2681. if isDate == "1" {
  2682. sqlnamestr += "Date"
  2683. }
  2684. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2685. // fmt.Println(sqlnamestr, sql)
  2686. if sql != "" {
  2687. s_params := make([]interface{}, 0)
  2688. // if fsion.HasKey("parammaps") {
  2689. fmt.Println(s_params, "222", p)
  2690. paramslist := strings.Split(p, ",")
  2691. if len(paramslist) > 0 && p != "" {
  2692. for _, value := range paramslist {
  2693. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2694. if tempv, exists := c.Get("jwt_username"); exists {
  2695. s_params = append(s_params, tempv.(string))
  2696. } else {
  2697. s_params = append(s_params, "")
  2698. }
  2699. } else {
  2700. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2701. }
  2702. }
  2703. }
  2704. if returntype == "xlsx" {
  2705. var xlsxfile *xlsx.File
  2706. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2707. //c.File("c:/dd.xlsx")
  2708. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2709. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2710. c.Header("Content-Transfer-Encoding", "binary")
  2711. _ = xlsxfile.Write(c.Writer)
  2712. } else {
  2713. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2714. if err != nil {
  2715. logging.Error("GetDataByName err: ", err)
  2716. msg := geterrmsg(err.Error())
  2717. appG.Response(http.StatusOK, e.ERROR, msg)
  2718. } else {
  2719. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2720. }
  2721. }
  2722. } else {
  2723. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2724. }
  2725. }
  2726. // type lpplanStruct struct {
  2727. // Id int64 `xorm:"id"`
  2728. // Tmrname string `xorm:"tmrname"`
  2729. // Tmrid int64 `xorm:"tmrid"`
  2730. // Sort int64 `xorm:"sort"`
  2731. // Sel int64 `xorm:"sel"`
  2732. // Times int64 `xorm:"times"`
  2733. // Ftname string `xorm:"ftname"`
  2734. // Ftid int64 `xorm:"ftid"`
  2735. // Maxweight float64 `xorm:"maxweight"`
  2736. // Sumweight float64 `xorm:"sumweight"`
  2737. // Sumcowcount int64 `xorm:"sumcowcount"`
  2738. // Pastureid string `xorm:"pastureid"`
  2739. // Display string `xorm:"display"`
  2740. // Issplit int64 `xorm:"issplit"`
  2741. // BeginTime string `xorm:"begintime"`
  2742. // }
  2743. func UpdateFTdetail(c *gin.Context) {
  2744. appG := app.Gin{C: c}
  2745. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2746. tempval_ := make(map[string]interface{})
  2747. tempCommon := make(map[string]interface{})
  2748. tempval := make([]map[string]interface{}, 0)
  2749. fTChange := make(map[string]interface{}, 0)
  2750. fpdOldDataList := make([]map[string]interface{}, 0)
  2751. fpdDataList := make([]map[string]interface{}, 0)
  2752. fsion := gofasion.NewFasion(string(dataByte))
  2753. // parammaps := fsion.Get("parammaps")
  2754. createdate := fsion.Get("createdate").ValueStr()
  2755. err := json.Unmarshal(dataByte, &tempval_)
  2756. if err != nil {
  2757. appG.Response(http.StatusOK, e.ERROR, false)
  2758. return
  2759. }
  2760. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2761. tx := restful.Engine.NewSession()
  2762. if v, ok := tempval_["data"].([]interface{}); ok {
  2763. for _, Tvalue := range v {
  2764. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2765. if v1["name"] == "updateFPbyFTChange" {
  2766. fTChange = v1
  2767. continue
  2768. }
  2769. tempval = append(tempval, v1)
  2770. }
  2771. }
  2772. }
  2773. parammaps := fTChange["parammaps"].(map[string]interface{})
  2774. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2775. // if err != nil {
  2776. // logs.Error(err)
  2777. // appG.Response(http.StatusOK, e.ERROR, false)
  2778. // return
  2779. // }
  2780. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2781. // if err != nil {
  2782. // logs.Error(err)
  2783. // appG.Response(http.StatusOK, e.ERROR, false)
  2784. // return
  2785. // }
  2786. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2787. // if err != nil {
  2788. // logs.Error(err)
  2789. // appG.Response(http.StatusOK, e.ERROR, false)
  2790. // return
  2791. // }
  2792. err = tx.Begin()
  2793. if err != nil {
  2794. logging.Error("tx.Begin 事务启动失败__error:", err)
  2795. }
  2796. defer func() {
  2797. if err != nil {
  2798. if tx != nil {
  2799. tx.Rollback()
  2800. }
  2801. }
  2802. if tx != nil {
  2803. tx.Close()
  2804. }
  2805. }()
  2806. if err != nil {
  2807. } else {
  2808. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2809. tempCommon = v
  2810. }
  2811. 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 ,
  2812. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2813. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2814. UNION
  2815. 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 ,
  2816. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2817. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2818. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2819. if err == nil {
  2820. if tempv, exists := c.Get("jwt_username"); exists {
  2821. tempCommon["jwt_username"] = tempv.(string)
  2822. }
  2823. for _, paramvalue := range tempval {
  2824. if _, ok := paramvalue["resultname"]; !ok {
  2825. paramvalue["resultname"] = paramvalue["name"]
  2826. }
  2827. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2828. if err != nil {
  2829. logging.Error("ExecDataParam error:", err)
  2830. break
  2831. }
  2832. }
  2833. if err != nil {
  2834. msg := geterrmsg(err.Error())
  2835. appG.Response(http.StatusOK, e.ERROR, msg)
  2836. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2837. }
  2838. }
  2839. }
  2840. tx.Commit()
  2841. // go func() {
  2842. if fTChange != nil {
  2843. parammaps := fTChange["parammaps"].(map[string]interface{})
  2844. if parammaps["type"].(float64) == 1 {
  2845. _, err = tx.SQL(`UPDATE feedp fp
  2846. set
  2847. fp.ftweight= IFNULL(IF(
  2848. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2849. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2850. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2851. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2852. ),0),fp.feedweight = IFNULL(IF(
  2853. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2854. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2855. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2856. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2857. ),0) +ifnull(fp.supplyweight,0)
  2858. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2859. _, err = tx.SQL(`UPDATE fpdetail fpd
  2860. INNER JOIN feedp fp
  2861. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2862. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2863. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2864. } else {
  2865. _, err = tx.SQL(`UPDATE feedp fp
  2866. SET
  2867. fp.supplyweight= IFNULL(IF(
  2868. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2869. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2870. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2871. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2872. ),0),fp.feedweight = IFNULL(IF(
  2873. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2874. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2875. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2876. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2877. ),0) +ifnull(fp.supplyweight,0)
  2878. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2879. _, err = tx.SQL(`UPDATE fpdetail fpd
  2880. INNER JOIN feedp fp
  2881. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2882. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2883. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2884. }
  2885. 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(ptid) ptid,TRIM(ptsid ) ptsid ,
  2886. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2887. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2888. UNION
  2889. 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 ,
  2890. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2891. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2892. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2893. lpplanList := make([]*lpplanStruct, 0)
  2894. err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2895. if err != nil {
  2896. logs.Error(err, 1)
  2897. return
  2898. }
  2899. lppidlist := []string{}
  2900. for _, lpp := range lpplanList {
  2901. lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2902. }
  2903. if len(lppidlist) <= 0 {
  2904. appG.Response(http.StatusOK, e.SUCCESS, true)
  2905. return
  2906. }
  2907. lpplandtl1AllList := make([]*lpplandtl1, 0)
  2908. err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  2909. order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  2910. if err != nil {
  2911. // tx.Rollback()
  2912. logs.Error(err, 2, parammaps["pastureid"])
  2913. return
  2914. }
  2915. var wg sync.WaitGroup
  2916. for _, old := range fpdOldDataList {
  2917. for _, fpd := range fpdDataList {
  2918. wg.Add(1)
  2919. go func(old, fpd map[string]interface{}) {
  2920. updateLppandList := make([]*lpplandtl1, 0)
  2921. defer wg.Done()
  2922. if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  2923. fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  2924. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  2925. oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  2926. var w float64
  2927. var status int
  2928. if fpd["barname"].(string) == "D1" {
  2929. fmt.Println("1")
  2930. }
  2931. if weight < oldweight {
  2932. if weight >= 0 {
  2933. return
  2934. }
  2935. w = weight
  2936. status = 0
  2937. } else {
  2938. if oldweight > 0 {
  2939. return
  2940. }
  2941. w = weight
  2942. status = 1
  2943. }
  2944. // fweight = w
  2945. for _, lpp := range lpplanList {
  2946. var fweight float64
  2947. var lweight float64
  2948. lpplandtl1List := make([]*lpplandtl1, 0)
  2949. fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  2950. for _, lppland := range lpplandtl1AllList {
  2951. if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  2952. lpplandtl1List = append(lpplandtl1List, lppland)
  2953. }
  2954. }
  2955. if len(lpplandtl1List) == 0 {
  2956. continue
  2957. }
  2958. for _, lppland := range lpplandtl1List {
  2959. lweight += lppland.Lweight
  2960. }
  2961. if status == 0 {
  2962. if lweight <= 0 {
  2963. continue
  2964. }
  2965. } else {
  2966. if lpp.Maxweight <= lweight {
  2967. continue
  2968. }
  2969. }
  2970. for _, lppland := range lpplandtl1List {
  2971. if fpdid == lppland.Fpdid {
  2972. if status == 1 {
  2973. // if w <= lppland.Lweight {
  2974. if lpp.Maxweight <= lweight {
  2975. continue
  2976. }
  2977. if w+lweight <= lpp.Maxweight {
  2978. lppland.Lweight += w
  2979. lweight += w
  2980. fweight += w
  2981. w = 0
  2982. } else {
  2983. w = w - (lpp.Maxweight - lweight)
  2984. n := (lpp.Maxweight - lweight)
  2985. lppland.Lweight = lppland.Lweight + n
  2986. lweight += n
  2987. fweight += n
  2988. }
  2989. } else {
  2990. if lppland.Lweight == 0 {
  2991. continue
  2992. }
  2993. if w+lppland.Lweight >= 0 {
  2994. lppland.Lweight = lppland.Lweight + w
  2995. lweight = lweight + w
  2996. fweight = fweight + w
  2997. w = 0
  2998. } else {
  2999. w = w + lppland.Lweight
  3000. lweight = lweight - lppland.Lweight
  3001. fweight = fweight - lppland.Lweight
  3002. lppland.Lweight = 0
  3003. }
  3004. }
  3005. updateLppandList = append(updateLppandList, lppland)
  3006. break
  3007. }
  3008. }
  3009. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3010. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3011. WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3012. if err != nil {
  3013. // tx.Rollback()
  3014. logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3015. return
  3016. }
  3017. for _, lppland := range updateLppandList {
  3018. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3019. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3020. if err != nil {
  3021. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3022. // tx.Rollback()
  3023. logs.Error(err, 3)
  3024. return
  3025. }
  3026. // defer wg.Done()
  3027. }
  3028. updateLppandList = []*lpplandtl1{}
  3029. if w == 0 {
  3030. break
  3031. }
  3032. }
  3033. }
  3034. }(old, fpd)
  3035. }
  3036. }
  3037. wg.Wait()
  3038. }
  3039. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3040. if err != nil {
  3041. logs.Error(err)
  3042. appG.Response(http.StatusOK, e.ERROR, false)
  3043. return
  3044. }
  3045. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3046. if err != nil {
  3047. logs.Error(err)
  3048. appG.Response(http.StatusOK, e.ERROR, false)
  3049. return
  3050. }
  3051. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3052. if err != nil {
  3053. logs.Error(err)
  3054. appG.Response(http.StatusOK, e.ERROR, false)
  3055. return
  3056. }
  3057. now := createdate
  3058. // for _, oldFpd := range oldFpdDataList {
  3059. for _, newFpd := range newFpdDataList {
  3060. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3061. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3062. // go func() {
  3063. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  3064. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3065. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3066. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  3067. if err != nil {
  3068. logs.Error(err)
  3069. appG.Response(http.StatusOK, e.ERROR, false)
  3070. return
  3071. }
  3072. // }()
  3073. }
  3074. // break
  3075. // }
  3076. // }
  3077. // }
  3078. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3079. for _, newLpplandtl1 := range newLpplandtl1List {
  3080. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3081. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3082. // go func() {
  3083. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3084. background,cowcount,ccountradio,lweighthis,createdate)
  3085. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3086. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3087. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3088. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3089. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3090. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  3091. if err != nil {
  3092. logs.Error(err)
  3093. appG.Response(http.StatusOK, e.ERROR, false)
  3094. return
  3095. }
  3096. // }()
  3097. // }
  3098. // break
  3099. // }
  3100. // }
  3101. }
  3102. // for _, oldFeedp := range oldFeedpList {
  3103. for _, newFeedp := range newFeedpList {
  3104. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3105. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3106. // go func() {
  3107. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3108. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  3109. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3110. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3111. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3112. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3113. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3114. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  3115. if err != nil {
  3116. logs.Error(err)
  3117. appG.Response(http.StatusOK, e.ERROR, false)
  3118. return
  3119. }
  3120. // }()
  3121. // }
  3122. // }
  3123. }
  3124. appG.Response(http.StatusOK, e.SUCCESS, true)
  3125. }
  3126. type lpplandtlInfo struct {
  3127. Id int64 `xorm:"id"`
  3128. Pastureid int64 `xorm:"pastureid"`
  3129. Lppid int64 `xorm:"lppid"`
  3130. Barid int64 `xorm:"barid"`
  3131. Barname string `xorm:"barname"`
  3132. Fpdid int64 `xorm:"fpdid"`
  3133. Fttype int64 `xorm:"fttype"`
  3134. Lweight float64 `xorm:"lweight"`
  3135. Sort int64 `xorm:"sort"`
  3136. Tmrid int64 `xorm:"tmrid"`
  3137. Tmrname string `xorm:"tmrname"`
  3138. Cowcount int64 `xorm:"cowcount"`
  3139. Ccountradio float64 `xorm:"ccountradio"`
  3140. Background string `xorm:"background"`
  3141. Lweighthis float64 `xorm:"lweighthis"`
  3142. Maxweight float64 `xorm:"maxweight"`
  3143. }
  3144. func UpdateFpdetailBar(c *gin.Context) {
  3145. appG := app.Gin{C: c}
  3146. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3147. fsion := gofasion.NewFasion(string(dataByte))
  3148. pastureid := fsion.Get("pastureid").ValueStr()
  3149. id := fsion.Get("id").ValueStr()
  3150. tx := restful.Engine.NewSession()
  3151. tx.Begin()
  3152. fpdList, err := tx.SQL(` select id,ifnull(ROUND((1-ptsrate)*weight,2),"") weight,ptuse from fpdetail where pastureid = ? and barid = ? order by times `,
  3153. pastureid, id).Query().List()
  3154. if err != nil {
  3155. logs.Error(err)
  3156. }
  3157. for _, fpd := range fpdList {
  3158. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3159. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3160. pastureid, fpd["id"]).Query().List()
  3161. if err != nil {
  3162. tx.Rollback()
  3163. logs.Error(err)
  3164. appG.Response(http.StatusOK, e.ERROR, false)
  3165. return
  3166. }
  3167. var lweight float64
  3168. for _, lppland := range lpplandList {
  3169. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3170. lweight += lweight1
  3171. }
  3172. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3173. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3174. if fpdweight >= ptuse && lweight == ptuse {
  3175. continue
  3176. } else {
  3177. if lweight <= fpdweight {
  3178. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3179. if err != nil {
  3180. tx.Rollback()
  3181. logs.Error(err)
  3182. appG.Response(http.StatusOK, e.ERROR, false)
  3183. return
  3184. }
  3185. } else {
  3186. weight := fpdweight - lweight
  3187. for _, lppland := range lpplandList {
  3188. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3189. if weight >= lpplandlweight {
  3190. weight = weight - lpplandlweight
  3191. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3192. if err != nil {
  3193. tx.Rollback()
  3194. logs.Error(err)
  3195. appG.Response(http.StatusOK, e.ERROR, false)
  3196. return
  3197. }
  3198. } else {
  3199. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lppland["lweight"].(float64)-weight, lppland["id"]).Execute()
  3200. if err != nil {
  3201. tx.Rollback()
  3202. logs.Error(err)
  3203. appG.Response(http.StatusOK, e.ERROR, false)
  3204. return
  3205. }
  3206. weight = 0
  3207. break
  3208. }
  3209. }
  3210. }
  3211. }
  3212. }
  3213. for _, list := range fsion.Get("data").Array() {
  3214. ftmap := make(map[string]interface{})
  3215. ftmap["old"] = list.Get("old").ValueFloat64()
  3216. ftmap["new"] = list.Get("new").ValueFloat64()
  3217. ftmap["times"] = list.Get("times").ValueInt64()
  3218. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3219. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3220. // fmt.Println(ftmap)
  3221. fpdDataList, err := tx.SQL(`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 ,
  3222. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  3223. WHERE fpdetail.pastureid = ? and barid = ? and times = ?
  3224. UNION
  3225. 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 ,
  3226. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3227. WHERE fpdetail.pastureid = ? and barid = ? and times = ? ) t
  3228. order by t.barname,t.times`, pastureid, id, ftmap["times"], pastureid, id, ftmap["times"]).Query().List()
  3229. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3230. if err != nil {
  3231. tx.Rollback()
  3232. logs.Error(err)
  3233. }
  3234. for _, fpd := range fpdDataList {
  3235. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  3236. fttype := -1
  3237. if ftmap["ptid"].(string) != "-1" {
  3238. fttype = 1
  3239. }
  3240. var fweight float64
  3241. var lweight float64
  3242. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3243. err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  3244. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  3245. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3246. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3247. if err != nil {
  3248. tx.Rollback()
  3249. logs.Error(err)
  3250. }
  3251. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3252. var w float64
  3253. var status int
  3254. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  3255. if weight >= 0 {
  3256. continue
  3257. }
  3258. w = weight
  3259. status = 0
  3260. } else {
  3261. if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  3262. continue
  3263. }
  3264. w = weight
  3265. status = 1
  3266. }
  3267. for _, lppland := range lpplandtl1List {
  3268. lweight += lppland.Lweight
  3269. }
  3270. for _, lppland := range lpplandtl1List {
  3271. if status == 1 {
  3272. // if w <= lppland.Lweight {
  3273. if lppland.Maxweight <= lweight {
  3274. continue
  3275. }
  3276. if w+lweight <= lppland.Maxweight {
  3277. lppland.Lweight += w
  3278. lweight += w
  3279. fweight += w
  3280. w = 0
  3281. } else {
  3282. w = w - (lppland.Maxweight - lweight)
  3283. n := (lppland.Maxweight - lweight)
  3284. lppland.Lweight = lppland.Lweight + n
  3285. lweight += n
  3286. fweight += n
  3287. }
  3288. } else {
  3289. if lppland.Lweight == 0 {
  3290. continue
  3291. }
  3292. if w+lppland.Lweight >= 0 {
  3293. lppland.Lweight = lppland.Lweight + w
  3294. lweight = lweight + w
  3295. fweight = fweight + w
  3296. w = 0
  3297. } else {
  3298. w = w + lppland.Lweight
  3299. lweight = lweight - lppland.Lweight
  3300. fweight = fweight - lppland.Lweight
  3301. lppland.Lweight = 0
  3302. }
  3303. }
  3304. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3305. if err != nil {
  3306. tx.Rollback()
  3307. logs.Error(err)
  3308. return
  3309. }
  3310. break
  3311. }
  3312. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3313. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3314. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3315. if err != nil {
  3316. tx.Rollback()
  3317. logs.Error(err)
  3318. }
  3319. if w == 0 {
  3320. break
  3321. }
  3322. }
  3323. }
  3324. }
  3325. tx.Commit()
  3326. now := time.Now()
  3327. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3328. if err != nil {
  3329. logs.Error(err)
  3330. appG.Response(http.StatusOK, e.ERROR, false)
  3331. return
  3332. }
  3333. // newFpdDataList, err := tx.SQL(` select * from fpdetail where barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3334. // if err != nil {
  3335. // logs.Error(err)
  3336. // appG.Response(http.StatusOK, e.ERROR, false)
  3337. // return
  3338. // }
  3339. // newFeedpList, err := tx.SQL(` select * from feedp where barid = ? and pastureid = ?`, id, pastureid).Query().List()
  3340. // if err != nil {
  3341. // logs.Error(err)
  3342. // appG.Response(http.StatusOK, e.ERROR, false)
  3343. // return
  3344. // }
  3345. for _, newLpplandtl1 := range newLpplandtl1List {
  3346. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3347. background,cowcount,ccountradio,lweighthis,createdate)
  3348. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3349. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3350. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3351. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3352. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3353. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  3354. if err != nil {
  3355. logs.Error(err)
  3356. appG.Response(http.StatusOK, e.ERROR, false)
  3357. return
  3358. }
  3359. }
  3360. // for _, newFpd := range newFpdDataList {
  3361. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  3362. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3363. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3364. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  3365. // if err != nil {
  3366. // logs.Error(err)
  3367. // appG.Response(http.StatusOK, e.ERROR, false)
  3368. // return
  3369. // }
  3370. // }
  3371. // for _, newFeedp := range newFeedpList {
  3372. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3373. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  3374. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3375. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3376. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3377. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3378. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3379. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  3380. // if err != nil {
  3381. // logs.Error(err)
  3382. // appG.Response(http.StatusOK, e.ERROR, false)
  3383. // return
  3384. // }
  3385. // }
  3386. appG.Response(http.StatusOK, e.SUCCESS, true)
  3387. }
  3388. func GetProcessAnalysis(c *gin.Context) {
  3389. appG := app.Gin{C: c}
  3390. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3391. fsion := gofasion.NewFasion(string(dataByte))
  3392. sqlnamestr := fsion.Get("name").ValueStr()
  3393. offset := fsion.Get("offset").ValueDefaultInt(0)
  3394. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3395. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3396. parammaps := fsion.Get("parammaps")
  3397. tx := restful.Engine.NewSession()
  3398. err := tx.Begin()
  3399. defer func() {
  3400. switch {
  3401. case err != nil:
  3402. logging.Error("tx.Begin 事务启动失败__error:", err)
  3403. if tx != nil {
  3404. tx.Rollback()
  3405. }
  3406. default:
  3407. if tx != nil {
  3408. err = tx.Commit()
  3409. }
  3410. }
  3411. if tx != nil {
  3412. tx.Close()
  3413. }
  3414. }()
  3415. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3416. s_params := make([]interface{}, 0)
  3417. paramslist := strings.Split(p, ",")
  3418. if len(paramslist) > 0 && p != "" {
  3419. for _, value := range paramslist {
  3420. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3421. if tempv, exists := c.Get("jwt_username"); exists {
  3422. s_params = append(s_params, tempv.(string))
  3423. } else {
  3424. s_params = append(s_params, "")
  3425. }
  3426. } else {
  3427. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3428. }
  3429. }
  3430. }
  3431. tmrtnameStr := ""
  3432. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3433. if len(tmrtnameStr) == 0 {
  3434. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3435. } else {
  3436. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3437. }
  3438. }
  3439. if len(tmrtnameStr) > 0 {
  3440. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3441. }
  3442. sql += " ORDER BY d.intime"
  3443. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3444. if err != nil {
  3445. logging.Error("GetDataByName err: ", err)
  3446. msg := geterrmsg(err.Error())
  3447. appG.Response(http.StatusOK, e.ERROR, msg)
  3448. } else {
  3449. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3450. }
  3451. }
  3452. func UpdateFeedtempletStatus(c *gin.Context) {
  3453. appG := app.Gin{C: c}
  3454. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3455. fsion := gofasion.NewFasion(string(dataByte))
  3456. parammaps := fsion.Get("parammaps")
  3457. tx := restful.Engine.NewSession()
  3458. tx.Begin()
  3459. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3460. if err != nil {
  3461. tx.Rollback()
  3462. logs.Error(err)
  3463. appG.Response(http.StatusOK, e.ERROR, err)
  3464. return
  3465. }
  3466. tx.Commit()
  3467. appG.Response(http.StatusOK, e.SUCCESS, true)
  3468. }
  3469. func AddFtdry(c *gin.Context) {
  3470. appG := app.Gin{C: c}
  3471. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3472. fsion := gofasion.NewFasion(string(dataByte))
  3473. sqlnamestr := fsion.Get("name").ValueStr()
  3474. s_params := make([]interface{}, 0)
  3475. tx := restful.Engine.NewSession()
  3476. err := tx.Begin()
  3477. defer func() {
  3478. switch {
  3479. case err != nil:
  3480. if tx != nil {
  3481. tx.Rollback()
  3482. }
  3483. default:
  3484. if tx != nil {
  3485. err = tx.Commit()
  3486. }
  3487. }
  3488. if tx != nil {
  3489. tx.Close()
  3490. }
  3491. }()
  3492. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3493. if sql != "" {
  3494. parammaps := fsion.Get("parammaps")
  3495. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3496. paramslist := strings.Split(p, ",")
  3497. if len(paramslist) > 0 && p != "" {
  3498. for _, value := range paramslist {
  3499. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3500. if tempv, exists := c.Get("jwt_username"); exists {
  3501. s_params = append(s_params, tempv.(string))
  3502. } else {
  3503. s_params = append(s_params, "")
  3504. }
  3505. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3506. ids, err := setting.SnowIds.NextId()
  3507. if err != nil {
  3508. ids = time.Now().UnixNano()
  3509. logging.Info("create SnowIds err", err)
  3510. }
  3511. s_params = append(s_params, ids)
  3512. } else {
  3513. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3514. }
  3515. }
  3516. }
  3517. var actweight float64
  3518. actweightList, err := tx.SQL(`select ROUND(avg(actweight),2) as actweight from ftdry
  3519. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3520. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3521. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3522. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3523. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3524. 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()
  3525. if err != nil {
  3526. logging.Error("AddFtdry err: ", err)
  3527. msg := geterrmsg(err.Error())
  3528. appG.Response(http.StatusOK, e.ERROR, msg)
  3529. }
  3530. if len(actweightList) > 0 {
  3531. for _, item := range actweightList {
  3532. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3533. if err != nil {
  3534. logging.Error("AddFtdry err: ", err)
  3535. msg := geterrmsg(err.Error())
  3536. appG.Response(http.StatusOK, e.ERROR, msg)
  3537. }
  3538. actweight = fl
  3539. }
  3540. } else {
  3541. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3542. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3543. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3544. if err != nil {
  3545. logging.Error("AddFtdry err: ", err)
  3546. msg := geterrmsg(err.Error())
  3547. appG.Response(http.StatusOK, e.ERROR, msg)
  3548. }
  3549. for _, item := range dryList {
  3550. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3551. if err != nil {
  3552. logging.Error("AddFtdry err: ", err)
  3553. msg := geterrmsg(err.Error())
  3554. appG.Response(http.StatusOK, e.ERROR, msg)
  3555. }
  3556. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3557. }
  3558. }
  3559. if sqlnamestr == "insertFtdry" {
  3560. s_params = append(s_params, actweight)
  3561. } else if sqlnamestr == "updateFtdry" {
  3562. sql = fmt.Sprintf(sql, actweight)
  3563. }
  3564. queryData, err := execDataBySqlT(sql, s_params, tx)
  3565. if err != nil {
  3566. logging.Error("AddFtdry err: ", err)
  3567. msg := geterrmsg(err.Error())
  3568. appG.Response(http.StatusOK, e.ERROR, msg)
  3569. } else {
  3570. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3571. }
  3572. } else {
  3573. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3574. }
  3575. }
  3576. func CheckDates(c *gin.Context) {
  3577. tx := restful.Engine.NewSession()
  3578. defer tx.Close()
  3579. appG := app.Gin{C: c}
  3580. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3581. tempval_ := make(map[string]interface{})
  3582. tempCommon := make(map[string]interface{})
  3583. tempval := make([]map[string]interface{}, 0)
  3584. err := json.Unmarshal(dataByte, &tempval_)
  3585. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3586. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3587. if err != nil {
  3588. } else {
  3589. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3590. tempCommon = v
  3591. }
  3592. if v, ok := tempval_["data"].([]interface{}); ok {
  3593. for _, Tvalue := range v {
  3594. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3595. tempval = append(tempval, v1)
  3596. }
  3597. }
  3598. }
  3599. if err == nil {
  3600. if tempv, exists := c.Get("jwt_username"); exists {
  3601. tempCommon["jwt_username"] = tempv.(string)
  3602. }
  3603. for _, paramvalue := range tempval {
  3604. if _, ok := paramvalue["resultname"]; !ok {
  3605. paramvalue["resultname"] = paramvalue["name"]
  3606. }
  3607. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3608. if err != nil {
  3609. logging.Error("ExecDataParam error:", err)
  3610. }
  3611. }
  3612. if err == nil {
  3613. vmsg := ""
  3614. for _, item := range tempval {
  3615. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3616. for _, childrenList := range list.([]interface{}) {
  3617. for k, children := range childrenList.(map[string]interface{}) {
  3618. if k != "children" {
  3619. continue
  3620. }
  3621. for _, v := range children.([]map[string]interface{}) {
  3622. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3623. if k1 == "list" {
  3624. for _, v2 := range v1.([]map[string]interface{}) {
  3625. if v2["vmsg"].(string) != "1" {
  3626. if len(vmsg) == 0 {
  3627. vmsg = v2["vmsg"].(string)
  3628. } else {
  3629. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3630. }
  3631. }
  3632. }
  3633. }
  3634. }
  3635. }
  3636. }
  3637. }
  3638. }
  3639. }
  3640. if len(vmsg) > 0 {
  3641. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3642. } else {
  3643. appG.Response(http.StatusOK, e.SUCCESS, true)
  3644. }
  3645. } else {
  3646. msg := geterrmsg(err.Error())
  3647. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3648. }
  3649. }
  3650. }
  3651. if err != nil {
  3652. msg := geterrmsg(err.Error())
  3653. appG.Response(http.StatusOK, e.ERROR, msg)
  3654. }
  3655. }
  3656. 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) {
  3657. sqlname := fasion["name"].(string)
  3658. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3659. if v, ok := fasion["type"]; ok {
  3660. sqltype = v.(string)
  3661. }
  3662. sql := ""
  3663. p := ""
  3664. s_params := make([]interface{}, 0)
  3665. if sqltype != "" {
  3666. sql, p = restful.GetSqlByName(sqlname, tx)
  3667. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3668. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3669. paramslist := strings.Split(p, ",")
  3670. if len(paramslist) > 0 && p != "" {
  3671. for _, value := range paramslist {
  3672. ss := ""
  3673. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3674. ids, err := setting.SnowIds.NextId()
  3675. if err != nil {
  3676. ids = time.Now().UnixNano()
  3677. logging.Info("create SnowIds err", err)
  3678. }
  3679. s_params = append(s_params, ids)
  3680. } else {
  3681. if ss == "" && CommonParamMap != nil {
  3682. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3683. ss = valuestring
  3684. tempstrb := strings.IndexAny(valuestring, "@")
  3685. tempstre := strings.IndexAny(valuestring, ".")
  3686. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3687. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3688. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3689. }
  3690. } else {
  3691. ss = ""
  3692. }
  3693. }
  3694. }
  3695. if ss == "" && ParentParamMap != nil {
  3696. ss = getParamValue_(v, value, ParentParamMap)
  3697. }
  3698. if ss == "" && sameParamMap != nil {
  3699. ss = getParamValue(v, value, sameParamMap)
  3700. }
  3701. if ss == "" && ParamMap != nil {
  3702. ss = getParamValue(v, value, ParamMap)
  3703. }
  3704. s_params = append(s_params, ss)
  3705. }
  3706. }
  3707. }
  3708. }
  3709. }
  3710. if sql == "" {
  3711. sqltype = ""
  3712. }
  3713. if sql != "" {
  3714. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3715. if err != nil {
  3716. return nil, err
  3717. }
  3718. // fmt.Println(tempValParam)
  3719. return tempValParam.(map[string]interface{}), nil
  3720. } else {
  3721. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3722. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3723. if err != nil {
  3724. return nil, err
  3725. }
  3726. return nil, err
  3727. }
  3728. }
  3729. return nil, nil
  3730. }
  3731. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3732. var err error
  3733. subarray, ok := fasion["children"]
  3734. if ok {
  3735. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3736. tempVal_arrary := make([]map[string]interface{}, 0)
  3737. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3738. tempVal_ := make(map[string]interface{})
  3739. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3740. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3741. } else {
  3742. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3743. }
  3744. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3745. if err != nil {
  3746. return err
  3747. }
  3748. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3749. }
  3750. v.(map[string]interface{})["children"] = tempVal_arrary
  3751. }
  3752. }
  3753. return nil
  3754. }
  3755. func FpdImportExcel(c *gin.Context) {
  3756. appG := app.Gin{C: c}
  3757. inputdata := ""
  3758. c.Request.ParseForm()
  3759. params := c.Request.Form
  3760. file, _, err := c.Request.FormFile("file")
  3761. if err != nil {
  3762. appG.Response(http.StatusOK, e.ERROR, err)
  3763. return
  3764. }
  3765. sqlnamestrs := params.Get("name")
  3766. sheetname := params.Get("sheetname")
  3767. pastureid := params.Get("pastureid")
  3768. // importParams := params.Get("importParams")
  3769. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3770. // 必输项参数 (字符串格式 "field1,field2,field3")
  3771. requiredParams := params.Get("requiredParams")
  3772. // 日期参数
  3773. dateParams := params.Get("dateParams")
  3774. // 数字参数
  3775. numParams := params.Get("numParams")
  3776. //将字符串分割开
  3777. dateParamslist := strings.Split(dateParams, ",")
  3778. requiredParamslist := strings.Split(requiredParams, ",")
  3779. numParamslist := strings.Split(numParams, ",")
  3780. queryData := make([]interface{}, 0)
  3781. sqlslist := strings.Split(sqlnamestrs, ",")
  3782. xlsx1, err := excelize.OpenReader(file)
  3783. if err != nil {
  3784. fmt.Println(err)
  3785. return
  3786. }
  3787. ok := 0
  3788. error := 0
  3789. isdone := true
  3790. tx := restful.Engine.NewSession()
  3791. defer tx.Close()
  3792. 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
  3793. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3794. if err != nil {
  3795. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3796. return
  3797. }
  3798. rows := xlsx1.GetRows(sheetname)
  3799. // 限制10000条,多余的截取掉
  3800. if len(rows) > 10000 {
  3801. rows = rows[:10000]
  3802. }
  3803. for i, row := range rows {
  3804. if i > 0 {
  3805. entry := make(map[string]interface{})
  3806. outentry := make(map[string]interface{})
  3807. for j, colCell := range rows[0] {
  3808. for k, colCell1 := range row {
  3809. if j == k {
  3810. outentry[colCell] = colCell1
  3811. entry[colCell] = colCell1
  3812. }
  3813. }
  3814. }
  3815. inputdata = ""
  3816. a := ""
  3817. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3818. //校验日期格式
  3819. for _, v := range dateParamslist {
  3820. if v == "" {
  3821. continue
  3822. }
  3823. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3824. dtime, err := TransfTime(d.(string))
  3825. if err != nil {
  3826. a = strings.Trim(v, " ")
  3827. break
  3828. }
  3829. outentry[strings.Trim(v, " ")] = dtime
  3830. }
  3831. }
  3832. if a != "" {
  3833. outentry["error_msg"] = a + " 格式错误"
  3834. error++
  3835. queryData = append(queryData, outentry)
  3836. continue
  3837. }
  3838. a = ""
  3839. //校验必填格式
  3840. for _, v := range requiredParamslist {
  3841. if v == "" {
  3842. continue
  3843. }
  3844. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3845. a = strings.Trim(v, " ")
  3846. break
  3847. }
  3848. }
  3849. if a != "" {
  3850. outentry["error_msg"] = a + " 未填或格式错误"
  3851. error++
  3852. queryData = append(queryData, outentry)
  3853. continue
  3854. }
  3855. a = ""
  3856. //校验数字格式
  3857. for _, v := range numParamslist {
  3858. if v == "" {
  3859. continue
  3860. }
  3861. d, ok := outentry[strings.Trim(v, " ")]
  3862. if !ok || d == "" {
  3863. outentry[strings.Trim(v, " ")] = 0
  3864. } else {
  3865. var fl float64
  3866. switch d.(type) {
  3867. case string:
  3868. fl, err = strconv.ParseFloat(d.(string), 64)
  3869. }
  3870. if err != nil || fl < 0 {
  3871. a = strings.Trim(v, " ")
  3872. break
  3873. }
  3874. }
  3875. }
  3876. if a != "" {
  3877. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3878. error++
  3879. queryData = append(queryData, outentry)
  3880. continue
  3881. }
  3882. errExist := false
  3883. for _, sqlnamestr := range sqlslist {
  3884. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3885. paramslist := strings.Split(paramslists, ",")
  3886. if len(paramslist) > 0 {
  3887. s_params := make([]interface{}, 0)
  3888. for _, value := range paramslist {
  3889. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3890. if tempv, exists := c.Get("jwt_username"); exists {
  3891. s_params = append(s_params, tempv.(string))
  3892. } else {
  3893. s_params = append(s_params, "")
  3894. }
  3895. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3896. s_params = append(s_params, pastureid)
  3897. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3898. ids, err := setting.SnowIds.NextId()
  3899. if err != nil {
  3900. ids = time.Now().UnixNano()
  3901. logging.Info("create SnowIds err", err)
  3902. }
  3903. s_params = append(s_params, ids)
  3904. } else {
  3905. if outentry[strings.Trim(value, " ")] == nil {
  3906. s_params = append(s_params, "")
  3907. } else {
  3908. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3909. }
  3910. }
  3911. }
  3912. outentry["input"] = inputdata
  3913. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3914. if err != nil {
  3915. errExist = true
  3916. // if tx != nil {
  3917. // tx.Rollback()
  3918. // }
  3919. // if tx != nil {
  3920. // tx.Close()
  3921. // }
  3922. msg := geterrmsg(err.Error())
  3923. outentry["error_msg"] = msg
  3924. error++
  3925. queryData = append(queryData, outentry)
  3926. isdone = true
  3927. break
  3928. } else {
  3929. if len(returnmsgmap1) > 0 {
  3930. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3931. // if tx != nil {
  3932. // tx.Rollback()
  3933. // }
  3934. // if tx != nil {
  3935. // tx.Close()
  3936. // }
  3937. msg := geterrmsg(va.(string))
  3938. outentry["error_msg"] = msg
  3939. error++
  3940. queryData = append(queryData, outentry)
  3941. isdone = true
  3942. break
  3943. }
  3944. }
  3945. isdone = false
  3946. }
  3947. }
  3948. }
  3949. if !errExist {
  3950. dataexcel := make(map[string]interface{}, 0)
  3951. if _, ok := outentry["栏舍名称"]; ok {
  3952. dataexcel["barname"] = outentry["栏舍名称"]
  3953. }
  3954. if _, ok := outentry["实际牛头数"]; ok {
  3955. dataexcel["ccount"] = outentry["实际牛头数"]
  3956. }
  3957. if _, ok := outentry["系数(%)"]; ok {
  3958. dataexcel["ratio"] = outentry["系数(%)"]
  3959. }
  3960. if _, ok := outentry["配方模板"]; ok {
  3961. dataexcel["ftname"] = outentry["配方模板"]
  3962. }
  3963. if _, ok := outentry["补料配方"]; ok {
  3964. dataexcel["ptsfname"] = outentry["补料配方"]
  3965. }
  3966. if _, ok := outentry["第一班比例(%)"]; ok {
  3967. dataexcel["1"] = outentry["第一班比例(%)"]
  3968. }
  3969. if _, ok := outentry["第二班比例(%)"]; ok {
  3970. dataexcel["2"] = outentry["第二班比例(%)"]
  3971. }
  3972. if _, ok := outentry["第三班比例(%)"]; ok {
  3973. dataexcel["3"] = outentry["第三班比例(%)"]
  3974. }
  3975. if _, ok := outentry["第四班比例(%)"]; ok {
  3976. dataexcel["4"] = outentry["第四班比例(%)"]
  3977. }
  3978. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3979. if err != nil {
  3980. logs.Error(err)
  3981. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3982. return
  3983. }
  3984. if !existbar {
  3985. continue
  3986. }
  3987. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  3988. if err != nil {
  3989. logs.Error(err)
  3990. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3991. return
  3992. }
  3993. if !ftexist {
  3994. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3995. if err != nil {
  3996. logs.Error(err)
  3997. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3998. return
  3999. }
  4000. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4001. if err != nil {
  4002. logs.Error(err)
  4003. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4004. return
  4005. }
  4006. }
  4007. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4008. if err != nil {
  4009. logs.Error(err)
  4010. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4011. return
  4012. }
  4013. if !exist {
  4014. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4015. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4016. if err != nil {
  4017. logs.Error(err)
  4018. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4019. return
  4020. }
  4021. }
  4022. var feedpargs []interface{}
  4023. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4024. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4025. if _, ok := dataexcel["ftname"]; ok {
  4026. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4027. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4028. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4029. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4030. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4031. } else {
  4032. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4033. }
  4034. if _, ok := dataexcel["ptsfname"]; ok {
  4035. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4036. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4037. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4038. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4039. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4040. } else {
  4041. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4042. }
  4043. upFeedpSql += " where barname = ? and pastureid = ? "
  4044. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4045. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4046. if err != nil {
  4047. logs.Error(err)
  4048. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4049. return
  4050. }
  4051. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4052. if err != nil {
  4053. logs.Error(err)
  4054. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4055. return
  4056. }
  4057. if !exist1 {
  4058. _, 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) `,
  4059. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4060. if err != nil {
  4061. logs.Error(err)
  4062. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4063. return
  4064. }
  4065. _, 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) `,
  4066. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4067. if err != nil {
  4068. logs.Error(err)
  4069. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4070. return
  4071. }
  4072. _, 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) `,
  4073. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4074. if err != nil {
  4075. logs.Error(err)
  4076. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4077. return
  4078. }
  4079. _, 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) `,
  4080. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4081. if err != nil {
  4082. logs.Error(err)
  4083. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4084. return
  4085. }
  4086. }
  4087. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4088. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4089. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4090. and pastureid = ? and times = ?`
  4091. var fpdargs1 []interface{}
  4092. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4093. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4094. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4095. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4096. if err != nil {
  4097. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4098. return
  4099. }
  4100. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4101. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4102. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4103. // and pastureid = ? and times = ?`
  4104. var fpdargs2 []interface{}
  4105. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4106. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4107. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4108. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4109. if err != nil {
  4110. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4111. return
  4112. }
  4113. var fpdargs3 []interface{}
  4114. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4115. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4116. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4117. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4118. if err != nil {
  4119. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4120. return
  4121. }
  4122. var fpdargs4 []interface{}
  4123. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4124. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4125. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4126. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4127. if err != nil {
  4128. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4129. return
  4130. }
  4131. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4132. 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()
  4133. if err != nil {
  4134. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4135. return
  4136. }
  4137. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4138. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4139. upFpdetailList := make([]*upFpdetail, 0)
  4140. for _, newfpd := range newList {
  4141. for _, oldfpd := range oldFpdList {
  4142. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4143. var oldweight, newweight float64
  4144. if oldfpd["weight"] != nil {
  4145. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4146. }
  4147. if newfpd["weight"] != nil {
  4148. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4149. }
  4150. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4151. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4152. Old: oldweight,
  4153. New: newweight,
  4154. Times: newfpd["times"].(int64),
  4155. Ptid: newfpd["ptid"].(int64),
  4156. Fweight: fweight,
  4157. Id: oldfpd["id"].(int64),
  4158. })
  4159. break
  4160. }
  4161. }
  4162. }
  4163. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4164. }
  4165. }
  4166. if !isdone {
  4167. ok++
  4168. isdone = true
  4169. }
  4170. }
  4171. data := make(map[string]interface{})
  4172. data["result"] = queryData
  4173. data["success"] = ok
  4174. data["err_count"] = error
  4175. appG.Response(http.StatusOK, e.SUCCESS, data)
  4176. }
  4177. type upFpdetail struct {
  4178. Old float64
  4179. New float64
  4180. Times int64
  4181. Ptid int64
  4182. Fweight float64
  4183. Id int64
  4184. // Ptsid string
  4185. }
  4186. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  4187. tx := restful.Engine.NewSession()
  4188. defer tx.Close()
  4189. tx.Begin()
  4190. fpdList, err := tx.SQL(` select id,ifnull(ROUND((1-ptsrate)*weight,2),"") weight,ptuse,times from fpdetail where pastureid = ? and barname = ? order by times `,
  4191. pastureid, barname).Query().List()
  4192. if err != nil {
  4193. logs.Error(err)
  4194. }
  4195. for _, fpd := range fpdList {
  4196. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  4197. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  4198. pastureid, fpd["id"], fpd["times"]).Query().List()
  4199. if err != nil {
  4200. tx.Rollback()
  4201. logs.Error(err)
  4202. return err
  4203. }
  4204. var lweight float64
  4205. for _, lppland := range lpplandList {
  4206. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4207. lweight += lweight1
  4208. }
  4209. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4210. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4211. if fpdweight >= ptuse && lweight == ptuse {
  4212. continue
  4213. } else {
  4214. if lweight <= fpdweight {
  4215. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  4216. if err != nil {
  4217. tx.Rollback()
  4218. logs.Error(err)
  4219. return err
  4220. }
  4221. } else {
  4222. weight := lweight - fpdweight
  4223. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  4224. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  4225. if err != nil {
  4226. tx.Rollback()
  4227. logs.Error(err)
  4228. return err
  4229. }
  4230. for _, lppland := range lpplandList {
  4231. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4232. if weight >= lpplandlweight {
  4233. weight = weight - lpplandlweight
  4234. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  4235. if err != nil {
  4236. tx.Rollback()
  4237. logs.Error(err)
  4238. return err
  4239. }
  4240. } else {
  4241. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4242. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  4243. if err != nil {
  4244. tx.Rollback()
  4245. logs.Error(err)
  4246. return err
  4247. }
  4248. weight = 0
  4249. break
  4250. }
  4251. }
  4252. }
  4253. }
  4254. }
  4255. for _, list := range dataList {
  4256. ftmap := make(map[string]interface{})
  4257. ftmap["old"] = list.Old
  4258. ftmap["new"] = list.New
  4259. ftmap["times"] = list.Times
  4260. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  4261. ftmap["ptsid"] = ""
  4262. // fmt.Println(ftmap)
  4263. fpdDataList, err := tx.SQL(`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 ,
  4264. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  4265. WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  4266. UNION
  4267. 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 ,
  4268. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  4269. WHERE fpdetail.pastureid = ? and barname = ? and times = ? ) t
  4270. order by t.barname,t.times`, pastureid, barname, ftmap["times"], pastureid, barname, ftmap["times"]).Query().List()
  4271. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  4272. if err != nil {
  4273. tx.Rollback()
  4274. logs.Error(err)
  4275. }
  4276. for _, fpd := range fpdDataList {
  4277. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  4278. fttype := -1
  4279. if ftmap["ptid"].(string) != "-1" {
  4280. fttype = 1
  4281. }
  4282. var fweight float64
  4283. var lweight float64
  4284. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4285. err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4286. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4287. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4288. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  4289. if err != nil {
  4290. tx.Rollback()
  4291. logs.Error(err)
  4292. }
  4293. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4294. // ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4295. var w float64
  4296. var status int
  4297. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  4298. if weight >= 0 {
  4299. continue
  4300. }
  4301. w = weight
  4302. status = 0
  4303. } else {
  4304. if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  4305. continue
  4306. }
  4307. w = weight
  4308. status = 1
  4309. }
  4310. for _, lppland := range lpplandtl1List {
  4311. lweight += lppland.Lweight
  4312. }
  4313. for _, lppland := range lpplandtl1List {
  4314. if status == 1 {
  4315. // if w <= lppland.Lweight {
  4316. if lppland.Maxweight <= lweight {
  4317. continue
  4318. }
  4319. if w+lweight <= lppland.Maxweight {
  4320. lppland.Lweight += w
  4321. lweight += w
  4322. fweight += w
  4323. w = 0
  4324. } else {
  4325. w = w - (lppland.Maxweight - lweight)
  4326. n := (lppland.Maxweight - lweight)
  4327. lppland.Lweight = lppland.Lweight + n
  4328. lweight += n
  4329. fweight += n
  4330. }
  4331. } else {
  4332. if lppland.Lweight == 0 {
  4333. continue
  4334. }
  4335. if w+lppland.Lweight >= 0 {
  4336. lppland.Lweight = lppland.Lweight + w
  4337. lweight = lweight + w
  4338. fweight = fweight + w
  4339. w = 0
  4340. } else {
  4341. w = w + lppland.Lweight
  4342. lweight = lweight - lppland.Lweight
  4343. fweight = fweight - lppland.Lweight
  4344. lppland.Lweight = 0
  4345. }
  4346. }
  4347. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4348. if err != nil {
  4349. tx.Rollback()
  4350. logs.Error(err)
  4351. return err
  4352. }
  4353. break
  4354. }
  4355. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4356. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4357. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  4358. if err != nil {
  4359. tx.Rollback()
  4360. logs.Error(err)
  4361. }
  4362. if w == 0 {
  4363. break
  4364. }
  4365. }
  4366. }
  4367. }
  4368. // for _, data := range dataList {
  4369. // fttype := -1
  4370. // if data.Ptid != -1 {
  4371. // fttype = 1
  4372. // }
  4373. // var fweight float64
  4374. // var lweight float64
  4375. // lpplandtl1List := make([]*lpplandtlInfo, 0)
  4376. // err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4377. // join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4378. // and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4379. // data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  4380. // if err != nil {
  4381. // tx.Rollback()
  4382. // logs.Error(err)
  4383. // return err
  4384. // }
  4385. // weight := data.Fweight
  4386. // // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4387. // var w float64
  4388. // var status int
  4389. // if data.New < data.Old {
  4390. // if weight >= 0 {
  4391. // continue
  4392. // }
  4393. // w = weight
  4394. // status = 0
  4395. // } else {
  4396. // // if weight-(data.New-data.Old) > 0 {
  4397. // // continue
  4398. // // }
  4399. // w = data.New - data.Old
  4400. // status = 1
  4401. // }
  4402. // for _, lppland := range lpplandtl1List {
  4403. // var lppdata lpplandtlInfo
  4404. // tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  4405. // lppland.Lppid, pastureid).GetFirst(&lppdata)
  4406. // if err != nil {
  4407. // tx.Rollback()
  4408. // logs.Error(err)
  4409. // return err
  4410. // }
  4411. // lweight = lppdata.Lweight
  4412. // if status == 1 {
  4413. // // if w <= lppland.Lweight {
  4414. // if lppland.Maxweight <= lweight {
  4415. // continue
  4416. // }
  4417. // if w+lweight <= lppland.Maxweight {
  4418. // lppland.Lweight += w
  4419. // lweight += w
  4420. // fweight += w
  4421. // w = 0
  4422. // } else {
  4423. // w = w - (lppland.Maxweight - lweight)
  4424. // n := (lppland.Maxweight - lweight)
  4425. // lppland.Lweight = lppland.Lweight + n
  4426. // lweight += n
  4427. // fweight += n
  4428. // }
  4429. // } else {
  4430. // if lppland.Lweight == 0 {
  4431. // continue
  4432. // }
  4433. // if w+lppland.Lweight >= 0 {
  4434. // lppland.Lweight = lppland.Lweight + w
  4435. // lweight = lweight + w
  4436. // fweight = fweight + w
  4437. // w = 0
  4438. // } else {
  4439. // w = w + lppland.Lweight
  4440. // lweight = lweight - lppland.Lweight
  4441. // fweight = fweight - lppland.Lweight
  4442. // lppland.Lweight = 0
  4443. // }
  4444. // }
  4445. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4446. // if err != nil {
  4447. // tx.Rollback()
  4448. // logs.Error(err)
  4449. // return err
  4450. // }
  4451. // break
  4452. // }
  4453. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4454. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4455. // WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  4456. // if err != nil {
  4457. // tx.Rollback()
  4458. // logs.Error(err)
  4459. // return err
  4460. // }
  4461. // // if w == 0 {
  4462. // // break
  4463. // // }
  4464. // // }
  4465. // }
  4466. err = tx.Commit()
  4467. if err != nil {
  4468. logs.Error(err)
  4469. tx.Rollback()
  4470. return err
  4471. }
  4472. now := time.Now()
  4473. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4474. if err != nil {
  4475. logs.Error(err)
  4476. return nil
  4477. }
  4478. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4479. if err != nil {
  4480. logs.Error(err)
  4481. return nil
  4482. }
  4483. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4484. if err != nil {
  4485. logs.Error(err)
  4486. return nil
  4487. }
  4488. for _, newLpplandtl1 := range newLpplandtl1List {
  4489. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4490. background,cowcount,ccountradio,lweighthis,createdate)
  4491. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4492. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  4493. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  4494. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  4495. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  4496. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  4497. if err != nil {
  4498. logs.Error(err)
  4499. // appG.Response(http.StatusOK, e.ERROR, false)
  4500. return nil
  4501. }
  4502. }
  4503. for _, newFpd := range newFpdDataList {
  4504. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  4505. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  4506. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  4507. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  4508. if err != nil {
  4509. logs.Error(err)
  4510. // appG.Response(http.StatusOK, e.ERROR, false)
  4511. return nil
  4512. }
  4513. }
  4514. for _, newFeedp := range newFeedpList {
  4515. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  4516. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  4517. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4518. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  4519. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  4520. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  4521. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  4522. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  4523. if err != nil {
  4524. logs.Error(err)
  4525. // appG.Response(http.StatusOK, e.ERROR, false)
  4526. return nil
  4527. }
  4528. }
  4529. return nil
  4530. }
  4531. func DeleteFTdetail(c *gin.Context) {
  4532. appG := app.Gin{C: c}
  4533. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4534. fsion := gofasion.NewFasion(string(dataByte))
  4535. parammaps := fsion.Get("parammaps")
  4536. pastureid := parammaps.Get("pastureid").ValueStr()
  4537. ftid := parammaps.Get("ftid").ValueStr()
  4538. tx := restful.Engine.NewSession()
  4539. defer tx.Close()
  4540. tx.Begin()
  4541. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  4542. if err != nil {
  4543. tx.Rollback()
  4544. logs.Error(err)
  4545. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4546. return
  4547. }
  4548. if parammaps.Get("type").ValueStr() == "1" {
  4549. _, err := tx.SQL(`UPDATE feedp fp
  4550. set
  4551. fp.ftweight= IFNULL(IF(
  4552. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4553. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4554. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4555. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4556. ),0),fp.feedweight = IFNULL(IF(
  4557. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4558. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4559. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4560. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4561. ),0) +ifnull(fp.supplyweight,0)
  4562. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4563. if err != nil {
  4564. tx.Rollback()
  4565. logs.Error(err)
  4566. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4567. return
  4568. }
  4569. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  4570. _, err = tx.SQL(`
  4571. UPDATE fpdetail fpd
  4572. INNER JOIN feedp fp
  4573. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4574. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4575. ptuse= 0
  4576. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4577. if err != nil {
  4578. tx.Rollback()
  4579. logs.Error(err)
  4580. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4581. return
  4582. }
  4583. } else {
  4584. _, err := tx.SQL(`UPDATE feedp fp
  4585. SET
  4586. fp.supplyweight= IFNULL(IF(
  4587. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4588. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4589. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4590. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4591. ),0),fp.feedweight = IFNULL(IF(
  4592. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4593. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4594. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4595. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4596. ),0) + ifnull(fp.supplyweight,0)
  4597. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4598. if err != nil {
  4599. tx.Rollback()
  4600. logs.Error(err)
  4601. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4602. return
  4603. }
  4604. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4605. _, err = tx.SQL(`
  4606. UPDATE fpdetail fpd
  4607. INNER JOIN feedp fp
  4608. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4609. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4610. ptsrate = 0
  4611. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4612. if err != nil {
  4613. tx.Rollback()
  4614. logs.Error(err)
  4615. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4616. return
  4617. }
  4618. }
  4619. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  4620. if err != nil {
  4621. tx.Rollback()
  4622. logs.Error(err)
  4623. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4624. return
  4625. }
  4626. err = tx.Commit()
  4627. if err != nil {
  4628. tx.Rollback()
  4629. logs.Error(err)
  4630. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4631. return
  4632. }
  4633. appG.Response(http.StatusOK, e.SUCCESS, true)
  4634. }
  4635. func DeleteSpillageAll(c *gin.Context) {
  4636. appG := app.Gin{C: c}
  4637. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4638. fsion := gofasion.NewFasion(string(dataByte))
  4639. parammaps := fsion.Get("parammaps")
  4640. pastureid := parammaps.Get("pastureid").ValueStr()
  4641. times := parammaps.Get("times").ValueStr()
  4642. barid := parammaps.Get("barid").ValueStr()
  4643. tx := restful.Engine.NewSession()
  4644. defer tx.Close()
  4645. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  4646. if err != nil {
  4647. logs.Error(err)
  4648. appG.Response(http.StatusOK, e.ERROR, false)
  4649. return
  4650. }
  4651. now := time.Now()
  4652. for _, item := range lpplandtl1List {
  4653. go func(item map[string]interface{}) {
  4654. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4655. background,cowcount,ccountradio,lweighthis,createdate)
  4656. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4657. item["pastureid"], item["lppid"], item["barid"],
  4658. item["barname"], item["fpdid"], item["fttype"],
  4659. item["lweight"], item["sort"], item["tmrid"],
  4660. item["tmrname"], item["background"], item["cowcount"],
  4661. item["ccountradio"], item["lweighthis"], now).Execute()
  4662. if err != nil {
  4663. logs.Error(err)
  4664. appG.Response(http.StatusOK, e.ERROR, false)
  4665. return
  4666. }
  4667. }(item)
  4668. }
  4669. tx.Begin()
  4670. _, 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()
  4671. if err != nil {
  4672. tx.Rollback()
  4673. logs.Error(err)
  4674. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4675. return
  4676. }
  4677. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4678. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  4679. if err != nil {
  4680. tx.Rollback()
  4681. logs.Error(err)
  4682. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4683. return
  4684. }
  4685. err = tx.Commit()
  4686. if err != nil {
  4687. tx.Rollback()
  4688. logs.Error(err)
  4689. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4690. return
  4691. }
  4692. appG.Response(http.StatusOK, e.SUCCESS, true)
  4693. }
  4694. func GetTMRListEnableTypeAll(c *gin.Context) {
  4695. appG := app.Gin{C: c}
  4696. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4697. fsion := gofasion.NewFasion(string(dataByte))
  4698. parammaps := fsion.Get("parammaps")
  4699. pastureid := parammaps.Get("pastureid").ValueStr()
  4700. tx := restful.Engine.NewSession()
  4701. defer tx.Close()
  4702. dataList, err := tx.SQL(`SELECT
  4703. eqcode,
  4704. tname,
  4705. datacaptureno,
  4706. trim(tclassid) tclassid,
  4707. concat(tname,' / ',eqcode) tmrmix,
  4708. d.label tclassname,
  4709. maxstirfeed,
  4710. remark,
  4711. tmr.enable,
  4712. TRIM(tmr.id) id,
  4713. TRIM(tmr.pastureid)pastureid
  4714. FROM
  4715. tmr
  4716. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  4717. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  4718. ORDER BY id DESC`, pastureid).Query().List()
  4719. if err != nil {
  4720. logs.Error(err)
  4721. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4722. return
  4723. }
  4724. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  4725. if err != nil {
  4726. logs.Error(err)
  4727. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4728. return
  4729. }
  4730. var carNum int64
  4731. for _, sysopt := range sysoptData {
  4732. if sysopt["inforvalue"] == nil {
  4733. carNum = 1
  4734. } else {
  4735. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  4736. }
  4737. }
  4738. id := 200
  4739. n := 0
  4740. for i := carNum; i > 0; i-- {
  4741. id++
  4742. n++
  4743. data := make(map[string]interface{}, 0)
  4744. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  4745. data["tname"] = fmt.Sprintf("任意车%d", n)
  4746. data["datacaptureno"] = -2
  4747. data["tclassid"] = -2
  4748. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  4749. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  4750. data["maxstirfeed"] = 100000
  4751. data["remark"] = fmt.Sprintf("任意车%d", n)
  4752. data["enable"] = 1
  4753. data["id"] = fmt.Sprintf("%d", id)
  4754. data["pastureid"] = pastureid
  4755. dataList = append(dataList, data)
  4756. }
  4757. // UNION ALL
  4758. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  4759. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4760. }
  4761. func GetFeedpHistory(c *gin.Context) {
  4762. appG := app.Gin{C: c}
  4763. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4764. fsion := gofasion.NewFasion(string(dataByte))
  4765. // parammaps := fsion.Get("parammaps")
  4766. bar := fsion.Get("barname").ValueStr()
  4767. startDate := fsion.Get("startDate").ValueStr()
  4768. endDate := fsion.Get("endDate").ValueStr()
  4769. tx := restful.Engine.NewSession()
  4770. defer tx.Close()
  4771. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4772. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  4773. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  4774. if err != nil {
  4775. logs.Error(err)
  4776. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4777. return
  4778. }
  4779. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from fpdetailhistory where barname = ?
  4780. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  4781. if err != nil {
  4782. logs.Error(err)
  4783. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4784. return
  4785. }
  4786. for _, feedp := range feedpList {
  4787. // LastftList, err := tx.SQL(` select tname ,id
  4788. // from feedtemplethistory where id = ?
  4789. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  4790. // if err != nil {
  4791. // logs.Error(err)
  4792. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4793. // return
  4794. // }
  4795. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4796. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  4797. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  4798. if err != nil {
  4799. logs.Error(err)
  4800. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4801. return
  4802. }
  4803. var ftname interface{}
  4804. ftnamestatus := 0
  4805. ftname = feedp["ftname"]
  4806. var lastftid int64
  4807. if len(nextfeedpList) > 0 {
  4808. for _, ft := range nextfeedpList {
  4809. if ft["ftname"].(string) != feedp["ftname"].(string) {
  4810. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  4811. lastftid = ft["ftid"].(int64)
  4812. ftnamestatus = 1
  4813. break
  4814. }
  4815. }
  4816. }
  4817. for i, fpd := range fpdList {
  4818. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4819. fpd["weightstatus"] = 0
  4820. fpd["tratiostatus"] = 0
  4821. fpd["ftnamestatus"] = ftnamestatus
  4822. for k, fpd2 := range fpdList {
  4823. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4824. if fpd["weight"].(string) != fpd2["weight"].(string) {
  4825. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4826. fpd["weightstatus"] = 1
  4827. }
  4828. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  4829. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  4830. fpd["tratiostatus"] = 1
  4831. }
  4832. break
  4833. }
  4834. }
  4835. fpd["barid"] = feedp["barid"]
  4836. fpd["barname"] = feedp["barname"]
  4837. fpd["ccount"] = feedp["ccount"]
  4838. fpd["ratio"] = feedp["ratio"]
  4839. fpd["ccountratio"] = feedp["ccountratio"]
  4840. fpd["ftid"] = feedp["ftid"]
  4841. fpd["ftname"] = ftname
  4842. fpd["ccountstatus"] = 0
  4843. fpd["ccountratiostatus"] = 0
  4844. fpd["ratiostatus"] = 0
  4845. fpd["ftnamestatus"] = 0
  4846. fpd["lastftid"] = lastftid
  4847. for _, next := range nextfeedpList {
  4848. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  4849. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  4850. fpd["ccountstatus"] = 1
  4851. }
  4852. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  4853. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  4854. fpd["ccountratiostatus"] = 1
  4855. }
  4856. if next["ratio"].(string) != fpd["ratio"].(string) {
  4857. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  4858. fpd["ratiostatus"] = 1
  4859. }
  4860. // if next["ftname"].(string) != fpd["ftname"].(string) {
  4861. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  4862. // fpd["ftnamestatus"] = 1
  4863. // }
  4864. }
  4865. }
  4866. }
  4867. }
  4868. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  4869. }
  4870. // func GetLpplandtl1History(c *gin.Context) {
  4871. // appG := app.Gin{C: c}
  4872. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4873. // fsion := gofasion.NewFasion(string(dataByte))
  4874. // // parammaps := fsion.Get("parammaps")
  4875. // barid := fsion.Get("barid").ValueStr()
  4876. // startDate := fsion.Get("startDate").ValueStr()
  4877. // endDate := fsion.Get("endDate").ValueStr()
  4878. // tx := restful.Engine.NewSession()
  4879. // defer tx.Close()
  4880. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  4881. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  4882. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  4883. // // if err != nil {
  4884. // // logs.Error(err)
  4885. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4886. // // return
  4887. // // }
  4888. // // for _, feedp := range feedpList {
  4889. // // fmt.Println(feedp)
  4890. // // for i, fpd := range fpdList {
  4891. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4892. // // for k, fpd2 := range fpdList {
  4893. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4894. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  4895. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4896. // // }
  4897. // // break
  4898. // // }
  4899. // // }
  4900. // // fpd["barid"] = feedp["barid"]
  4901. // // fpd["barname"] = feedp["barname"]
  4902. // // fpd["ccount"] = feedp["ccount"]
  4903. // // fpd["ratio"] = feedp["ratio"]
  4904. // // fpd["ccountratio"] = feedp["ccountratio"]
  4905. // // fpd["ftid"] = feedp["ftid"]
  4906. // // fpd["ftname"] = feedp["ftname"]
  4907. // // }
  4908. // // }
  4909. // // }
  4910. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  4911. // }
  4912. func GetRemind(c *gin.Context) {
  4913. appG := app.Gin{C: c}
  4914. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4915. fsion := gofasion.NewFasion(string(dataByte))
  4916. parammaps := fsion.Get("parammaps")
  4917. pastureid := parammaps.Get("pastureid").ValueStr()
  4918. tx := restful.Engine.NewSession()
  4919. defer tx.Close()
  4920. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  4921. if err != nil {
  4922. logs.Error(err)
  4923. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4924. return
  4925. }
  4926. // pastureid = "3"
  4927. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  4928. if err != nil {
  4929. logs.Error(err)
  4930. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4931. return
  4932. }
  4933. defer resp.Body.Close()
  4934. buf := bytes.NewBuffer(make([]byte, 0, 512))
  4935. buf.ReadFrom(resp.Body)
  4936. fmt.Println(string(buf.Bytes()))
  4937. respMap := make(map[string]interface{}, 0)
  4938. err = json.Unmarshal(buf.Bytes(), &respMap)
  4939. if err != nil {
  4940. logs.Error(err)
  4941. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4942. return
  4943. }
  4944. for _, data := range dataList {
  4945. r := make(map[string]interface{}, 0)
  4946. r["sys_name"] = ""
  4947. r["service_id"] = ""
  4948. r["pasture_id"] = ""
  4949. r["type_name"] = ""
  4950. r["remind_type_id"] = ""
  4951. r["remind_type"] = ""
  4952. r["push_date"] = ""
  4953. r["push_time"] = ""
  4954. r["interval_time"] = ""
  4955. r["push_limit"] = ""
  4956. r["template_id"] = ""
  4957. r["roles_id"] = ""
  4958. r["users_id"] = ""
  4959. r["date_type"] = ""
  4960. r["cycle_type"] = ""
  4961. data["data"] = r
  4962. for _, resp := range respMap["data"].([]interface{}) {
  4963. resp1 := resp.(map[string]interface{})
  4964. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  4965. if resp1["push_time"] == nil {
  4966. resp1["push_time"] = ""
  4967. }
  4968. data["data"] = resp1
  4969. break
  4970. }
  4971. }
  4972. }
  4973. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4974. }
  4975. type NoticeMsgtype struct {
  4976. SysName string `json:"sys_name"`
  4977. PastureId int64 `json:"pasture_id"`
  4978. ServiceId int64 `json:"service_id"`
  4979. TypeName string `json:"type_name"`
  4980. RemindType int64 `json:"remind_type"`
  4981. PushDate int64 `json:"push_date"`
  4982. PushTime string `json:"push_time"`
  4983. IntervalTime int64 `json:"interval_time"`
  4984. PushLimit int64 `json:"push_limit"`
  4985. TemplateId string `json:"template_id"`
  4986. UsersId string `json:"users_id"`
  4987. DateType int64 `json:"date_type"`
  4988. CycleType int64 `json:"cycle_type"`
  4989. DelayTime int64 `json:"delay_time"`
  4990. Status int64 `json:"status"`
  4991. }
  4992. func UpdateRemind(c *gin.Context) {
  4993. appG := app.Gin{C: c}
  4994. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4995. parammaps := gofasion.NewFasion(string(dataByte))
  4996. // parammaps := fsion.Get("parammaps")
  4997. // user := parammaps.Get("user").ValueStr()
  4998. id := parammaps.Get("id").ValueInt64()
  4999. noticeMsgtype := new(NoticeMsgtype)
  5000. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  5001. noticeMsgtype.ServiceId = id
  5002. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  5003. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  5004. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  5005. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  5006. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  5007. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  5008. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  5009. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  5010. noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  5011. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  5012. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  5013. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  5014. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  5015. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  5016. //TODO
  5017. noticeMsgtype.SysName = "tmrWatch"
  5018. userList := parammaps.Get("user").Array()
  5019. var userstr []string
  5020. for _, user := range userList {
  5021. userstr = append(userstr, user.ValueStr())
  5022. }
  5023. tx := restful.Engine.NewSession()
  5024. defer tx.Close()
  5025. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  5026. if err != nil {
  5027. logs.Error(err)
  5028. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5029. return
  5030. }
  5031. // var jsonStr = []byte(noticeMsgtype
  5032. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  5033. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  5034. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  5035. req.Header.Set("Content-Type", "application/json")
  5036. client := &http.Client{}
  5037. resp, err := client.Do(req)
  5038. if err != nil {
  5039. logs.Error(err)
  5040. }
  5041. defer resp.Body.Close()
  5042. body, _ := ioutil.ReadAll(resp.Body)
  5043. fmt.Println("response Body:", string(body))
  5044. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  5045. if err != nil {
  5046. logs.Error(err)
  5047. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5048. return
  5049. }
  5050. defer getresp.Body.Close()
  5051. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5052. buf.ReadFrom(getresp.Body)
  5053. // fmt.Println(string(buf.Bytes()))
  5054. respMap := make(map[string]interface{}, 0)
  5055. err = json.Unmarshal(buf.Bytes(), &respMap)
  5056. if err != nil {
  5057. logs.Error(err)
  5058. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5059. return
  5060. }
  5061. for _, resp := range respMap["data"].([]interface{}) {
  5062. resp1 := resp.(map[string]interface{})
  5063. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  5064. if err != nil {
  5065. logs.Error(err)
  5066. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5067. return
  5068. }
  5069. }
  5070. appG.Response(http.StatusOK, e.SUCCESS, true)
  5071. }
  5072. func GetSpillageallHistory(c *gin.Context) {
  5073. appG := app.Gin{C: c}
  5074. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5075. parammaps := gofasion.NewFasion(string(dataByte))
  5076. barname := parammaps.Get("barname").ValueStr()
  5077. pastureid := parammaps.Get("pastureid").ValueStr()
  5078. startdate := parammaps.Get("startDate").ValueStr()
  5079. enddate := parammaps.Get("endDate").ValueStr()
  5080. tx := restful.Engine.NewSession()
  5081. defer tx.Close()
  5082. 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
  5083. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  5084. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  5085. if err != nil {
  5086. logs.Error(err)
  5087. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5088. return
  5089. }
  5090. respMap := make([]map[string]interface{}, 0)
  5091. data := make(map[interface{}]interface{})
  5092. for _, history := range historyList {
  5093. data[history["createdate"]] = history["createdate"]
  5094. }
  5095. createList := []string{}
  5096. for _, v := range data {
  5097. createList = append(createList, v.(string))
  5098. }
  5099. // sort.Sort()
  5100. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  5101. sort.Slice(createList, func(i, j int) bool {
  5102. return createList[i] > createList[j]
  5103. })
  5104. for _, v := range createList {
  5105. a := make(map[string]interface{})
  5106. a["createdate"] = data[v]
  5107. // createList = append(createList, v.(string))
  5108. respMap = append(respMap, a)
  5109. }
  5110. number := 0
  5111. dataMap := make([]interface{}, 0)
  5112. for k, resp := range respMap {
  5113. createdate := resp["createdate"].(string)
  5114. var nextcreatedate string
  5115. if len(respMap) > k+1 {
  5116. nextcreatedate = respMap[k+1]["createdate"].(string)
  5117. }
  5118. // dataList := make(map[string][]interface{})
  5119. // list := make(map[string]interface{})
  5120. times := make(map[interface{}]int)
  5121. for _, history := range historyList {
  5122. // List := make(map[interface{}][]interface{})
  5123. i := 0
  5124. if history["createdate"].(string) == createdate {
  5125. times[history["times"]]++
  5126. data := make(map[string]interface{})
  5127. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  5128. // exist := false
  5129. if nextcreatedate != "" {
  5130. for _, history1 := range historyList {
  5131. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  5132. history1["times"].(int64) == history["times"].(int64) {
  5133. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", data[fmt.Sprintf("a%d", times[history["times"]])], history["lweight"])
  5134. break
  5135. // exist = true
  5136. }
  5137. }
  5138. }
  5139. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5140. i++
  5141. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  5142. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  5143. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  5144. // resp["times"] = history["times"]
  5145. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5146. data1 := make(map[string]interface{})
  5147. data1["times"] = history["times"]
  5148. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5149. data1["createdate"] = resp["createdate"]
  5150. // fmt.Println(dataList)
  5151. dataMap = append(dataMap, data1)
  5152. }
  5153. if i > number {
  5154. number = i
  5155. }
  5156. // respMap = append(respMap, dataList)
  5157. }
  5158. // for k, data := range dataList {
  5159. // resp[k] = data
  5160. // }
  5161. // resp["data"] = dataList
  5162. }
  5163. // resp := make(map[string]interface{})
  5164. // sort.Strings(createList)
  5165. //
  5166. // for _, create := range createList {
  5167. // for _, r := range respMap {
  5168. // if create == r["createdate"].(string) {
  5169. // resp[create] = r
  5170. // break
  5171. // }
  5172. // }
  5173. // }
  5174. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  5175. var trainsList []interface{}
  5176. for i := 0; i < number; i++ {
  5177. trains := make(map[string]interface{})
  5178. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  5179. trains["prop"] = fmt.Sprintf("a%d", i+1)
  5180. trainsList = append(trainsList, trains)
  5181. }
  5182. respdata := make(map[string]interface{})
  5183. respdata["data"] = dataMap
  5184. respdata["trains"] = trainsList
  5185. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  5186. }
  5187. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  5188. appG := app.Gin{C: c}
  5189. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5190. parammaps := gofasion.NewFasion(string(dataByte))
  5191. ftid := parammaps.Get("ftid").ValueInt64()
  5192. lastftid := parammaps.Get("lastftid").ValueInt64()
  5193. pastureid := parammaps.Get("pastureid").ValueInt64()
  5194. // createdate := parammaps.Get("createdate").ValueStr()
  5195. tx := restful.Engine.NewSession()
  5196. defer tx.Close()
  5197. data := make(map[string]interface{})
  5198. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5199. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  5200. if err != nil {
  5201. logs.Error(err)
  5202. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5203. return
  5204. }
  5205. feedtemplet := make(map[string]interface{})
  5206. for _, f := range feedtempletList {
  5207. feedtemplet = f
  5208. }
  5209. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  5210. if err != nil {
  5211. logs.Error(err)
  5212. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5213. return
  5214. }
  5215. feedtemplet["fit"] = fitList
  5216. data["current"] = feedtemplet
  5217. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5218. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  5219. if err != nil {
  5220. logs.Error(err)
  5221. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5222. return
  5223. }
  5224. lastfeedtemplet := make(map[string]interface{})
  5225. for _, f := range lastfeedtempletList {
  5226. lastfeedtemplet = f
  5227. }
  5228. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  5229. if err != nil {
  5230. logs.Error(err)
  5231. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5232. return
  5233. }
  5234. lastfeedtemplet["fit"] = lastfitList
  5235. data["last"] = lastfeedtemplet
  5236. appG.Response(http.StatusOK, e.SUCCESS, data)
  5237. }
  5238. func GetFeedtempletHistory(c *gin.Context) {
  5239. appG := app.Gin{C: c}
  5240. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5241. parammaps := gofasion.NewFasion(string(dataByte))
  5242. ftid := parammaps.Get("ftid").ValueStr()
  5243. pastureid := parammaps.Get("pastureid").ValueInt64()
  5244. start := parammaps.Get("startdate").ValueStr()
  5245. end := parammaps.Get("enddate").ValueStr()
  5246. tx := restful.Engine.NewSession()
  5247. defer tx.Close()
  5248. ftList, err := tx.SQL(` select *,DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate1 from feedtemplethistory where createdate between ? and ?
  5249. and id = ? and pastureid = ? order by createdate desc `,
  5250. start, end, ftid, pastureid).Query().List()
  5251. if err != nil {
  5252. logs.Error(err)
  5253. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5254. return
  5255. }
  5256. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  5257. ftid, pastureid).Query().List()
  5258. if err != nil {
  5259. logs.Error(err)
  5260. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5261. return
  5262. }
  5263. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  5264. for i, ft := range ftList {
  5265. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  5266. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  5267. 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
  5268. where fit.fitid = ?
  5269. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  5270. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  5271. if err != nil {
  5272. logs.Error(err)
  5273. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5274. return
  5275. }
  5276. ft["createdate"] = ft["createdate1"]
  5277. // data["tname"] = ft["tname"]
  5278. // data["tcode"] = ft["tcode"]
  5279. // data["tcolor"] = ft["tcolor"]
  5280. // data["fttype"] = ft["fttype"]
  5281. // data["ccname"] = ft["ccname"]
  5282. // data["source"] = ft["source"]
  5283. // data["version"] = ft["version"]
  5284. // data["remark"] = ft["remark"]
  5285. for n, ft2 := range ftList {
  5286. if i < n {
  5287. if ft["tname"].(string) != ft2["tname"].(string) {
  5288. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  5289. }
  5290. if _, ok := ft["tcode"]; ok {
  5291. if _, ok := ft2["tcode"]; ok {
  5292. if ft["tcode"].(string) != ft2["tcode"].(string) {
  5293. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  5294. }
  5295. }
  5296. }
  5297. if _, ok := ft["tcolor"]; ok {
  5298. if _, ok := ft2["tcolor"]; ok {
  5299. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  5300. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  5301. }
  5302. }
  5303. }
  5304. if _, ok := ft["fttype"]; ok {
  5305. if _, ok := ft2["fttype"]; ok {
  5306. if ft["fttype"].(string) != ft2["fttype"].(string) {
  5307. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  5308. }
  5309. }
  5310. }
  5311. if _, ok := ft["ccname"]; ok {
  5312. if _, ok := ft2["ccname"]; ok {
  5313. if ft["ccname"].(string) != ft2["ccname"].(string) {
  5314. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  5315. }
  5316. }
  5317. }
  5318. if _, ok := ft["source"]; ok {
  5319. if _, ok := ft2["source"]; ok {
  5320. if ft["source"].(string) != ft2["source"].(string) {
  5321. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  5322. }
  5323. }
  5324. }
  5325. if _, ok := ft["version"]; ok {
  5326. if _, ok := ft2["version"]; ok {
  5327. if ft["version"].(int64) != ft2["version"].(int64) {
  5328. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  5329. }
  5330. }
  5331. }
  5332. if _, ok := ft["remark"]; ok {
  5333. if _, ok := ft2["remark"]; ok {
  5334. if ft["remark"].(string) != ft2["remark"].(string) {
  5335. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  5336. }
  5337. }
  5338. }
  5339. break
  5340. }
  5341. }
  5342. dataList := make([]map[string]interface{}, 0)
  5343. if len(fithisList) > 0 {
  5344. for _, fit := range fithisList {
  5345. data := make(map[string]interface{})
  5346. data["feedgroup"] = fit["feedgroup"]
  5347. data["fname"] = fit["fname"]
  5348. if fit["Eweight"] != nil {
  5349. if fit["Eweight"].(string) != fit["weight"].(string) {
  5350. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  5351. } else {
  5352. data["fweight"] = fit["Eweight"]
  5353. }
  5354. data["fweightstatus"] = 1
  5355. } else {
  5356. data["fweight"] = fit["weight"]
  5357. data["fweightstatus"] = 0
  5358. }
  5359. data["autosecond"] = fit["autosecond"]
  5360. // data["tname"] = ft["tname"]
  5361. // data["tcode"] = ft["tcode"]
  5362. // data["tcolor"] = ft["tcolor"]
  5363. // data["fttype"] = ft["fttype"]
  5364. // data["ccname"] = ft["ccname"]
  5365. // data["source"] = ft["source"]
  5366. // data["version"] = ft["version"]
  5367. // data["remark"] = ft["remark"]
  5368. // data["createdate"] = ft["createdate1"]
  5369. // ft["fit"] = data
  5370. dataList = append(dataList, data)
  5371. }
  5372. } else {
  5373. for _, fit := range ftdetailList {
  5374. data := make(map[string]interface{})
  5375. data["feedgroup"] = fit["feedgroup"]
  5376. data["fname"] = fit["fname"]
  5377. // if fit["Eweight"] != nil {
  5378. // data["weight"] = fit["Eweight"]
  5379. // } else {
  5380. data["fweight"] = fit["fweight"]
  5381. // }
  5382. data["autosecond"] = fit["autosecond"]
  5383. // ft["fit"] = data
  5384. dataList = append(dataList, data)
  5385. }
  5386. }
  5387. ft["fit"] = dataList
  5388. }
  5389. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  5390. }
  5391. func UpdateMaterialTMR(c *gin.Context) {
  5392. appG := app.Gin{C: c}
  5393. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5394. parammaps := gofasion.NewFasion(string(dataByte))
  5395. tmrid := parammaps.Get("tmrid").ValueStr()
  5396. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5397. lppid := parammaps.Get("lppid").ValueStr()
  5398. times := parammaps.Get("times").ValueStr()
  5399. pastureid := parammaps.Get("pastureid").ValueStr()
  5400. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  5401. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5402. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5403. tx := restful.Engine.NewSession()
  5404. defer tx.Close()
  5405. tx.Begin()
  5406. if tmrid != "1000" {
  5407. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5408. if err != nil {
  5409. logs.Error(err)
  5410. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5411. return
  5412. }
  5413. var maxstirfeed float64
  5414. for _, tmr := range tmrList {
  5415. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5416. }
  5417. if status == 0 {
  5418. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5419. if err != nil {
  5420. tx.Rollback()
  5421. logs.Error(err)
  5422. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5423. return
  5424. }
  5425. var lweight float64
  5426. for _, item := range lpplandtl1List {
  5427. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5428. lweight += fl
  5429. }
  5430. if lweight > maxstirfeed {
  5431. lweight = lweight - maxstirfeed
  5432. } else {
  5433. lweight = 0
  5434. }
  5435. if lweight > 0 {
  5436. lweight1 := lweight / float64(len(lpplandtl1List))
  5437. number := 0
  5438. for _, item := range lpplandtl1List {
  5439. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5440. if lweight1 >= fl {
  5441. number++
  5442. }
  5443. }
  5444. lweight := lweight / float64((len(lpplandtl1List) - number))
  5445. for _, item := range lpplandtl1List {
  5446. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5447. if lweight1 >= fl {
  5448. continue
  5449. }
  5450. if tmrtype == "1" {
  5451. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  5452. if err != nil {
  5453. tx.Rollback()
  5454. logs.Error(err)
  5455. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5456. return
  5457. }
  5458. } else if tmrtype == "2" {
  5459. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  5460. if err != nil {
  5461. tx.Rollback()
  5462. logs.Error(err)
  5463. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5464. return
  5465. }
  5466. }
  5467. if item["fttype"].(int64) == 0 {
  5468. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5469. if err != nil {
  5470. tx.Rollback()
  5471. logs.Error(err)
  5472. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5473. return
  5474. }
  5475. } else {
  5476. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5477. if err != nil {
  5478. tx.Rollback()
  5479. logs.Error(err)
  5480. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5481. return
  5482. }
  5483. }
  5484. }
  5485. } else {
  5486. for _, item := range lpplandtl1List {
  5487. // 自走式
  5488. if tmrtype == "1" {
  5489. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5490. if err != nil {
  5491. logs.Error(err)
  5492. tx.Rollback()
  5493. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5494. return
  5495. }
  5496. } else if tmrtype == "2" {
  5497. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5498. if err != nil {
  5499. logs.Error(err)
  5500. tx.Rollback()
  5501. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5502. return
  5503. }
  5504. }
  5505. }
  5506. }
  5507. } else if status == 1 {
  5508. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5509. if err != nil {
  5510. logs.Error(err)
  5511. tx.Rollback()
  5512. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5513. return
  5514. }
  5515. var lweight float64
  5516. for _, item := range lpplandtl1List {
  5517. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5518. lweight += fl
  5519. }
  5520. if lweight > maxstirfeed {
  5521. lweight = lweight - maxstirfeed
  5522. } else {
  5523. lweight = 0
  5524. }
  5525. for _, item := range lpplandtl1List {
  5526. if lweight > 0 {
  5527. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5528. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5529. if fl >= lweight {
  5530. item["lweight"] = fl - lweight
  5531. lweight = 0
  5532. if tmrtype == "1" {
  5533. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  5534. if err != nil {
  5535. logs.Error(err)
  5536. tx.Rollback()
  5537. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5538. return
  5539. }
  5540. } else if tmrtype == "2" {
  5541. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  5542. if err != nil {
  5543. logs.Error(err)
  5544. tx.Rollback()
  5545. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5546. return
  5547. }
  5548. }
  5549. if item["fttype"].(int64) == 0 {
  5550. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5551. if err != nil {
  5552. logs.Error(err)
  5553. tx.Rollback()
  5554. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5555. return
  5556. }
  5557. } else {
  5558. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5559. if err != nil {
  5560. logs.Error(err)
  5561. tx.Rollback()
  5562. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5563. return
  5564. }
  5565. }
  5566. } else {
  5567. lweight = lweight - fl
  5568. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  5569. if err != nil {
  5570. logs.Error(err)
  5571. tx.Rollback()
  5572. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5573. return
  5574. }
  5575. if item["fttype"].(int64) == 0 {
  5576. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5577. if err != nil {
  5578. logs.Error(err)
  5579. tx.Rollback()
  5580. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5581. return
  5582. }
  5583. } else {
  5584. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5585. if err != nil {
  5586. logs.Error(err)
  5587. tx.Rollback()
  5588. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5589. return
  5590. }
  5591. }
  5592. }
  5593. } else {
  5594. // 自走式
  5595. if tmrtype == "1" {
  5596. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5597. if err != nil {
  5598. logs.Error(err)
  5599. tx.Rollback()
  5600. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5601. return
  5602. }
  5603. } else if tmrtype == "2" {
  5604. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5605. if err != nil {
  5606. logs.Error(err)
  5607. tx.Rollback()
  5608. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5609. return
  5610. }
  5611. }
  5612. }
  5613. }
  5614. } else {
  5615. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  5616. if err != nil {
  5617. logs.Error(err)
  5618. tx.Rollback()
  5619. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5620. return
  5621. }
  5622. for _, item := range lpplandtl1List {
  5623. if item["fttype"].(int64) == 0 {
  5624. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5625. if err != nil {
  5626. logs.Error(err)
  5627. tx.Rollback()
  5628. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5629. return
  5630. }
  5631. } else {
  5632. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5633. if err != nil {
  5634. logs.Error(err)
  5635. tx.Rollback()
  5636. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5637. return
  5638. }
  5639. }
  5640. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  5641. if err != nil {
  5642. logs.Error(err)
  5643. tx.Rollback()
  5644. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5645. return
  5646. }
  5647. }
  5648. }
  5649. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  5650. if err != nil {
  5651. logs.Error(err)
  5652. tx.Rollback()
  5653. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5654. return
  5655. }
  5656. } else {
  5657. if status == 2 {
  5658. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  5659. if err != nil {
  5660. logs.Error(err)
  5661. tx.Rollback()
  5662. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5663. return
  5664. }
  5665. for _, item := range lpplandtl1List {
  5666. if item["fttype"].(int64) == 0 {
  5667. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5668. if err != nil {
  5669. logs.Error(err)
  5670. tx.Rollback()
  5671. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5672. return
  5673. }
  5674. } else {
  5675. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5676. if err != nil {
  5677. logs.Error(err)
  5678. tx.Rollback()
  5679. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5680. return
  5681. }
  5682. }
  5683. }
  5684. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  5685. if err != nil {
  5686. logs.Error(err)
  5687. tx.Rollback()
  5688. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5689. return
  5690. }
  5691. } else {
  5692. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  5693. if err != nil {
  5694. logs.Error(err)
  5695. tx.Rollback()
  5696. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5697. return
  5698. }
  5699. }
  5700. }
  5701. err := tx.Commit()
  5702. if err != nil {
  5703. logs.Error(err)
  5704. tx.Rollback()
  5705. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5706. return
  5707. }
  5708. appG.Response(http.StatusOK, e.SUCCESS, true)
  5709. }
  5710. func UpdateMaterialTMRDate(c *gin.Context) {
  5711. appG := app.Gin{C: c}
  5712. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5713. parammaps := gofasion.NewFasion(string(dataByte))
  5714. tmrid := parammaps.Get("tmrid").ValueStr()
  5715. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5716. lppid := parammaps.Get("lppid").ValueStr()
  5717. times := parammaps.Get("times").ValueStr()
  5718. pastureid := parammaps.Get("pastureid").ValueStr()
  5719. date := parammaps.Get("date").ValueStr()
  5720. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5721. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5722. tx := restful.Engine.NewSession()
  5723. defer tx.Close()
  5724. tx.Begin()
  5725. if tmrid != "1000" {
  5726. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5727. if err != nil {
  5728. logs.Error(err)
  5729. tx.Rollback()
  5730. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5731. return
  5732. }
  5733. var maxstirfeed float64
  5734. for _, tmr := range tmrList {
  5735. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5736. }
  5737. if status == 0 {
  5738. 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()
  5739. if err != nil {
  5740. logs.Error(err)
  5741. tx.Rollback()
  5742. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5743. return
  5744. }
  5745. var lweight float64
  5746. for _, item := range lpplandtl1List {
  5747. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5748. lweight += fl
  5749. }
  5750. if lweight > maxstirfeed {
  5751. lweight = lweight - maxstirfeed
  5752. } else {
  5753. lweight = 0
  5754. }
  5755. if lweight > 0 {
  5756. lweight1 := lweight / float64(len(lpplandtl1List))
  5757. number := 0
  5758. for _, item := range lpplandtl1List {
  5759. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5760. if lweight1 >= fl {
  5761. number++
  5762. }
  5763. }
  5764. lweight := lweight / float64((len(lpplandtl1List) - number))
  5765. for _, item := range lpplandtl1List {
  5766. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5767. if lweight1 >= fl {
  5768. continue
  5769. }
  5770. if tmrtype == "1" {
  5771. _, 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()
  5772. if err != nil {
  5773. logs.Error(err)
  5774. tx.Rollback()
  5775. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5776. return
  5777. }
  5778. } else if tmrtype == "2" {
  5779. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  5780. if err != nil {
  5781. logs.Error(err)
  5782. tx.Rollback()
  5783. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5784. return
  5785. }
  5786. }
  5787. if item["fttype"].(int64) == 0 {
  5788. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5789. if err != nil {
  5790. logs.Error(err)
  5791. tx.Rollback()
  5792. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5793. return
  5794. }
  5795. } else {
  5796. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5797. if err != nil {
  5798. logs.Error(err)
  5799. tx.Rollback()
  5800. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5801. return
  5802. }
  5803. }
  5804. }
  5805. } else {
  5806. for _, item := range lpplandtl1List {
  5807. // 自走式
  5808. if tmrtype == "1" {
  5809. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5810. if err != nil {
  5811. logs.Error(err)
  5812. tx.Rollback()
  5813. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5814. return
  5815. }
  5816. } else if tmrtype == "2" {
  5817. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5818. if err != nil {
  5819. logs.Error(err)
  5820. tx.Rollback()
  5821. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5822. return
  5823. }
  5824. }
  5825. }
  5826. }
  5827. } else if status == 1 {
  5828. 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()
  5829. if err != nil {
  5830. logs.Error(err)
  5831. tx.Rollback()
  5832. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5833. return
  5834. }
  5835. var lweight float64
  5836. for _, item := range lpplandtl1List {
  5837. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5838. lweight += fl
  5839. }
  5840. if lweight > maxstirfeed {
  5841. lweight = lweight - maxstirfeed
  5842. } else {
  5843. lweight = 0
  5844. }
  5845. for _, item := range lpplandtl1List {
  5846. if lweight > 0 {
  5847. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5848. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5849. if fl >= lweight {
  5850. item["lweight"] = fl - lweight
  5851. lweight = 0
  5852. if tmrtype == "1" {
  5853. _, 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()
  5854. if err != nil {
  5855. logs.Error(err)
  5856. tx.Rollback()
  5857. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5858. return
  5859. }
  5860. } else if tmrtype == "2" {
  5861. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  5862. if err != nil {
  5863. logs.Error(err)
  5864. tx.Rollback()
  5865. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5866. return
  5867. }
  5868. }
  5869. if item["fttype"].(int64) == 0 {
  5870. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5871. if err != nil {
  5872. logs.Error(err)
  5873. tx.Rollback()
  5874. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5875. return
  5876. }
  5877. } else {
  5878. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5879. if err != nil {
  5880. logs.Error(err)
  5881. tx.Rollback()
  5882. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5883. return
  5884. }
  5885. }
  5886. } else {
  5887. lweight = lweight - fl
  5888. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  5889. if err != nil {
  5890. logs.Error(err)
  5891. tx.Rollback()
  5892. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5893. return
  5894. }
  5895. if item["fttype"].(int64) == 0 {
  5896. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5897. if err != nil {
  5898. logs.Error(err)
  5899. tx.Rollback()
  5900. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5901. return
  5902. }
  5903. } else {
  5904. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5905. if err != nil {
  5906. logs.Error(err)
  5907. tx.Rollback()
  5908. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5909. return
  5910. }
  5911. }
  5912. }
  5913. } else {
  5914. // 自走式
  5915. if tmrtype == "1" {
  5916. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5917. if err != nil {
  5918. logs.Error(err)
  5919. tx.Rollback()
  5920. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5921. return
  5922. }
  5923. } else if tmrtype == "2" {
  5924. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5925. if err != nil {
  5926. logs.Error(err)
  5927. tx.Rollback()
  5928. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5929. return
  5930. }
  5931. }
  5932. }
  5933. }
  5934. } else {
  5935. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  5936. if err != nil {
  5937. logs.Error(err)
  5938. tx.Rollback()
  5939. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5940. return
  5941. }
  5942. for _, item := range lpplandtl1List {
  5943. if item["fttype"].(int64) == 0 {
  5944. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5945. if err != nil {
  5946. logs.Error(err)
  5947. tx.Rollback()
  5948. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5949. return
  5950. }
  5951. } else {
  5952. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5953. if err != nil {
  5954. logs.Error(err)
  5955. tx.Rollback()
  5956. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5957. return
  5958. }
  5959. }
  5960. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  5961. if err != nil {
  5962. logs.Error(err)
  5963. tx.Rollback()
  5964. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5965. return
  5966. }
  5967. }
  5968. }
  5969. _, 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()
  5970. if err != nil {
  5971. logs.Error(err)
  5972. tx.Rollback()
  5973. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5974. return
  5975. }
  5976. } else {
  5977. if status == 2 {
  5978. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  5979. if err != nil {
  5980. logs.Error(err)
  5981. tx.Rollback()
  5982. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5983. return
  5984. }
  5985. for _, item := range lpplandtl1List {
  5986. if item["fttype"].(int64) == 0 {
  5987. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5988. if err != nil {
  5989. logs.Error(err)
  5990. tx.Rollback()
  5991. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5992. return
  5993. }
  5994. } else {
  5995. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  5996. if err != nil {
  5997. logs.Error(err)
  5998. tx.Rollback()
  5999. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6000. return
  6001. }
  6002. }
  6003. }
  6004. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  6005. if err != nil {
  6006. logs.Error(err)
  6007. tx.Rollback()
  6008. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6009. return
  6010. }
  6011. } else {
  6012. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  6013. if err != nil {
  6014. logs.Error(err)
  6015. tx.Rollback()
  6016. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6017. return
  6018. }
  6019. }
  6020. }
  6021. err := tx.Commit()
  6022. if err != nil {
  6023. logs.Error(err)
  6024. tx.Rollback()
  6025. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6026. return
  6027. }
  6028. appG.Response(http.StatusOK, e.SUCCESS, true)
  6029. }
  6030. func Decimal(value float64) float64 {
  6031. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  6032. return value
  6033. }
  6034. func UpdateDailyData(c *gin.Context) {
  6035. appG := app.Gin{C: c}
  6036. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6037. parammaps := gofasion.NewFasion(string(dataByte))
  6038. pid := parammaps.Get("pid").ValueDefaultStr("0")
  6039. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  6040. sort := parammaps.Get("sort").ValueDefaultStr("0")
  6041. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  6042. date := parammaps.Get("date").ValueStr()
  6043. tx := restful.Engine.NewSession()
  6044. defer tx.Close()
  6045. tx.Begin()
  6046. if location == 0 {
  6047. fid := parammaps.Get("fid").ValueStr()
  6048. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  6049. if err != nil {
  6050. logs.Error("UpdateDailyData-error-1:", err)
  6051. tx.Rollback()
  6052. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6053. return
  6054. }
  6055. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6056. if err != nil {
  6057. logs.Error("UpdateDailyData-error-1:", err)
  6058. tx.Rollback()
  6059. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6060. return
  6061. }
  6062. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  6063. if err != nil {
  6064. fmt.Println("Error:", err)
  6065. return
  6066. }
  6067. actualWeight := weight - num
  6068. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  6069. if err != nil {
  6070. logs.Error("UpdateDailyData-error-2:", err)
  6071. tx.Rollback()
  6072. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6073. return
  6074. }
  6075. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  6076. if err != nil {
  6077. logs.Error("UpdateDailyData-error-3:", err)
  6078. tx.Rollback()
  6079. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6080. return
  6081. }
  6082. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6083. if err != nil {
  6084. logs.Error("UpdateDailyData-error-4:", err)
  6085. tx.Rollback()
  6086. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6087. return
  6088. }
  6089. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6090. if err != nil {
  6091. logs.Error("UpdateDailyData-error-5:", err)
  6092. tx.Rollback()
  6093. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6094. return
  6095. }
  6096. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6097. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6098. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6099. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6100. if err != nil {
  6101. fmt.Println("Error:", err)
  6102. return
  6103. }
  6104. // actual := actualWeight / float64(len(downloadedplanList))
  6105. for _, item := range downloadedplanList {
  6106. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6107. if err != nil {
  6108. fmt.Println("Error:", err)
  6109. return
  6110. }
  6111. actual := itemLweight / lweight * actualWeight
  6112. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6113. if err != nil {
  6114. logs.Error("UpdateDailyData-error-6:", err)
  6115. tx.Rollback()
  6116. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6117. return
  6118. }
  6119. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6120. if err != nil {
  6121. logs.Error("UpdateDailyData-error-7:", err)
  6122. tx.Rollback()
  6123. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6124. return
  6125. }
  6126. _, 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()
  6127. if err != nil {
  6128. logs.Error("UpdateDailyData-error-8:", err)
  6129. tx.Rollback()
  6130. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6131. return
  6132. }
  6133. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6134. if err != nil {
  6135. logs.Error("UpdateDailyData-error-9:", err)
  6136. tx.Rollback()
  6137. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6138. return
  6139. }
  6140. }
  6141. } else {
  6142. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6143. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6144. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6145. // if err != nil {
  6146. // fmt.Println("Error:", err)
  6147. // return
  6148. // }
  6149. for _, item := range downloadedplanList {
  6150. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6151. if err != nil {
  6152. logs.Error("UpdateDailyData-error-6:", err)
  6153. tx.Rollback()
  6154. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6155. return
  6156. }
  6157. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6158. item["lweight"], actualWeight, item["id"]).Execute()
  6159. if err != nil {
  6160. logs.Error("UpdateDailyData-error-7:", err)
  6161. tx.Rollback()
  6162. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6163. return
  6164. }
  6165. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6166. where pid = ?`, item["id"]).Execute()
  6167. if err != nil {
  6168. logs.Error("UpdateDailyData-error-8:", err)
  6169. tx.Rollback()
  6170. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6171. return
  6172. }
  6173. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6174. if err != nil {
  6175. logs.Error("UpdateDailyData-error-9:", err)
  6176. tx.Rollback()
  6177. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6178. return
  6179. }
  6180. }
  6181. }
  6182. } else {
  6183. fbarid := parammaps.Get("fbarid").ValueStr()
  6184. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  6185. if err != nil {
  6186. logs.Error("UpdateDailyData-error-10:", err)
  6187. tx.Rollback()
  6188. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6189. return
  6190. }
  6191. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6192. if err != nil {
  6193. logs.Error("UpdateDailyData-error-1:", err)
  6194. tx.Rollback()
  6195. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6196. return
  6197. }
  6198. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  6199. if err != nil {
  6200. fmt.Println("Error:", err)
  6201. return
  6202. }
  6203. actualWeight := weight - num
  6204. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  6205. if err != nil {
  6206. logs.Error("UpdateDailyData-error-11:", err)
  6207. tx.Rollback()
  6208. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6209. return
  6210. }
  6211. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  6212. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6213. if err != nil {
  6214. logs.Error("UpdateDailyData-error-12:", err)
  6215. tx.Rollback()
  6216. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6217. return
  6218. }
  6219. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6220. where pid = ? `, pid).Execute()
  6221. if err != nil {
  6222. logs.Error("UpdateDailyData-error-13:", err)
  6223. tx.Rollback()
  6224. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6225. return
  6226. }
  6227. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6228. if err != nil {
  6229. logs.Error("UpdateDailyData-error-14:", err)
  6230. tx.Rollback()
  6231. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6232. return
  6233. }
  6234. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6235. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6236. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6237. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6238. if err != nil {
  6239. fmt.Println("Error:", err)
  6240. return
  6241. }
  6242. for _, item := range downloadedplanList {
  6243. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6244. if err != nil {
  6245. fmt.Println("Error:", err)
  6246. return
  6247. }
  6248. actual := itemLweight / lweight * actualWeight
  6249. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6250. if err != nil {
  6251. logs.Error("UpdateDailyData-error-6:", err)
  6252. tx.Rollback()
  6253. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6254. return
  6255. }
  6256. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6257. if err != nil {
  6258. logs.Error("UpdateDailyData-error-7:", err)
  6259. tx.Rollback()
  6260. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6261. return
  6262. }
  6263. _, 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()
  6264. if err != nil {
  6265. logs.Error("UpdateDailyData-error-8:", err)
  6266. tx.Rollback()
  6267. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6268. return
  6269. }
  6270. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6271. if err != nil {
  6272. logs.Error("UpdateDailyData-error-9:", err)
  6273. tx.Rollback()
  6274. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6275. return
  6276. }
  6277. }
  6278. } else {
  6279. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6280. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6281. for _, item := range downloadedplanList {
  6282. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6283. // if err != nil {
  6284. // fmt.Println("Error:", err)
  6285. // return
  6286. // }
  6287. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6288. if err != nil {
  6289. logs.Error("UpdateDailyData-error-6:", err)
  6290. tx.Rollback()
  6291. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6292. return
  6293. }
  6294. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6295. item["lweight"], actualWeight, item["id"]).Execute()
  6296. if err != nil {
  6297. logs.Error("UpdateDailyData-error-7:", err)
  6298. tx.Rollback()
  6299. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6300. return
  6301. }
  6302. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6303. where pid = ?`, item["id"]).Execute()
  6304. if err != nil {
  6305. logs.Error("UpdateDailyData-error-8:", err)
  6306. tx.Rollback()
  6307. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6308. return
  6309. }
  6310. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6311. if err != nil {
  6312. logs.Error("UpdateDailyData-error-9:", err)
  6313. tx.Rollback()
  6314. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6315. return
  6316. }
  6317. }
  6318. }
  6319. }
  6320. err := tx.Commit()
  6321. if err != nil {
  6322. logs.Error("UpdateDailyData-error-20:", err)
  6323. tx.Rollback()
  6324. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6325. return
  6326. }
  6327. appG.Response(http.StatusOK, e.SUCCESS, true)
  6328. }
  6329. func GetFormulaStatistics(c *gin.Context) {
  6330. appG := app.Gin{C: c}
  6331. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6332. parammaps := gofasion.NewFasion(string(dataByte))
  6333. startTime := parammaps.Get("startTime").ValueStr()
  6334. endTime := parammaps.Get("endTime").ValueStr()
  6335. pastureId := parammaps.Get("pastureId").ValueStr()
  6336. tx := restful.Engine.NewSession()
  6337. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  6338. if err != nil {
  6339. logs.Error("GetFormulaStatistics-error-1:", err)
  6340. tx.Rollback()
  6341. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6342. return
  6343. }
  6344. var feedtemplet, dateList []string
  6345. for _, f := range feedtempletList {
  6346. feedtemplet = append(feedtemplet, f["tname"].(string))
  6347. }
  6348. layout := "2006-01-02"
  6349. // s := "2023-05-01"
  6350. // e := "2023-05-23"
  6351. start, err := time.Parse(layout, startTime)
  6352. if err != nil {
  6353. fmt.Println(err)
  6354. return
  6355. }
  6356. end, err := time.Parse(layout, endTime)
  6357. if err != nil {
  6358. fmt.Println(err)
  6359. return
  6360. }
  6361. end = end.AddDate(0, 0, 1)
  6362. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  6363. dateList = append(dateList, d.Format("2006-01-02"))
  6364. }
  6365. downloadedplanList, err := tx.SQL(`select count(1) total,ft.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  6366. join feedtemplet ft on ft.id = d.tempid where d.mydate between ? and ? and d.lpplantype in(0,1) and d.iscompleted = 1 and d.pastureId= ?
  6367. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  6368. if err != nil {
  6369. logs.Error("GetFormulaStatistics-error-2:", err)
  6370. tx.Rollback()
  6371. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6372. return
  6373. }
  6374. var data2 [][]interface{}
  6375. for _, f := range feedtemplet {
  6376. var data1 []interface{}
  6377. for _, date := range dateList {
  6378. exist := false
  6379. for _, item := range downloadedplanList {
  6380. if date == item["mydate"].(string) && f == item["tname"].(string) {
  6381. data1 = append(data1, item["total"])
  6382. exist = true
  6383. break
  6384. }
  6385. }
  6386. if !exist {
  6387. data1 = append(data1, 0)
  6388. }
  6389. }
  6390. data2 = append(data2, data1)
  6391. }
  6392. //前端让加的
  6393. feedtemplet = append(feedtemplet, "")
  6394. {
  6395. var data1 []interface{}
  6396. for _, f := range dateList {
  6397. // f = f + "\n"
  6398. fmt.Println(f)
  6399. data1 = append(data1, 0)
  6400. }
  6401. data2 = append(data2, data1)
  6402. }
  6403. resp := make(map[string]interface{}, 0)
  6404. resp["xdata"] = dateList
  6405. resp["data1"] = feedtemplet
  6406. resp["data2"] = data2
  6407. appG.Response(http.StatusOK, e.SUCCESS, resp)
  6408. }