ops.go 261 KB

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