db.go 214 KB

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