ops.go 298 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878
  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/gm"
  20. "tmr-watch/http/handle/restful"
  21. "tmr-watch/module"
  22. "tmr-watch/pkg/app"
  23. "tmr-watch/pkg/e"
  24. "tmr-watch/pkg/logging"
  25. "github.com/360EntSecGroup-Skylar/excelize"
  26. "github.com/Anderson-Lu/gofasion/gofasion"
  27. "github.com/astaxie/beego/logs"
  28. "github.com/gin-gonic/gin"
  29. "github.com/qichengzx/coordtransform"
  30. "github.com/tealeg/xlsx"
  31. "github.com/xormplus/xorm"
  32. )
  33. // @Summary 根据SQL执行得到数据集
  34. // @Tags getData
  35. // @Accept json
  36. // @Produce json
  37. // @Param sql query string true "sql"
  38. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  39. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  40. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  41. // @Router /data/getdata [POST]
  42. func GetData(c *gin.Context) {
  43. appG := app.Gin{C: c}
  44. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  45. fsion := gofasion.NewFasion(string(dataByte))
  46. sqlstr := fsion.Get("sql").ValueStr()
  47. offset := fsion.Get("offset").ValueDefaultInt(0)
  48. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  49. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  50. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  51. if err != nil {
  52. appG.Response(http.StatusOK, e.ERROR, err.Error())
  53. } else {
  54. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  55. }
  56. }
  57. func Testpartitions(c *gin.Context) {
  58. appG := app.Gin{C: c}
  59. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  60. fsion := gofasion.NewFasion(string(dataByte))
  61. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  62. user := fsion.Get("user").ValueStr() //获取新数据库用户
  63. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  64. host := fsion.Get("host").ValueStr() //获取新数据库名称
  65. port := fsion.Get("port").ValueStr() //获取新数据库名称
  66. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  67. if sqls == nil || err1 != nil {
  68. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  69. }
  70. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  71. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  72. mydb, err := sql.Open("mysql", connecting) //连接新连接
  73. if err != nil {
  74. println("err1", err.Error())
  75. }
  76. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  77. if err != nil {
  78. println("err2", err.Error())
  79. }
  80. mydb.Close()
  81. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  82. mydb, err = sql.Open("mysql", connecting)
  83. if err != nil {
  84. println("err3", err.Error())
  85. }
  86. defer mydb.Close()
  87. if err == nil {
  88. mydb.SetMaxOpenConns(10)
  89. mydb.SetMaxIdleConns(10)
  90. }
  91. errmsg := ""
  92. if err == nil {
  93. //tx ,_ :=mydb.Begin()
  94. for _, sqlstr := range sqlstrs {
  95. //println("sqlstr---",sqlstr)
  96. if sqlstr == "" {
  97. continue
  98. }
  99. _, err = mydb.Exec(sqlstr)
  100. if err != nil {
  101. println("err4", err.Error())
  102. errmsg = err.Error()
  103. //err1 :=tx.Rollback()
  104. }
  105. }
  106. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  107. //err =tx.Commit()
  108. }
  109. if errmsg == "" {
  110. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  111. } else {
  112. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  113. }
  114. }
  115. func TestData(c *gin.Context) {
  116. appG := app.Gin{C: c}
  117. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  118. fsion := gofasion.NewFasion(string(dataByte))
  119. sqlstr := fsion.Get("sql").ValueStr()
  120. token := ""
  121. if tempv, exists := c.Get("jwt_username"); exists {
  122. token = tempv.(string)
  123. }
  124. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  125. }
  126. // @Summary 根据APISQL表中SQL执行得到数据集
  127. // @Tags GetDataByName
  128. // @Accept json
  129. // @Produce json
  130. // @Param sqlname body string true "sqlname"
  131. // @Param offset body int true "offset"
  132. // @Param pagecount body int true "pagecount"
  133. // @Param returntype body string true "returntype"
  134. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  135. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  136. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  137. // @Router /data/GetDataByName [POST]
  138. func GetDataByName(c *gin.Context) {
  139. appG := app.Gin{C: c}
  140. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  141. fsion := gofasion.NewFasion(string(dataByte))
  142. sqlnamestr := fsion.Get("name").ValueStr()
  143. offset := fsion.Get("offset").ValueDefaultInt(0)
  144. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  145. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  146. tx := restful.Engine.NewSession()
  147. err := tx.Begin()
  148. defer func() {
  149. switch {
  150. case err != nil:
  151. logging.Error("tx.Begin 事务启动失败__error:", err)
  152. if tx != nil {
  153. tx.Rollback()
  154. }
  155. default:
  156. if tx != nil {
  157. err = tx.Commit()
  158. }
  159. }
  160. if tx != nil {
  161. tx.Close()
  162. }
  163. }()
  164. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  165. if sql != "" {
  166. s_params := make([]interface{}, 0)
  167. if fsion.HasKey("parammaps") {
  168. parammaps := fsion.Get("parammaps")
  169. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  170. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  171. }
  172. paramslist := strings.Split(p, ",")
  173. if len(paramslist) > 0 && p != "" {
  174. for _, value := range paramslist {
  175. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  176. if tempv, exists := c.Get("jwt_username"); exists {
  177. s_params = append(s_params, tempv.(string))
  178. } else {
  179. s_params = append(s_params, "")
  180. }
  181. } else {
  182. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  183. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  184. // tmrNameList := []string{}
  185. // for _, tmr := range tmrArray {
  186. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  187. // }
  188. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  189. // } else {
  190. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  191. // }
  192. }
  193. }
  194. }
  195. } else if fsion.HasKey("params") {
  196. params := fsion.Get("params").Array()
  197. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  198. for _, v_params := range params {
  199. s_params = append(s_params, v_params.ValueStr())
  200. }
  201. }
  202. if returntype == "xlsx" {
  203. var xlsxfile *xlsx.File
  204. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  205. //c.File("c:/dd.xlsx")
  206. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  207. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  208. c.Header("Content-Transfer-Encoding", "binary")
  209. _ = xlsxfile.Write(c.Writer)
  210. } else {
  211. if sqlnamestr == "getHomepageStr" {
  212. parammaps := fsion.Get("parammaps")
  213. pastureid := parammaps.Get("pastureid").ValueStr()
  214. var montimeList []float64
  215. var montime float64
  216. var wg sync.WaitGroup
  217. now := time.Now()
  218. for i := 0; i < 30; i++ {
  219. wg.Add(1)
  220. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  221. go func(nowstr string) {
  222. defer wg.Done()
  223. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  224. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  225. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  226. montimeList = append(montimeList, m)
  227. }(nowstr)
  228. }
  229. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  230. if err != nil {
  231. logging.Error("GetDataByName err: ", err)
  232. msg := geterrmsg(err.Error())
  233. appG.Response(http.StatusOK, e.ERROR, msg)
  234. }
  235. wg.Wait()
  236. for _, m := range montimeList {
  237. montime += m
  238. }
  239. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  240. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  241. return
  242. }
  243. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  244. if err != nil {
  245. logging.Error("GetDataByName err: ", err)
  246. msg := geterrmsg(err.Error())
  247. appG.Response(http.StatusOK, e.ERROR, msg)
  248. } else {
  249. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  250. }
  251. }
  252. } else {
  253. appG.Response(http.StatusOK, e.SUCCESS, nil)
  254. }
  255. }
  256. // @Summary 根据APISQL表中SQL执行得到数据集
  257. // @Tags GetDataByName
  258. // @Accept json
  259. // @Produce json
  260. // @Param sqlname body string true "sqlname"
  261. // @Param offset body int true "offset"
  262. // @Param pagecount body int true "pagecount"
  263. // @Param returntype body string true "returntype"
  264. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  265. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  266. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  267. // @Router /data/GetDataByName [POST]
  268. func GetDataBySqlIN(c *gin.Context) {
  269. appG := app.Gin{C: c}
  270. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  271. fsion := gofasion.NewFasion(string(dataByte))
  272. sqlnamestr := fsion.Get("name").ValueStr()
  273. offset := fsion.Get("offset").ValueDefaultInt(0)
  274. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  275. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  276. tx := restful.Engine.NewSession()
  277. err := tx.Begin()
  278. defer func() {
  279. switch {
  280. case err != nil:
  281. logging.Error("tx.Begin 事务启动失败__error:", err)
  282. if tx != nil {
  283. tx.Rollback()
  284. }
  285. default:
  286. if tx != nil {
  287. err = tx.Commit()
  288. }
  289. }
  290. if tx != nil {
  291. tx.Close()
  292. }
  293. }()
  294. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  295. if sql != "" {
  296. s_params := make([]interface{}, 0)
  297. if fsion.HasKey("parammaps") {
  298. parammaps := fsion.Get("parammaps")
  299. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  300. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  301. }
  302. paramslist := strings.Split(p, ",")
  303. if len(paramslist) > 0 && p != "" {
  304. for _, value := range paramslist {
  305. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  306. if tempv, exists := c.Get("jwt_username"); exists {
  307. s_params = append(s_params, tempv.(string))
  308. } else {
  309. s_params = append(s_params, "")
  310. }
  311. } else {
  312. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  313. }
  314. }
  315. }
  316. } else if fsion.HasKey("params") {
  317. params := fsion.Get("params").Array()
  318. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  319. for _, v_params := range params {
  320. s_params = append(s_params, v_params.ValueStr())
  321. }
  322. }
  323. if returntype == "xlsx" {
  324. var xlsxfile *xlsx.File
  325. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  326. //c.File("c:/dd.xlsx")
  327. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  328. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  329. c.Header("Content-Transfer-Encoding", "binary")
  330. _ = xlsxfile.Write(c.Writer)
  331. } else {
  332. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  333. if err != nil {
  334. logging.Error("GetDataByName err: ", err)
  335. msg := geterrmsg(err.Error())
  336. appG.Response(http.StatusOK, e.ERROR, msg)
  337. } else {
  338. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  339. }
  340. }
  341. } else {
  342. appG.Response(http.StatusOK, e.SUCCESS, nil)
  343. }
  344. }
  345. // 错误处理
  346. // 将报错信息处理成汉字
  347. func geterrmsg(errstr string) (msgstr string) {
  348. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  349. rs := []rune(errstr)
  350. if hzRegexp.MatchString(string(rs[0])) {
  351. msgstr = errstr
  352. return
  353. }
  354. if strings.Contains(errstr, "Duplicate entry") {
  355. strs := strings.Split(errstr, ` key '`)
  356. if len(strs) > 1 {
  357. if len(strs[len(strs)-1]) > 1 {
  358. errstr = "Duplicate entry :" + strs[len(strs)-1]
  359. }
  360. }
  361. }
  362. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  363. if err != nil {
  364. msgstr = errstr
  365. return
  366. }
  367. if msg == nil || len(msg) == 0 {
  368. var param []interface{}
  369. param = append(param, errstr, errstr)
  370. go func() {
  371. tx := restful.Engine.NewSession()
  372. err := tx.Begin()
  373. defer func() {
  374. switch {
  375. case err != nil:
  376. logging.Error("tx.Begin 事务启动失败__error:", err)
  377. if tx != nil {
  378. tx.Rollback()
  379. }
  380. default:
  381. if tx != nil {
  382. err = tx.Commit()
  383. }
  384. }
  385. if tx != nil {
  386. tx.Close()
  387. }
  388. }()
  389. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  390. if err != nil {
  391. logging.Error("insert into err_msg(err,msg) err", err)
  392. }
  393. }()
  394. msgstr = errstr
  395. } else {
  396. msgstr = msg[0]["msg"]
  397. }
  398. return
  399. }
  400. // @Summary 根据APISQL表中SQL执行得到数据集
  401. // @Tags GetDataByNameForm
  402. // @Accept json
  403. // @Produce json
  404. // @Param sqlname body json true "sqlname"
  405. // @Param offset query int true "offset"
  406. // @Param pagecount query int true "pagecount"
  407. // @Param returntype query string true "returntype"
  408. // @Param s formData json true "ss"
  409. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  410. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  411. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  412. // @Router /data/GetDataByNameForm [POST]
  413. func GetDataByNameForm(c *gin.Context) {
  414. appG := app.Gin{C: c}
  415. //sqlnamestr := c.PostForm("measureNumber")
  416. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  417. //fsion := gofasion.NewFasion(string(dataByte))
  418. //sqlnamestr := fsion.Get("name").ValueStr()
  419. //offset := fsion.Get("offset").ValueInt()
  420. //pagecount := fsion.Get("pagecount").ValueInt()
  421. //returntype := fsion.Get("returntype").ValueStr()
  422. //params := fsion.Get("params").Array()
  423. c.Request.ParseForm()
  424. params := c.Request.Form
  425. offset := 0
  426. pageSize_ := 0
  427. returntype := params.Get("page")
  428. if returntype == "" {
  429. returntype = "0"
  430. }
  431. if tempv, exists := c.Get("jwt_username"); exists {
  432. params.Set("JwtUserName", tempv.(string))
  433. } else {
  434. params.Set("JwtUserName", "")
  435. }
  436. sqlnamestr := params.Get("name")
  437. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  438. s_params := make([]interface{}, 0)
  439. if returntype == "1" {
  440. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  441. if error != nil {
  442. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  443. }
  444. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  445. if error != nil {
  446. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  447. }
  448. pageSize_ = pageSize
  449. offset = pageNum
  450. }
  451. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  452. paramslist := strings.Split(p, ",")
  453. if len(paramslist) > 0 && p != "" {
  454. for _, value := range paramslist {
  455. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  456. }
  457. }
  458. if sql != "" {
  459. if returntype == "xlsx" {
  460. var xlsxfile *xlsx.File
  461. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  462. c.Header("Content-Type", "application/octet-stream")
  463. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  464. c.Header("Content-Transfer-Encoding", "binary")
  465. _ = xlsxfile.Write(c.Writer)
  466. } else {
  467. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  468. if err != nil {
  469. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  470. } else {
  471. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  472. }
  473. }
  474. } else {
  475. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  476. }
  477. }
  478. // @Summary 递归获取所有
  479. // @Tags menu
  480. // @Accept json
  481. // @Produce json
  482. // @Param Ton query string true "Ton"
  483. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  484. // @Router /authdata/GetRoleMenus [GET]
  485. func GetRecuDataByName(c *gin.Context) {
  486. appG := app.Gin{C: c}
  487. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  488. fsion := gofasion.NewFasion(string(dataByte))
  489. sqlnamestr := fsion.Get("name").ValueStr()
  490. parentidname := fsion.Get("idname").ValueStr()
  491. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  492. params := make(map[string]interface{})
  493. s_params := make([]interface{}, 0)
  494. if fsion.HasKey("params") {
  495. for _, v_params := range fsion.Get("params").Array() {
  496. s_params = append(s_params, v_params.ValueStr())
  497. }
  498. params["params"] = s_params
  499. } else {
  500. jparams := fsion.Get("parammaps")
  501. paramslist := strings.Split(p, ",")
  502. if len(paramslist) > 0 && p != "" {
  503. for _, value := range paramslist {
  504. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  505. if tempv, exists := c.Get("jwt_username"); exists {
  506. params[value] = tempv.(string)
  507. } else {
  508. params[value] = ""
  509. }
  510. } else {
  511. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  512. }
  513. }
  514. }
  515. }
  516. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  517. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  518. if err != nil {
  519. appG.Response(http.StatusOK, e.ERROR, err.Error())
  520. }
  521. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  522. }
  523. // @Summary 根据APISQL表中SQL执行得到数据集
  524. // @Tags GetDataByNames
  525. // @Accept json
  526. // @Produce json
  527. // @RequestBody sqlname query string true "sqlname"
  528. // @Param offset query int true "offset"
  529. // @Param pagecount query int true "pagecount"
  530. // @Param returntype query string true "returntype"
  531. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  532. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  533. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  534. // @Router /data/GetDataByNames [POST]
  535. func GetDataByNames(c *gin.Context) {
  536. appG := app.Gin{C: c}
  537. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  538. fsion := gofasion.NewFasion(string(dataByte))
  539. sqlParams := fsion.Array()
  540. queryData := make(map[string]interface{})
  541. for _, v := range sqlParams {
  542. fsion2 := gofasion.NewFasion(v.Json())
  543. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  544. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  545. if sql == "" {
  546. errorm := make(map[string]interface{})
  547. errorm["code"] = e.ERROR
  548. errorm["message"] = "sql没找到"
  549. queryData[fsion2.Get("name").ValueStr()] = errorm
  550. continue
  551. } else if sql != "" {
  552. offset := fsion2.Get("offset").ValueInt()
  553. pagecount := fsion2.Get("pagecount").ValueInt()
  554. returntype := fsion2.Get("returntype").ValueStr()
  555. s_params := make([]interface{}, 0)
  556. if fsion2.HasKey("parammaps") {
  557. parammaps := fsion2.Get("parammaps")
  558. paramslist := strings.Split(p, ",")
  559. if len(paramslist) > 0 && p != "" {
  560. for _, value := range paramslist {
  561. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  562. if tempv, exists := c.Get("jwt_username"); exists {
  563. s_params = append(s_params, tempv.(string))
  564. } else {
  565. s_params = append(s_params, "")
  566. }
  567. } else {
  568. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  569. }
  570. }
  571. }
  572. } else if fsion2.HasKey("params") {
  573. params := fsion2.Get("params").Array()
  574. for _, v_params := range params {
  575. s_params = append(s_params, v_params.ValueStr())
  576. }
  577. }
  578. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  579. if err != nil {
  580. errorm := make(map[string]interface{})
  581. errorm["code"] = e.ERROR
  582. errorm["message"] = err.Error()
  583. queryData[fsion2.Get("name").ValueStr()] = errorm
  584. logging.Error("GetDataByNames err: ", err)
  585. continue
  586. } else {
  587. queryData[fsion2.Get("name").ValueStr()] = queryData1
  588. }
  589. }
  590. }
  591. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  592. }
  593. // @Summary 根据APISQL表中SQL执行得到数据集
  594. // @Tags PostDataByNameForm
  595. // @Accept json
  596. // @Produce json
  597. // @Param sqlname query string true "sqlname"
  598. // @Param offset query int true "offset"
  599. // @Param pagecount query int true "pagecount"
  600. // @Param returntype query string true "returntype"
  601. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  602. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  603. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  604. // @Router /data/PostDataByNameForm [POST]
  605. func PostDataByNameForm(c *gin.Context) {
  606. appG := app.Gin{C: c}
  607. c.Request.ParseForm()
  608. params := c.Request.Form
  609. sqlnamestr := params.Get("name")
  610. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  611. s_params := make([]interface{}, 0)
  612. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  613. paramslist := strings.Split(p, ",")
  614. if len(paramslist) > 0 {
  615. for _, value := range paramslist {
  616. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  617. }
  618. }
  619. if sql != "" {
  620. queryData, err := execDataBySql(sql, s_params)
  621. if err != nil {
  622. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  623. } else {
  624. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  625. }
  626. } else {
  627. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  628. }
  629. }
  630. // GetReportform 将数据集转换格式
  631. // @Tags PostDataByNameForm
  632. // @Accept json
  633. // @Produce json
  634. // @Param sqlname query string true "sqlname"
  635. // @Param offset query int true "offset"
  636. // @Param pagecount query int true "pagecount"
  637. // @Param returntype query string true "returntype"
  638. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  639. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  640. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  641. func GetReportform(c *gin.Context) {
  642. appG := app.Gin{C: c}
  643. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  644. fsion := gofasion.NewFasion(string(dataByte))
  645. sqlnamestr := fsion.Get("name").ValueStr()
  646. checked := fsion.Get("checked").ValueStr()
  647. offset := fsion.Get("offset").ValueDefaultInt(0)
  648. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  649. parammaps := fsion.Get("parammaps")
  650. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  651. mode := parammaps.Get("mode").ValueDefaultInt(0)
  652. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  653. tx := restful.Engine.NewSession()
  654. err := tx.Begin()
  655. defer func() {
  656. switch {
  657. case err != nil:
  658. if tx != nil {
  659. tx.Rollback()
  660. }
  661. default:
  662. if tx != nil {
  663. err = tx.Commit()
  664. }
  665. }
  666. if tx != nil {
  667. tx.Close()
  668. }
  669. }()
  670. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  671. if err != nil {
  672. appG.Response(http.StatusOK, e.ERROR, err.Error())
  673. } else {
  674. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  675. }
  676. }
  677. // GetUpkeepPlan 保养计划
  678. func GetUpkeepPlan(c *gin.Context) {
  679. appG := app.Gin{C: c}
  680. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  681. fsion := gofasion.NewFasion(string(dataByte))
  682. sqlnamestr := fsion.Get("name").ValueStr()
  683. offset := fsion.Get("offset").ValueDefaultInt(0)
  684. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  685. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  686. month := fsion.Get("month").ValueDefaultStr("map")
  687. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  688. tx := restful.Engine.NewSession()
  689. err := tx.Begin()
  690. defer func() {
  691. switch {
  692. case err != nil:
  693. if tx != nil {
  694. tx.Rollback()
  695. }
  696. default:
  697. if tx != nil {
  698. err = tx.Commit()
  699. }
  700. }
  701. if tx != nil {
  702. tx.Close()
  703. }
  704. }()
  705. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  706. if sql != "" {
  707. s_params := make([]interface{}, 0)
  708. if fsion.HasKey("parammaps") {
  709. parammaps := fsion.Get("parammaps")
  710. paramslist := strings.Split(p, ",")
  711. if len(paramslist) > 0 && p != "" {
  712. for _, value := range paramslist {
  713. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  714. if tempv, exists := c.Get("jwt_username"); exists {
  715. s_params = append(s_params, tempv.(string))
  716. } else {
  717. s_params = append(s_params, "")
  718. }
  719. } else {
  720. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  721. }
  722. }
  723. }
  724. } else if fsion.HasKey("params") {
  725. params := fsion.Get("params").Array()
  726. for _, v_params := range params {
  727. s_params = append(s_params, v_params.ValueStr())
  728. }
  729. }
  730. if returntype == "xlsx" {
  731. var xlsxfile *xlsx.File
  732. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  733. //c.File("c:/dd.xlsx")
  734. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  735. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  736. c.Header("Content-Transfer-Encoding", "binary")
  737. _ = xlsxfile.Write(c.Writer)
  738. } else {
  739. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  740. if err != nil {
  741. appG.Response(http.StatusOK, e.ERROR, err.Error())
  742. } else {
  743. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  744. if v, ok := value["id"]; ok {
  745. //month = "2020-03"
  746. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  747. if seviceplans != nil {
  748. for _, va := range seviceplans { //根据保养计划获取保养单
  749. //day,_ :=strconv.Atoi(va["day"])
  750. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  751. //buk := make(map[string]map[string]string)
  752. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  753. jstr := ""
  754. if bu["plantime"][8:9] == "0" {
  755. jstr = "m" + bu["plantime"][9:]
  756. } else {
  757. jstr = "m" + bu["plantime"][8:]
  758. }
  759. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  760. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  761. } else {
  762. if bu["flowCompeleted"] >= "2" {
  763. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  764. } else {
  765. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  766. }
  767. }
  768. }
  769. }
  770. }
  771. }
  772. }
  773. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  774. }
  775. }
  776. } else {
  777. appG.Response(http.StatusOK, e.SUCCESS, nil)
  778. }
  779. }
  780. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  781. // todo 优化性能 children统一查询
  782. // @Tags PostDataByNameForm
  783. // @Accept json
  784. // @Produce json
  785. // @Param sqlname query string true "sqlname"
  786. // @Param offset query int true "offset"
  787. // @Param pagecount query int true "pagecount"
  788. // @Param returntype query string true "returntype"
  789. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  790. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  791. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  792. func GetArrList(c *gin.Context) {
  793. appG := app.Gin{C: c}
  794. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  795. fsion := gofasion.NewFasion(string(dataByte))
  796. sqlnamestr := fsion.Get("name").ValueStr()
  797. sqlnamestr1 := fsion.Get("name1").ValueStr()
  798. offset := fsion.Get("offset").ValueDefaultInt(0)
  799. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  800. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  801. month := fsion.Get("month").ValueDefaultStr("map")
  802. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  803. tx := restful.Engine.NewSession()
  804. err := tx.Begin()
  805. defer func() {
  806. switch {
  807. case err != nil:
  808. if tx != nil {
  809. tx.Rollback()
  810. }
  811. default:
  812. if tx != nil {
  813. err = tx.Commit()
  814. }
  815. }
  816. if tx != nil {
  817. tx.Close()
  818. }
  819. }()
  820. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  821. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  822. if sql != "" {
  823. s_params := make([]interface{}, 0)
  824. if fsion.HasKey("parammaps") {
  825. parammaps := fsion.Get("parammaps")
  826. paramslist := strings.Split(p, ",")
  827. if len(paramslist) > 0 && p != "" {
  828. for _, value := range paramslist {
  829. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  830. if tempv, exists := c.Get("jwt_username"); exists {
  831. s_params = append(s_params, tempv.(string))
  832. } else {
  833. s_params = append(s_params, "")
  834. }
  835. } else {
  836. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  837. }
  838. }
  839. }
  840. }
  841. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  842. if err != nil {
  843. appG.Response(http.StatusOK, e.ERROR, err.Error())
  844. } else {
  845. paramslist1 := strings.Split(p1, ",")
  846. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  847. s_params1 := make([]interface{}, 0)
  848. if len(paramslist1) > 0 && p1 != "" {
  849. for _, v := range paramslist1 {
  850. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  851. }
  852. }
  853. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  854. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  855. }
  856. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  857. }
  858. } else {
  859. appG.Response(http.StatusOK, e.SUCCESS, nil)
  860. }
  861. }
  862. func GetAccount(c *gin.Context) {
  863. appG := app.Gin{C: c}
  864. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  865. fsion := gofasion.NewFasion(string(dataByte))
  866. sqlnamestr := fsion.Get("name").ValueStr()
  867. offset := fsion.Get("offset").ValueDefaultInt(0)
  868. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  869. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  870. tx := restful.Engine.NewSession()
  871. err := tx.Begin()
  872. defer func() {
  873. switch {
  874. case err != nil:
  875. logging.Error("tx.Begin 事务启动失败__error:", err)
  876. if tx != nil {
  877. tx.Rollback()
  878. }
  879. default:
  880. if tx != nil {
  881. err = tx.Commit()
  882. }
  883. }
  884. if tx != nil {
  885. tx.Close()
  886. }
  887. }()
  888. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  889. if sql != "" {
  890. s_params := make([]interface{}, 0)
  891. if fsion.HasKey("parammaps") {
  892. parammaps := fsion.Get("parammaps")
  893. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  894. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  895. }
  896. paramslist := strings.Split(p, ",")
  897. if len(paramslist) > 0 && p != "" {
  898. for _, value := range paramslist {
  899. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  900. if tempv, exists := c.Get("jwt_username"); exists {
  901. s_params = append(s_params, tempv.(string))
  902. } else {
  903. s_params = append(s_params, "")
  904. }
  905. } else {
  906. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  907. }
  908. }
  909. }
  910. } else if fsion.HasKey("params") {
  911. params := fsion.Get("params").Array()
  912. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  913. for _, v_params := range params {
  914. s_params = append(s_params, v_params.ValueStr())
  915. }
  916. }
  917. if returntype == "xlsx" {
  918. var xlsxfile *xlsx.File
  919. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  920. //c.File("c:/dd.xlsx")
  921. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  922. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  923. c.Header("Content-Transfer-Encoding", "binary")
  924. _ = xlsxfile.Write(c.Writer)
  925. } else {
  926. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  927. if err != nil {
  928. logging.Error("GetDataByName err: ", err)
  929. msg := geterrmsg(err.Error())
  930. appG.Response(http.StatusOK, e.ERROR, msg)
  931. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  932. } else {
  933. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  934. }
  935. }
  936. } else {
  937. appG.Response(http.StatusOK, e.SUCCESS, nil)
  938. }
  939. }
  940. // PostDataByName 根据APISQL表中SQL执行得到数据集
  941. // @Accept json
  942. // @Produce json
  943. // @Param sqlname query string true "sqlname"
  944. // @Param offset query int true "offset"
  945. // @Param pagecount query int true "pagecount"
  946. // @Param returntype query string true "returntype"
  947. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  948. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  949. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  950. // @Router /data/PostDataByName [POST]
  951. func PostDataByName(c *gin.Context) {
  952. appG := app.Gin{C: c}
  953. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  954. fsion := gofasion.NewFasion(string(dataByte))
  955. var err error
  956. queryData, err := module.PostDataByName(c, fsion)
  957. if err != nil {
  958. appG.Response(http.StatusOK, e.ERROR, err)
  959. return
  960. }
  961. var (
  962. keyWord string
  963. )
  964. switch fsion.Get("name").ValueStr() {
  965. case "insertFeedclass":
  966. keyWord = "feed"
  967. err = module.GroupCategorySync(keyWord, fsion)
  968. case "deleteFeedclass":
  969. keyWord = "feed_delete"
  970. err = module.GroupCategoryDelete(keyWord, fsion)
  971. case "insertCowclass":
  972. keyWord = "cow"
  973. err = module.GroupCategorySync(keyWord, fsion)
  974. case "deleteCowclass":
  975. keyWord = "cow_delete"
  976. err = module.GroupCategoryDelete(keyWord, fsion)
  977. default:
  978. }
  979. if err != nil {
  980. logging.Error(keyWord, err)
  981. }
  982. if queryData != nil {
  983. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  984. return
  985. }
  986. appG.Response(http.StatusOK, e.SUCCESS, nil)
  987. }
  988. //人脸识别/格润富德接口
  989. func GetRJSBData(c *gin.Context) {
  990. appG := app.Gin{C: c}
  991. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  992. fsion := gofasion.NewFasion(string(dataByte))
  993. sqlnamestr := fsion.Get("name").ValueStr()
  994. sqlnamestr1 := fsion.Get("name1").ValueStr()
  995. offset := fsion.Get("offset").ValueDefaultInt(0)
  996. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  997. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  998. month := fsion.Get("month").ValueDefaultStr("map")
  999. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1000. tx := restful.Engine.NewSession()
  1001. err := tx.Begin()
  1002. defer func() {
  1003. switch {
  1004. case err != nil:
  1005. if tx != nil {
  1006. tx.Rollback()
  1007. }
  1008. default:
  1009. if tx != nil {
  1010. err = tx.Commit()
  1011. }
  1012. }
  1013. if tx != nil {
  1014. tx.Close()
  1015. }
  1016. }()
  1017. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1018. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1019. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1020. if sql != "" {
  1021. s_params := make([]interface{}, 0)
  1022. if fsion.HasKey("parammaps") {
  1023. parammaps := fsion.Get("parammaps")
  1024. paramslist := strings.Split(p, ",")
  1025. if len(paramslist) > 0 && p != "" {
  1026. for _, value := range paramslist {
  1027. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1028. if tempv, exists := c.Get("jwt_username"); exists {
  1029. s_params = append(s_params, tempv.(string))
  1030. } else {
  1031. s_params = append(s_params, "")
  1032. }
  1033. } else {
  1034. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1035. }
  1036. }
  1037. }
  1038. }
  1039. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1040. if err != nil {
  1041. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1042. } else {
  1043. paramslist1 := strings.Split(p1, ",")
  1044. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1045. s_params1 := make([]interface{}, 0)
  1046. if len(paramslist1) > 0 && p1 != "" {
  1047. for _, v := range paramslist1 {
  1048. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1049. }
  1050. }
  1051. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1052. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1053. }
  1054. var wg sync.WaitGroup
  1055. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1056. wg.Add(1)
  1057. go func(value map[string]interface{}) {
  1058. defer wg.Done()
  1059. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1060. }(value)
  1061. }
  1062. wg.Wait()
  1063. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1064. }
  1065. } else {
  1066. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1067. }
  1068. }
  1069. func PostRJSBData(c *gin.Context) {
  1070. appG := app.Gin{C: c}
  1071. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1072. fsion := gofasion.NewFasion(string(dataByte))
  1073. logging.Info("PostRJSBData err: ", string(dataByte))
  1074. s_params := make([]interface{}, 0)
  1075. tx := restful.Engine.NewSession()
  1076. err := tx.Begin()
  1077. defer func() {
  1078. switch {
  1079. case err != nil:
  1080. if tx != nil {
  1081. tx.Rollback()
  1082. }
  1083. default:
  1084. if tx != nil {
  1085. err = tx.Commit()
  1086. }
  1087. }
  1088. if tx != nil {
  1089. tx.Close()
  1090. }
  1091. }()
  1092. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1093. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1094. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1095. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1096. if !fsion.HasKey("parammaps") {
  1097. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1098. return
  1099. }
  1100. parammaps := fsion.Get("parammaps")
  1101. paramslist := strings.Split(p, ",")
  1102. if len(paramslist) > 0 && p != "" {
  1103. for _, value := range paramslist {
  1104. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1105. }
  1106. }
  1107. _, err = tx.SQL(sql, s_params...).Execute()
  1108. if err != nil {
  1109. logging.Error("PostRJSBData err: ", err)
  1110. msg := geterrmsg(err.Error())
  1111. // appG.Response(http.StatusOK, e.ERROR, msg)
  1112. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1113. return
  1114. }
  1115. s_params = make([]interface{}, 0)
  1116. paramslist = strings.Split(p1, ",")
  1117. if len(paramslist) > 0 && p1 != "" {
  1118. for _, value := range paramslist {
  1119. // if value == "ID" {
  1120. // id := parammaps.Get("ID").ValueStr()
  1121. // pastureid := parammaps.Get("pastureid").ValueStr()
  1122. // 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
  1123. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1124. // if err != nil {
  1125. // logging.Error("PostRJSBData err: ", err)
  1126. // msg := geterrmsg(err.Error())
  1127. // appG.Response(http.StatusOK, e.ERROR, msg)
  1128. // return
  1129. // }
  1130. // for _, item := range datalist {
  1131. // id = item["id"]
  1132. // }
  1133. // s_params = append(s_params, id)
  1134. // } else {
  1135. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1136. // }
  1137. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1138. }
  1139. }
  1140. _, err = tx.SQL(sql1, s_params...).Execute()
  1141. if err != nil {
  1142. logging.Error("PostRJSBData1 err: ", err)
  1143. msg := geterrmsg(err.Error())
  1144. appG.Response(http.StatusOK, e.ERROR, msg)
  1145. return
  1146. }
  1147. s_params = make([]interface{}, 0)
  1148. paramslist = strings.Split(p2, ",")
  1149. if len(paramslist) > 0 && p2 != "" {
  1150. for _, value := range paramslist {
  1151. if value == "ID" {
  1152. id := parammaps.Get("ID").ValueStr()
  1153. pastureid := parammaps.Get("pastureid").ValueStr()
  1154. 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
  1155. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1156. if err != nil {
  1157. logging.Error("PostRJSBData err: ", err)
  1158. msg := geterrmsg(err.Error())
  1159. appG.Response(http.StatusOK, e.ERROR, msg)
  1160. return
  1161. }
  1162. for _, item := range datalist {
  1163. id = item["id"]
  1164. }
  1165. s_params = append(s_params, id)
  1166. } else {
  1167. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1168. }
  1169. }
  1170. }
  1171. _, err = tx.SQL(sql2, s_params...).Execute()
  1172. if err != nil {
  1173. logging.Error("PostRJSBData2 err: ", err)
  1174. msg := geterrmsg(err.Error())
  1175. appG.Response(http.StatusOK, e.ERROR, msg)
  1176. return
  1177. }
  1178. s_params = make([]interface{}, 0)
  1179. paramslist = strings.Split(p3, ",")
  1180. if len(paramslist) > 0 && p3 != "" {
  1181. for _, value := range paramslist {
  1182. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1183. }
  1184. }
  1185. _, err = tx.SQL(sql3, s_params...).Execute()
  1186. if err != nil {
  1187. logging.Error("PostRJSBData3 err: ", err)
  1188. msg := geterrmsg(err.Error())
  1189. appG.Response(http.StatusOK, e.ERROR, msg)
  1190. return
  1191. }
  1192. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1193. }
  1194. func PostRJSBDatas(c *gin.Context) {
  1195. appG := app.Gin{C: c}
  1196. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1197. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1198. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1199. tx := restful.Engine.NewSession()
  1200. err := tx.Begin()
  1201. defer func() {
  1202. switch {
  1203. case err != nil:
  1204. if tx != nil {
  1205. tx.Rollback()
  1206. }
  1207. default:
  1208. if tx != nil {
  1209. err = tx.Commit()
  1210. }
  1211. }
  1212. if tx != nil {
  1213. tx.Close()
  1214. }
  1215. }()
  1216. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1217. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1218. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1219. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1220. for _, fsion := range fsions {
  1221. if !fsion.HasKey("parammaps") {
  1222. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1223. return
  1224. }
  1225. parammaps := fsion.Get("parammaps")
  1226. ID := parammaps.Get("ID").ValueStr()
  1227. if ID == "" {
  1228. continue
  1229. }
  1230. s_params := make([]interface{}, 0)
  1231. paramslist := strings.Split(p, ",")
  1232. if len(paramslist) > 0 && p != "" {
  1233. for _, value := range paramslist {
  1234. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1235. }
  1236. }
  1237. _, err = tx.SQL(sql, s_params...).Execute()
  1238. if err != nil {
  1239. logging.Error("PostRJSBData err: ", err)
  1240. msg := geterrmsg(err.Error())
  1241. // appG.Response(http.StatusOK, e.ERROR, msg)
  1242. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1243. return
  1244. }
  1245. s_params = make([]interface{}, 0)
  1246. paramslist = strings.Split(p1, ",")
  1247. if len(paramslist) > 0 && p1 != "" {
  1248. for _, value := range paramslist {
  1249. // if value == "ID" {
  1250. // id := parammaps.Get("ID").ValueStr()
  1251. // pastureid := parammaps.Get("pastureid").ValueStr()
  1252. // 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
  1253. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1254. // if err != nil {
  1255. // logging.Error("PostRJSBData err: ", err)
  1256. // msg := geterrmsg(err.Error())
  1257. // appG.Response(http.StatusOK, e.ERROR, msg)
  1258. // return
  1259. // }
  1260. // for _, item := range datalist {
  1261. // id = item["id"]
  1262. // }
  1263. // s_params = append(s_params, id)
  1264. // } else {
  1265. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1266. // }
  1267. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1268. }
  1269. }
  1270. _, err = tx.SQL(sql1, s_params...).Execute()
  1271. if err != nil {
  1272. logging.Error("PostRJSBData1 err: ", err)
  1273. msg := geterrmsg(err.Error())
  1274. appG.Response(http.StatusOK, e.ERROR, msg)
  1275. return
  1276. }
  1277. s_params = make([]interface{}, 0)
  1278. paramslist = strings.Split(p2, ",")
  1279. if len(paramslist) > 0 && p2 != "" {
  1280. for _, value := range paramslist {
  1281. if value == "ID" {
  1282. id := parammaps.Get("ID").ValueStr()
  1283. pastureid := parammaps.Get("pastureid").ValueStr()
  1284. 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
  1285. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1286. if err != nil {
  1287. logging.Error("PostRJSBData err: ", err)
  1288. msg := geterrmsg(err.Error())
  1289. appG.Response(http.StatusOK, e.ERROR, msg)
  1290. return
  1291. }
  1292. for _, item := range datalist {
  1293. id = item["id"]
  1294. }
  1295. s_params = append(s_params, id)
  1296. } else {
  1297. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1298. }
  1299. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1300. }
  1301. }
  1302. _, err = tx.SQL(sql2, s_params...).Execute()
  1303. if err != nil {
  1304. logging.Error("PostRJSBData2 err: ", err)
  1305. msg := geterrmsg(err.Error())
  1306. appG.Response(http.StatusOK, e.ERROR, msg)
  1307. return
  1308. }
  1309. s_params = make([]interface{}, 0)
  1310. paramslist = strings.Split(p3, ",")
  1311. if len(paramslist) > 0 && p3 != "" {
  1312. for _, value := range paramslist {
  1313. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1314. }
  1315. }
  1316. _, err = tx.SQL(sql3, s_params...).Execute()
  1317. if err != nil {
  1318. logging.Error("PostRJSBData3 err: ", err)
  1319. msg := geterrmsg(err.Error())
  1320. appG.Response(http.StatusOK, e.ERROR, msg)
  1321. return
  1322. }
  1323. }
  1324. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1325. }
  1326. // @Summary 根据APISQL表中SQL执行得到数据集
  1327. // @Tags ExecDataByConfig
  1328. // @Accept json
  1329. // @Produce json
  1330. // @Param sqlname query string true "sqlname"
  1331. // @Param offset query int true "offset"
  1332. // @Param pagecount query int true "pagecount"
  1333. // @Param returntype query string true "returntype"
  1334. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1335. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1336. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1337. // @Router /data/PostDataByName [POST]
  1338. func ExecDataByConfig(c *gin.Context) {
  1339. appG := app.Gin{C: c}
  1340. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1341. tempval_ := make(map[string]interface{})
  1342. tempCommon := make(map[string]interface{})
  1343. tempval := make([]map[string]interface{}, 0)
  1344. err := json.Unmarshal(dataByte, &tempval_)
  1345. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1346. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1347. if err != nil {
  1348. } else {
  1349. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1350. tempCommon = v
  1351. }
  1352. if v, ok := tempval_["data"].([]interface{}); ok {
  1353. for _, Tvalue := range v {
  1354. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1355. tempval = append(tempval, v1)
  1356. }
  1357. }
  1358. }
  1359. tx := restful.Engine.NewSession()
  1360. err := tx.Begin()
  1361. if err != nil {
  1362. logging.Error("tx.Begin 事务启动失败__error:", err)
  1363. }
  1364. defer func() {
  1365. switch {
  1366. case err != nil:
  1367. if tx != nil {
  1368. tx.Rollback()
  1369. }
  1370. default:
  1371. if tx != nil {
  1372. err = tx.Commit()
  1373. }
  1374. }
  1375. if tx != nil {
  1376. tx.Close()
  1377. }
  1378. }()
  1379. if err == nil {
  1380. if tempv, exists := c.Get("jwt_username"); exists {
  1381. tempCommon["jwt_username"] = tempv.(string)
  1382. }
  1383. for _, paramvalue := range tempval {
  1384. fmt.Println(paramvalue["name"])
  1385. if paramvalue["name"].(string) == "updateBigFP" {
  1386. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1387. if err != nil {
  1388. msg := geterrmsg(err.Error())
  1389. appG.Response(http.StatusOK, e.ERROR, msg)
  1390. return
  1391. }
  1392. }
  1393. }
  1394. for _, paramvalue := range tempval {
  1395. if _, ok := paramvalue["resultname"]; !ok {
  1396. paramvalue["resultname"] = paramvalue["name"]
  1397. }
  1398. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1399. if err != nil {
  1400. logging.Error("ExecDataParam error:", err)
  1401. break
  1402. }
  1403. if paramvalue["name"].(string) == "createdownloadedplan" {
  1404. checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1405. }
  1406. }
  1407. if err == nil {
  1408. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1409. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1410. } else {
  1411. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1412. }
  1413. } else {
  1414. msg := geterrmsg(err.Error())
  1415. appG.Response(http.StatusOK, e.ERROR, msg)
  1416. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1417. }
  1418. }
  1419. }
  1420. if err != nil {
  1421. msg := geterrmsg(err.Error())
  1422. appG.Response(http.StatusOK, e.ERROR, msg)
  1423. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1424. }
  1425. }
  1426. func interfacetostring(val interface{}) string {
  1427. switch val.(type) {
  1428. case string:
  1429. ss := val.(string)
  1430. return ss
  1431. break
  1432. case int:
  1433. ss := val.(int)
  1434. return strconv.Itoa(ss)
  1435. break
  1436. case int64:
  1437. ss := val.(int64)
  1438. return strconv.FormatInt(ss, 10)
  1439. break
  1440. case float64:
  1441. ss := val.(float64)
  1442. return strconv.FormatFloat(ss, 'E', -1, 32)
  1443. break
  1444. }
  1445. return ""
  1446. }
  1447. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1448. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1449. tempstrb := strings.IndexAny(valuestring, "@")
  1450. tempstre := strings.IndexAny(valuestring, ".")
  1451. if tempstrb > -1 && tempstre > -1 {
  1452. for _, ParamMapList := range ParamMap {
  1453. if v, ok := ParamMapList["resultname"]; ok {
  1454. if v == valuestring[tempstrb+1:tempstre] {
  1455. if v1, ok := ParamMapList["resultmaps"]; ok {
  1456. if newA, ok := v1.([]map[string]interface{}); ok {
  1457. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1458. } else if newA, ok := v1.(map[string]interface{}); ok {
  1459. return interfacetostring(newA[valuestring[tempstre+1:]])
  1460. }
  1461. }
  1462. }
  1463. }
  1464. }
  1465. } else {
  1466. return valuestring
  1467. }
  1468. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1469. return strconv.FormatInt(int64(valuestring), 10)
  1470. }
  1471. return ""
  1472. }
  1473. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1474. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1475. tempstrb := strings.IndexAny(valuestring, "@")
  1476. tempstre := strings.IndexAny(valuestring, ".")
  1477. if tempstrb > -1 && tempstre > -1 {
  1478. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1479. if s, ok := v.(string); ok {
  1480. return s
  1481. } else if s, ok := v.(float64); ok {
  1482. return strconv.FormatFloat(s, 'f', -1, 64)
  1483. // return strconv.FormatInt(int64(s), 10)
  1484. }
  1485. }
  1486. }
  1487. }
  1488. return ""
  1489. }
  1490. 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) {
  1491. sqlname := fasion["name"].(string)
  1492. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1493. if v, ok := fasion["type"]; ok {
  1494. sqltype = v.(string)
  1495. }
  1496. sql := ""
  1497. p := ""
  1498. s_params := make([]interface{}, 0)
  1499. if sqltype != "" {
  1500. sql, p = restful.GetSqlByName(sqlname, tx)
  1501. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1502. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1503. paramslist := strings.Split(p, ",")
  1504. if len(paramslist) > 0 && p != "" {
  1505. for _, value := range paramslist {
  1506. ss := ""
  1507. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1508. ids, err := setting.SnowIds.NextId()
  1509. if err != nil {
  1510. ids = time.Now().UnixNano()
  1511. logging.Info("create SnowIds err", err)
  1512. }
  1513. s_params = append(s_params, ids)
  1514. } else {
  1515. if ss == "" && CommonParamMap != nil {
  1516. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1517. ss = valuestring
  1518. tempstrb := strings.IndexAny(valuestring, "@")
  1519. tempstre := strings.IndexAny(valuestring, ".")
  1520. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1521. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1522. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1523. }
  1524. } else {
  1525. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1526. ss = ""
  1527. }
  1528. }
  1529. }
  1530. }
  1531. if ss == "" && ParentParamMap != nil {
  1532. ss = getParamValue_(v, value, ParentParamMap)
  1533. }
  1534. if ss == "" && sameParamMap != nil {
  1535. ss = getParamValue(v, value, sameParamMap)
  1536. }
  1537. if ss == "" && ParamMap != nil {
  1538. ss = getParamValue(v, value, ParamMap)
  1539. }
  1540. s_params = append(s_params, ss)
  1541. }
  1542. }
  1543. }
  1544. }
  1545. }
  1546. if sql == "" {
  1547. sqltype = ""
  1548. }
  1549. if sqltype == "s1" {
  1550. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1551. if v, ok := tempValParam.(map[string]interface{}); ok {
  1552. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  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 == "sm" {
  1563. tempValParam, err := restful.QueryByMap(sql, 0, 0, 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. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1572. if err != nil {
  1573. return nil, err
  1574. }
  1575. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1576. } else if sqltype == "v" {
  1577. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1578. if v, ok := tempValParam.(map[string]interface{}); ok {
  1579. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1580. } else {
  1581. }
  1582. if err != nil {
  1583. return nil, err
  1584. }
  1585. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1586. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1587. }
  1588. } else if sqltype == "e" {
  1589. tempVal_arrary := make([]map[string]interface{}, 0)
  1590. tempVal_map := make(map[string]interface{})
  1591. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1592. if err == nil {
  1593. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1594. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1595. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1596. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1597. return tempVal_arrary, err
  1598. }
  1599. return nil, err
  1600. } else {
  1601. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1602. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1603. if err != nil {
  1604. return nil, err
  1605. }
  1606. return nil, err
  1607. }
  1608. }
  1609. return nil, nil
  1610. }
  1611. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1612. var err error
  1613. subarray, ok := fasion["children"]
  1614. if ok {
  1615. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1616. tempVal_arrary := make([]map[string]interface{}, 0)
  1617. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1618. tempVal_ := make(map[string]interface{})
  1619. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1620. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1621. } else {
  1622. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1623. }
  1624. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1625. if err != nil {
  1626. return err
  1627. }
  1628. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1629. }
  1630. v.(map[string]interface{})["children"] = tempVal_arrary
  1631. }
  1632. }
  1633. return nil
  1634. }
  1635. // @Summary 删除图片
  1636. // @Tags RemovePicByName
  1637. // @Accept json
  1638. // @Produce json
  1639. // @Param sqlname query string true "sqlname"
  1640. // @Param offset query int true "offset"
  1641. // @Param pagecount query int true "pagecount"
  1642. // @Param returntype query string true "returntype"
  1643. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1644. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1645. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1646. // @Router /data/PostDataByName [POST]
  1647. func RemovePicByName(c *gin.Context) {
  1648. logging.Info("RemovePicByName ", c.Keys)
  1649. appG := app.Gin{C: c}
  1650. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1651. fsion := gofasion.NewFasion(string(dataByte))
  1652. sqlnamestr := fsion.Get("name").ValueStr()
  1653. picname := fsion.Get("picname").ValueStr()
  1654. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1655. params := fsion.Get("params").Array()
  1656. s_params := make([]interface{}, 0)
  1657. for _, v_params := range params {
  1658. s_params = append(s_params, v_params.ValueStr())
  1659. }
  1660. if sql != "" {
  1661. queryData, err := execDataBySql(sql, s_params)
  1662. if picname != "" {
  1663. // Destination
  1664. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1665. err := os.Remove(distPath) //删除文件test.txt
  1666. if err != nil {
  1667. //如果删除失败则输出 file remove Error!
  1668. fmt.Println("file remove Error!")
  1669. //输出错误详细信息
  1670. fmt.Printf("%s", err)
  1671. } else {
  1672. //如果删除成功则输出 file remove OK!
  1673. fmt.Print("file remove OK!")
  1674. }
  1675. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1676. err = os.Remove(distPath) //删除文件test.txt
  1677. if err != nil {
  1678. //如果删除失败则输出 file remove Error!
  1679. fmt.Println("file remove Error!")
  1680. //输出错误详细信息
  1681. fmt.Printf("%s", err)
  1682. } else {
  1683. //如果删除成功则输出 file remove OK!
  1684. fmt.Print("file remove OK!")
  1685. }
  1686. }
  1687. if err != nil {
  1688. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1689. } else {
  1690. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1691. }
  1692. } else {
  1693. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1694. }
  1695. }
  1696. // @Summary 删除文件
  1697. // @Tags RemoveFileByName
  1698. // @Accept json
  1699. // @Produce json
  1700. // @Param sqlname query string true "sqlname"
  1701. // @Param offset query int true "offset"
  1702. // @Param pagecount query int true "pagecount"
  1703. // @Param returntype query string true "returntype"
  1704. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1705. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1706. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1707. // @Router /data/PostDataByName [POST]
  1708. func RemoveFileByName(c *gin.Context) {
  1709. appG := app.Gin{C: c}
  1710. id := c.Param("id")
  1711. logging.Info("DownloadFile ", c.Keys, id)
  1712. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1713. if eqdoc == nil {
  1714. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1715. return
  1716. }
  1717. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1718. err = os.Remove(distPath) //删除文件test.txt
  1719. if err != nil {
  1720. //如果删除失败则输出 file remove Error!
  1721. fmt.Println("file remove Error!")
  1722. //输出错误详细信息
  1723. fmt.Printf("%s", err)
  1724. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1725. return
  1726. }
  1727. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1728. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1729. }
  1730. // @Summary 根据APISQL表中SQL执行得到数据集
  1731. // @Tags PostDataByName
  1732. // @Accept json
  1733. // @Produce json
  1734. // @Param sqlname query string true "sqlname"
  1735. // @Param offset query int true "offset"
  1736. // @Param pagecount query int true "pagecount"
  1737. // @Param returntype query string true "returntype"
  1738. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1739. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1740. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1741. // @Router /data/PostDataByName [POST]
  1742. func UpdateDataRelation(c *gin.Context) {
  1743. appG := app.Gin{C: c}
  1744. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1745. fsion := gofasion.NewFasion(string(dataByte))
  1746. tablename := fsion.Get("name").ValueStr()
  1747. dataname := fsion.Get("dataname").ValueStr()
  1748. datavalue := fsion.Get("datavalue").ValueStr()
  1749. valuename := fsion.Get("valuename").ValueStr()
  1750. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1751. values := fsion.Get("values").Array()
  1752. tx := restful.Engine.NewSession()
  1753. err := tx.Begin()
  1754. defer func() {
  1755. switch {
  1756. case err != nil:
  1757. if tx != nil {
  1758. tx.Rollback()
  1759. }
  1760. default:
  1761. if tx != nil {
  1762. err = tx.Commit()
  1763. }
  1764. }
  1765. if tx != nil {
  1766. tx.Close()
  1767. }
  1768. }()
  1769. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1770. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1771. d_params := make([]interface{}, 4)
  1772. d_params[0] = datavalue
  1773. s_params := ""
  1774. for _, v_values := range values {
  1775. d_params[1] = v_values.ValueStr()
  1776. if s_params == "" {
  1777. s_params = v_values.ValueStr()
  1778. } else {
  1779. s_params = s_params + "," + v_values.ValueStr()
  1780. }
  1781. d_params[2] = d_params[1]
  1782. d_params[3] = d_params[0]
  1783. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1784. if err != nil {
  1785. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1786. break
  1787. }
  1788. }
  1789. if s_params != "" {
  1790. deleteSqlstr := "delete from " + tablename + " " +
  1791. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1792. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1793. if err != nil {
  1794. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1795. } else if err == nil {
  1796. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1797. }
  1798. } else {
  1799. deleteSqlstr := "delete from " + tablename + " " +
  1800. " where " + dataname + " = " + datavalue
  1801. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1802. if err != nil {
  1803. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1804. } else if err == nil {
  1805. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1806. }
  1807. }
  1808. }
  1809. // @Summary 根据APISQL表中SQL执行得到数据集
  1810. // @Tags PostDatasByName
  1811. // @Accept json
  1812. // @Produce json
  1813. // @Param sqlname query string true "sqlname"
  1814. // @Param offset query int true "offset"
  1815. // @Param pagecount query int true "pagecount"
  1816. // @Param returntype query string true "returntype"
  1817. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1818. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1819. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1820. // @Router /data/PostDatasByName [POST]
  1821. func PostDataByNames(c *gin.Context) {
  1822. appG := app.Gin{C: c}
  1823. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1824. fsion := gofasion.NewFasion(string(dataByte))
  1825. sqlParams := fsion.Get("array").Array()
  1826. queryData := make(map[string]interface{})
  1827. for _, v := range sqlParams {
  1828. fsion2 := gofasion.NewFasion(v.Json())
  1829. ss := fsion2.Get("name")
  1830. aa := fsion2.Get("params")
  1831. fmt.Println(ss, aa)
  1832. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1833. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1834. if sql == "" {
  1835. errorm := make(map[string]interface{})
  1836. errorm["code"] = e.ERROR
  1837. errorm["message"] = "sql没有找到"
  1838. errorm["param"] = ""
  1839. queryData[fsion2.Get("name").ValueStr()] = errorm
  1840. continue
  1841. } else if sql != "" {
  1842. s_params := make([]interface{}, 0)
  1843. if fsion2.HasKey("parammaps") {
  1844. parammaps := fsion2.Get("parammaps")
  1845. paramslist := strings.Split(p, ",")
  1846. if len(paramslist) > 0 && p != "" {
  1847. for _, value := range paramslist {
  1848. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1849. if tempv, exists := c.Get("jwt_username"); exists {
  1850. s_params = append(s_params, tempv.(string))
  1851. } else {
  1852. s_params = append(s_params, "")
  1853. }
  1854. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1855. ids, err := setting.SnowIds.NextId()
  1856. if err != nil {
  1857. ids = time.Now().UnixNano()
  1858. logging.Info("create SnowIds err", err)
  1859. }
  1860. s_params = append(s_params, ids)
  1861. } else {
  1862. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1863. }
  1864. }
  1865. }
  1866. } else if fsion2.HasKey("params") {
  1867. params := fsion2.Get("params").Array()
  1868. //ids,err := setting.SnowIds.NextId()
  1869. //if err !=nil{
  1870. // ids = time.Now().UnixNano()
  1871. // logging.Info("create SnowIds err",err)
  1872. //}
  1873. //s_params = append(s_params, ids)
  1874. for _, v_params := range params {
  1875. s_params = append(s_params, v_params.ValueStr())
  1876. }
  1877. }
  1878. _, err := execDataBySql(sql, s_params)
  1879. if err != nil {
  1880. logging.Error("PostDataByName err: ", err)
  1881. errorm := make(map[string]interface{})
  1882. errorm["code"] = e.ERROR
  1883. errorm["message"] = err.Error()
  1884. errorm["param"] = s_params
  1885. queryData[fsion2.Get("name").ValueStr()] = errorm
  1886. continue
  1887. } else {
  1888. errorm := make(map[string]interface{})
  1889. errorm["code"] = e.SUCCESS
  1890. errorm["message"] = "success"
  1891. queryData[fsion2.Get("name").ValueStr()] = errorm
  1892. continue
  1893. }
  1894. } else {
  1895. errorm := make(map[string]interface{})
  1896. errorm["code"] = e.ERROR
  1897. errorm["message"] = "NO SQL"
  1898. errorm["param"] = ""
  1899. queryData[fsion2.Get("name").ValueStr()] = errorm
  1900. }
  1901. }
  1902. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1903. }
  1904. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1905. if offset > 0 {
  1906. offset = offset - 1
  1907. }
  1908. //if pagecount == 0 {
  1909. // pagecount = setting.AppSetting.PageSize
  1910. //}else if pagecount>setting.AppSetting.PageSize{
  1911. // pagecount = setting.AppSetting.PageSize
  1912. //}
  1913. if returntype == "list" {
  1914. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1915. return queryData, err
  1916. } else if returntype == "listlist" {
  1917. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1918. return queryData, err
  1919. } else {
  1920. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1921. return queryData, err
  1922. }
  1923. }
  1924. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1925. if offset > 0 {
  1926. offset = offset - 1
  1927. }
  1928. //if pagecount == 0 {
  1929. // pagecount = setting.AppSetting.PageSize
  1930. //}else if pagecount>setting.AppSetting.PageSize{
  1931. // pagecount = setting.AppSetting.PageSize
  1932. //}
  1933. if returntype == "list" {
  1934. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1935. return queryData, err
  1936. } else if returntype == "listlist" {
  1937. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1938. return queryData, err
  1939. } else {
  1940. fmt.Println(params)
  1941. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1942. return queryData, err
  1943. }
  1944. }
  1945. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1946. paramslist := strings.Split(Params, ",")
  1947. s_params := make([]interface{}, 0)
  1948. if isList {
  1949. for _, v_params := range thisParams["params"].([]interface{}) {
  1950. s_params = append(s_params, v_params)
  1951. }
  1952. } else {
  1953. paramslist := strings.Split(Params, ",")
  1954. if len(paramslist) > 0 && Params != "" {
  1955. for _, value := range paramslist {
  1956. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1957. }
  1958. }
  1959. }
  1960. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  1961. for _, queryData_ := range queryData {
  1962. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  1963. if isList {
  1964. if queryData_[idname] != nil {
  1965. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  1966. }
  1967. } else {
  1968. if queryData_[idname] != nil {
  1969. thisParams[idname] = queryData_[idname].(interface{})
  1970. }
  1971. if len(paramslist) > 0 && Params != "" {
  1972. s_params = make([]interface{}, 0)
  1973. for _, value := range paramslist {
  1974. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1975. }
  1976. }
  1977. }
  1978. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  1979. } else {
  1980. }
  1981. }
  1982. return queryData, err
  1983. }
  1984. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1985. queryData, err := restful.ExecQuery(sqlstr, params)
  1986. return queryData, err
  1987. }
  1988. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1989. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  1990. return queryData, err
  1991. }
  1992. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1993. queryData, err := restful.ExecQuery(sqlstr, params)
  1994. return queryData, err
  1995. }
  1996. // @Summary 导入excel文件到数据库,excel第一行作为参数
  1997. // @Tags ImportExcel
  1998. // @Accept json
  1999. // @Produce json
  2000. // @Param file query string true "文件名"
  2001. // @Param name header string true "执行sql的名字"
  2002. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2003. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2004. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2005. // @Router /data/ImportExcel [POST]
  2006. func ImportExcel(c *gin.Context) {
  2007. appG := app.Gin{C: c}
  2008. inputdata := ""
  2009. c.Request.ParseForm()
  2010. params := c.Request.Form
  2011. file, _, err := c.Request.FormFile("file")
  2012. if err != nil {
  2013. appG.Response(http.StatusOK, e.ERROR, err)
  2014. return
  2015. }
  2016. sqlnamestrs := params.Get("name")
  2017. sheetname := params.Get("sheetname")
  2018. pastureid := params.Get("pastureid")
  2019. //importParams := params.Get("importParams")
  2020. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2021. // 必输项参数 (字符串格式 "field1,field2,field3")
  2022. requiredParams := params.Get("requiredParams")
  2023. // 日期参数
  2024. dateParams := params.Get("dateParams")
  2025. // 数字参数
  2026. numParams := params.Get("numParams")
  2027. //将字符串分割开
  2028. dateParamslist := strings.Split(dateParams, ",")
  2029. requiredParamslist := strings.Split(requiredParams, ",")
  2030. numParamslist := strings.Split(numParams, ",")
  2031. queryData := make([]interface{}, 0)
  2032. sqlslist := strings.Split(sqlnamestrs, ",")
  2033. xlsx1, err := excelize.OpenReader(file)
  2034. if err != nil {
  2035. fmt.Println(err)
  2036. return
  2037. }
  2038. ok := 0
  2039. error := 0
  2040. isdone := true
  2041. rows := xlsx1.GetRows(sheetname)
  2042. // 限制10000条,多余的截取掉
  2043. if len(rows) > 10000 {
  2044. rows = rows[:10000]
  2045. }
  2046. for i, row := range rows {
  2047. if i > 0 {
  2048. entry := make(map[string]interface{})
  2049. outentry := make(map[string]interface{})
  2050. for j, colCell := range rows[0] {
  2051. for k, colCell1 := range row {
  2052. if j == k {
  2053. outentry[colCell] = colCell1
  2054. entry[colCell] = colCell1
  2055. }
  2056. }
  2057. }
  2058. inputdata = ""
  2059. a := ""
  2060. fmt.Println(outentry, entry)
  2061. //校验日期格式
  2062. for _, v := range dateParamslist {
  2063. if v == "" {
  2064. continue
  2065. }
  2066. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2067. dtime, err := TransfTime(d.(string))
  2068. if err != nil {
  2069. a = strings.Trim(v, " ")
  2070. break
  2071. }
  2072. outentry[strings.Trim(v, " ")] = dtime
  2073. }
  2074. }
  2075. if a != "" {
  2076. outentry["error_msg"] = a + " 格式错误"
  2077. error++
  2078. queryData = append(queryData, outentry)
  2079. continue
  2080. }
  2081. a = ""
  2082. //校验必填格式
  2083. for _, v := range requiredParamslist {
  2084. if v == "" {
  2085. continue
  2086. }
  2087. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2088. a = strings.Trim(v, " ")
  2089. break
  2090. }
  2091. }
  2092. if a != "" {
  2093. outentry["error_msg"] = a + " 未填或格式错误"
  2094. error++
  2095. queryData = append(queryData, outentry)
  2096. continue
  2097. }
  2098. a = ""
  2099. //校验数字格式
  2100. for _, v := range numParamslist {
  2101. if v == "" {
  2102. continue
  2103. }
  2104. d, ok := outentry[strings.Trim(v, " ")]
  2105. if !ok || d == "" {
  2106. outentry[strings.Trim(v, " ")] = 0
  2107. } else {
  2108. var fl float64
  2109. switch d.(type) {
  2110. case string:
  2111. fl, err = strconv.ParseFloat(d.(string), 64)
  2112. }
  2113. if err != nil || fl < 0 {
  2114. a = strings.Trim(v, " ")
  2115. break
  2116. }
  2117. }
  2118. }
  2119. if a != "" {
  2120. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2121. error++
  2122. queryData = append(queryData, outentry)
  2123. continue
  2124. }
  2125. tx := restful.Engine.NewSession()
  2126. err := tx.Begin()
  2127. for _, sqlnamestr := range sqlslist {
  2128. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2129. paramslist := strings.Split(paramslists, ",")
  2130. if len(paramslist) > 0 {
  2131. s_params := make([]interface{}, 0)
  2132. for _, value := range paramslist {
  2133. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2134. if tempv, exists := c.Get("jwt_username"); exists {
  2135. s_params = append(s_params, tempv.(string))
  2136. } else {
  2137. s_params = append(s_params, "")
  2138. }
  2139. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2140. s_params = append(s_params, pastureid)
  2141. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2142. ids, err := setting.SnowIds.NextId()
  2143. if err != nil {
  2144. ids = time.Now().UnixNano()
  2145. logging.Info("create SnowIds err", err)
  2146. }
  2147. s_params = append(s_params, ids)
  2148. } else {
  2149. if outentry[strings.Trim(value, " ")] == nil {
  2150. s_params = append(s_params, "")
  2151. } else {
  2152. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2153. }
  2154. }
  2155. }
  2156. outentry["input"] = inputdata
  2157. fmt.Println(sql, s_params)
  2158. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2159. if err != nil {
  2160. if tx != nil {
  2161. tx.Rollback()
  2162. }
  2163. if tx != nil {
  2164. tx.Close()
  2165. }
  2166. msg := geterrmsg(err.Error())
  2167. outentry["error_msg"] = msg
  2168. error++
  2169. queryData = append(queryData, outentry)
  2170. isdone = true
  2171. break
  2172. } else {
  2173. if len(returnmsgmap1) > 0 {
  2174. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2175. if tx != nil {
  2176. tx.Rollback()
  2177. }
  2178. if tx != nil {
  2179. tx.Close()
  2180. }
  2181. msg := geterrmsg(va.(string))
  2182. outentry["error_msg"] = msg
  2183. error++
  2184. queryData = append(queryData, outentry)
  2185. isdone = true
  2186. break
  2187. }
  2188. }
  2189. isdone = false
  2190. }
  2191. }
  2192. }
  2193. switch {
  2194. case err != nil:
  2195. if tx != nil {
  2196. tx.Rollback()
  2197. }
  2198. default:
  2199. if tx != nil {
  2200. err = tx.Commit()
  2201. }
  2202. }
  2203. if tx != nil {
  2204. tx.Close()
  2205. }
  2206. }
  2207. if !isdone {
  2208. ok++
  2209. isdone = true
  2210. }
  2211. }
  2212. data := make(map[string]interface{})
  2213. data["result"] = queryData
  2214. data["success"] = ok
  2215. data["err_count"] = error
  2216. appG.Response(http.StatusOK, e.SUCCESS, data)
  2217. }
  2218. func TransfTime(timestr string) (string, error) {
  2219. if timestr == "" {
  2220. return time.Now().Format("2006-01-02"), nil
  2221. }
  2222. days, err := strconv.Atoi(timestr)
  2223. if err != nil {
  2224. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2225. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2226. }
  2227. _, err := time.Parse("2006-01-02", timestr)
  2228. if err != nil {
  2229. t, err := time.Parse("2006/01/02", timestr)
  2230. if err != nil {
  2231. t, err := time.Parse("2006.01.02", timestr)
  2232. if err != nil {
  2233. return "", err
  2234. } else {
  2235. return t.Format("2006-01-02"), nil
  2236. }
  2237. } else {
  2238. return t.Format("2006-01-02"), nil
  2239. }
  2240. } else {
  2241. return timestr, nil
  2242. }
  2243. }
  2244. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2245. times = times.AddDate(0, 0, days)
  2246. return times.Format("2006-01-02"), nil
  2247. }
  2248. func Createchart(c *gin.Context) {
  2249. appG := app.Gin{C: c}
  2250. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2251. fsion := gofasion.NewFasion(string(dataByte))
  2252. chart_name := fsion.Get("chart_name").ValueStr()
  2253. desc := fsion.Get("desc").ValueStr()
  2254. pastureid := fsion.Get("pastureid").ValueStr()
  2255. source_id := fsion.Get("source_id").ValueStr()
  2256. emp := fsion.Get("emp").ValueStr()
  2257. content := fsion.Get("content").Json()
  2258. var mapResult map[string]interface{}
  2259. err1 := json.Unmarshal([]byte(content), &mapResult)
  2260. if err1 != nil {
  2261. fmt.Println("JsonToMapDemo err: ", err1)
  2262. }
  2263. tx := restful.Engine.NewSession()
  2264. err := tx.Begin()
  2265. defer func() {
  2266. switch {
  2267. case err != nil:
  2268. logging.Error("tx.Begin 事务启动失败__error:", err)
  2269. if tx != nil {
  2270. tx.Rollback()
  2271. }
  2272. default:
  2273. if tx != nil {
  2274. err = tx.Commit()
  2275. }
  2276. }
  2277. if tx != nil {
  2278. tx.Close()
  2279. }
  2280. }()
  2281. ids, err := setting.SnowIds.NextId()
  2282. if err != nil {
  2283. ids = time.Now().UnixNano()
  2284. logging.Info("create SnowIds err", err)
  2285. }
  2286. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2287. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2288. if err != nil {
  2289. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2290. } else {
  2291. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2292. }
  2293. }
  2294. func Updatedashboard(c *gin.Context) {
  2295. appG := app.Gin{C: c}
  2296. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2297. fsion := gofasion.NewFasion(string(dataByte))
  2298. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2299. pastureid := fsion.Get("pastureid").ValueStr()
  2300. content := fsion.Get("content").Json()
  2301. var mapResult map[string]interface{}
  2302. err1 := json.Unmarshal([]byte(content), &mapResult)
  2303. if err1 != nil {
  2304. fmt.Println("JsonToMapDemo err: ", err1)
  2305. }
  2306. layout := mapResult["layout"]
  2307. tx := restful.Engine.NewSession()
  2308. err := tx.Begin()
  2309. defer func() {
  2310. switch {
  2311. case err != nil:
  2312. logging.Error("tx.Begin 事务启动失败__error:", err)
  2313. if tx != nil {
  2314. tx.Rollback()
  2315. }
  2316. default:
  2317. if tx != nil {
  2318. err = tx.Commit()
  2319. }
  2320. }
  2321. if tx != nil {
  2322. tx.Close()
  2323. }
  2324. }()
  2325. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2326. if err != nil {
  2327. println("2", err.Error())
  2328. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2329. } else {
  2330. if exec != nil {
  2331. if exec[0]["content"] == nil {
  2332. mapR := make(map[string]interface{})
  2333. mapR["layout"] = layout
  2334. mjson, _ := json.Marshal(mapR)
  2335. mString := string(mjson)
  2336. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2337. if err3 != nil {
  2338. println("3", err3.Error())
  2339. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2340. } else {
  2341. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2342. }
  2343. } else {
  2344. var mapR map[string]interface{}
  2345. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2346. if err1 != nil {
  2347. fmt.Println("JsonToMapDemo err: ", err2)
  2348. }
  2349. mapR["layout"] = layout
  2350. mjson, _ := json.Marshal(mapR)
  2351. mString := string(mjson)
  2352. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2353. if err3 != nil {
  2354. println("3", err3.Error())
  2355. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2356. } else {
  2357. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2358. }
  2359. }
  2360. } else {
  2361. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2362. }
  2363. }
  2364. }
  2365. func ExecSQL(c *gin.Context) {
  2366. appG := app.Gin{C: c}
  2367. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2368. fsion := gofasion.NewFasion(string(dataByte))
  2369. content := fsion.Get("content").Json()
  2370. pastureid := fsion.Get("pastureid").ValueStr()
  2371. var mapResult map[string]interface{}
  2372. err1 := json.Unmarshal([]byte(content), &mapResult)
  2373. if err1 != nil {
  2374. fmt.Println("JsonToMapDemo err: ", err1)
  2375. }
  2376. sqlstr := "select "
  2377. groupstr := " GROUP BY "
  2378. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2379. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2380. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2381. }
  2382. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2383. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2384. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2385. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2386. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2387. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2388. sqlstr = sqlstr + tem + ","
  2389. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2390. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2391. sqlstr = sqlstr + tem + ","
  2392. } else {
  2393. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2394. sqlstr = sqlstr + tem + ","
  2395. }
  2396. }
  2397. if _, ok := mapResult["selectedCalcul2"]; ok {
  2398. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2399. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2400. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2401. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2402. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2403. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2404. sqlstr = sqlstr + tem + ","
  2405. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2406. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2407. sqlstr = sqlstr + tem + ","
  2408. } else {
  2409. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2410. sqlstr = sqlstr + tem + ","
  2411. }
  2412. }
  2413. }
  2414. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2415. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2416. sqlstr = sqlstr + " where pastureid=" + pastureid
  2417. if len(mapResult["filters"].([]interface{})) > 0 {
  2418. sqlstr = sqlstr + " and "
  2419. }
  2420. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2421. for _, value := range mapResult["filters"].([]interface{}) {
  2422. switch value.(map[string]interface{})["filterOperator"].(string) {
  2423. case ">", "=", "<", ">=", "<=", "!=", "like":
  2424. 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 "
  2425. case "IN":
  2426. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2427. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2428. sqlstr = sqlstr + value1.(string) + ","
  2429. }
  2430. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2431. sqlstr = sqlstr + ")" + " AND "
  2432. case "BETWEEN":
  2433. 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 "
  2434. }
  2435. }
  2436. if len(mapResult["filters"].([]interface{})) > 0 {
  2437. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2438. }
  2439. //
  2440. groupstr = groupstr[0 : len(groupstr)-1]
  2441. sqlstr = sqlstr + groupstr + " "
  2442. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2443. sqlstr = sqlstr + " order by "
  2444. }
  2445. //
  2446. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2447. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2448. sqlstr = sqlstr + value.(string) + " "
  2449. } else {
  2450. sqlstr = sqlstr + value.(string) + ","
  2451. }
  2452. }
  2453. //
  2454. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2455. tx := restful.Engine.NewSession()
  2456. err := tx.Begin()
  2457. defer func() {
  2458. switch {
  2459. case err != nil:
  2460. logging.Error("tx.Begin 事务启动失败__error:", err)
  2461. if tx != nil {
  2462. tx.Rollback()
  2463. }
  2464. default:
  2465. if tx != nil {
  2466. err = tx.Commit()
  2467. }
  2468. }
  2469. if tx != nil {
  2470. tx.Close()
  2471. }
  2472. }()
  2473. exec, err := tx.SQL(sqlstr).Query().List()
  2474. if err != nil {
  2475. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2476. } else {
  2477. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2478. }
  2479. }
  2480. func Dashboards(c *gin.Context) {
  2481. appG := app.Gin{C: c}
  2482. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2483. fsion := gofasion.NewFasion(string(dataByte))
  2484. sqlnamestr := fsion.Get("name").ValueStr()
  2485. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2486. offset := fsion.Get("offset").ValueDefaultInt(0)
  2487. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2488. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2489. month := fsion.Get("month").ValueDefaultStr("map")
  2490. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2491. tx := restful.Engine.NewSession()
  2492. err := tx.Begin()
  2493. defer func() {
  2494. switch {
  2495. case err != nil:
  2496. if tx != nil {
  2497. tx.Rollback()
  2498. }
  2499. default:
  2500. if tx != nil {
  2501. err = tx.Commit()
  2502. }
  2503. }
  2504. if tx != nil {
  2505. tx.Close()
  2506. }
  2507. }()
  2508. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2509. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2510. if sql != "" {
  2511. s_params := make([]interface{}, 0)
  2512. if fsion.HasKey("parammaps") {
  2513. parammaps := fsion.Get("parammaps")
  2514. paramslist := strings.Split(p, ",")
  2515. if len(paramslist) > 0 && p != "" {
  2516. for _, value := range paramslist {
  2517. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2518. if tempv, exists := c.Get("jwt_username"); exists {
  2519. s_params = append(s_params, tempv.(string))
  2520. } else {
  2521. s_params = append(s_params, "")
  2522. }
  2523. } else {
  2524. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2525. }
  2526. }
  2527. }
  2528. }
  2529. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2530. if err != nil {
  2531. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2532. } else {
  2533. //paramslist1 := strings.Split(p1, ",")
  2534. dids := make([]interface{}, 0)
  2535. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2536. var mapResult map[string]interface{}
  2537. dids = append(dids, value["dashboard_id"])
  2538. if value["content"] != nil {
  2539. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2540. if err1 != nil {
  2541. println("JsonToMapDemo1 err: ", err1)
  2542. }
  2543. temap := make(map[string]interface{})
  2544. tem := mapResult["layout"].([]interface{})
  2545. if v, ok := value["chartids"]; ok {
  2546. chartids := strings.Split(v.(string), ",")
  2547. for _, va := range chartids {
  2548. a := false
  2549. for _, v2 := range tem {
  2550. if v2.(map[string]interface{})["id"].(string) == va {
  2551. a = true
  2552. //println("va1======",va)
  2553. }
  2554. }
  2555. if !a {
  2556. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2557. va + "\",\"id\":\"" + va +
  2558. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2559. var mapTem map[string]interface{}
  2560. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2561. if err1 != nil {
  2562. println("JsonToMapDemo err: ", err1)
  2563. }
  2564. tem = append(tem, mapTem)
  2565. }
  2566. }
  2567. temap["layout"] = tem
  2568. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2569. }
  2570. } else {
  2571. temap := make(map[string]interface{})
  2572. tem := make([]interface{}, 0)
  2573. if v, ok := value["chartids"]; ok {
  2574. chartids := strings.Split(v.(string), ",")
  2575. for _, va := range chartids {
  2576. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2577. va + "\",\"id\":\"" + va +
  2578. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2579. var mapTem map[string]interface{}
  2580. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2581. if err1 != nil {
  2582. println("JsonToMapDemo err: ", err1)
  2583. }
  2584. tem = append(tem, mapTem)
  2585. }
  2586. temap["layout"] = tem
  2587. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2588. }
  2589. }
  2590. }
  2591. queryData.(map[string]interface{})["order"] = dids
  2592. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2593. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2594. }
  2595. } else {
  2596. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2597. }
  2598. }
  2599. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2600. fsion := gofasion.NewFasion(parammaps)
  2601. sqlnamestr := fsion.Get("name").ValueStr()
  2602. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2603. offset := fsion.Get("offset").ValueDefaultInt(0)
  2604. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2605. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2606. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2607. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2608. body := []byte("")
  2609. if sql != "" {
  2610. s_params := make([]interface{}, 0)
  2611. if fsion.HasKey("parammaps") {
  2612. parammaps := fsion.Get("parammaps")
  2613. paramslist := strings.Split(p, ",")
  2614. if len(paramslist) > 0 && p != "" {
  2615. for _, value := range paramslist {
  2616. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2617. }
  2618. }
  2619. }
  2620. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2621. if err != nil {
  2622. } else {
  2623. paramslist1 := strings.Split(p1, ",")
  2624. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2625. s_params1 := make([]interface{}, 0)
  2626. if len(paramslist1) > 0 && p1 != "" {
  2627. for _, v := range paramslist1 {
  2628. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2629. }
  2630. }
  2631. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2632. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2633. body, _ = json.Marshal(queryData)
  2634. }
  2635. }
  2636. }
  2637. bs := bytes.NewBuffer(body)
  2638. client := &http.Client{}
  2639. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2640. req, err := http.NewRequest(RequestMethod,
  2641. url,
  2642. bs,
  2643. )
  2644. if err != nil {
  2645. }
  2646. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2647. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2648. if err != nil {
  2649. // handle error
  2650. }
  2651. resp, err := client.Do(req)
  2652. if err != nil {
  2653. return ""
  2654. }
  2655. defer resp.Body.Close()
  2656. result_body, err := ioutil.ReadAll(resp.Body)
  2657. if err != nil {
  2658. return ""
  2659. }
  2660. fmt.Println(string(result_body))
  2661. return ""
  2662. }
  2663. func GetSummary(c *gin.Context) {
  2664. appG := app.Gin{C: c}
  2665. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2666. fsion := gofasion.NewFasion(string(dataByte))
  2667. offset := fsion.Get("offset").ValueDefaultInt(0)
  2668. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2669. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2670. parammaps := fsion.Get("parammaps")
  2671. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2672. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2673. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2674. tx := restful.Engine.NewSession()
  2675. defer tx.Close()
  2676. sqlnamestr := ""
  2677. if genre == "0" {
  2678. if status == "0" {
  2679. sqlnamestr = "getAccuracyJSY"
  2680. } else if status == "1" {
  2681. sqlnamestr = "getAccuracyHFT"
  2682. } else if status == "2" {
  2683. sqlnamestr = "getAccuracyHNS"
  2684. } else if status == "3" {
  2685. sqlnamestr = "getAccuracyHSC"
  2686. } else if status == "4" {
  2687. sqlnamestr = "getAccuracyHCC"
  2688. } else if status == "5" {
  2689. sqlnamestr = "getAccuracyMC"
  2690. } else if status == "6" {
  2691. sqlnamestr = "getAccuracyFeedHL"
  2692. } else if status == "7" {
  2693. sqlnamestr = "getAccuracyRT"
  2694. }
  2695. } else {
  2696. if status == "0" {
  2697. sqlnamestr = "getAccuracySCCJSY"
  2698. } else if status == "1" {
  2699. sqlnamestr = "getAccuracySFT"
  2700. } else if status == "2" {
  2701. sqlnamestr = "getAccuracySNS"
  2702. } else if status == "3" {
  2703. sqlnamestr = "getAccuracySSC"
  2704. } else if status == "4" {
  2705. sqlnamestr = "getAccuracySCC"
  2706. } else if status == "5" {
  2707. sqlnamestr = "getAccuracySLCL"
  2708. } else if status == "7" {
  2709. sqlnamestr = "getAccuracySCCRT"
  2710. }
  2711. }
  2712. if isDate == "1" {
  2713. sqlnamestr += "Date"
  2714. }
  2715. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2716. // fmt.Println(sqlnamestr, sql)
  2717. if sql != "" {
  2718. s_params := make([]interface{}, 0)
  2719. // if fsion.HasKey("parammaps") {
  2720. fmt.Println(s_params, "222", p)
  2721. paramslist := strings.Split(p, ",")
  2722. if len(paramslist) > 0 && p != "" {
  2723. for _, value := range paramslist {
  2724. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2725. if tempv, exists := c.Get("jwt_username"); exists {
  2726. s_params = append(s_params, tempv.(string))
  2727. } else {
  2728. s_params = append(s_params, "")
  2729. }
  2730. } else {
  2731. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2732. }
  2733. }
  2734. }
  2735. if returntype == "xlsx" {
  2736. var xlsxfile *xlsx.File
  2737. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2738. //c.File("c:/dd.xlsx")
  2739. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2740. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2741. c.Header("Content-Transfer-Encoding", "binary")
  2742. _ = xlsxfile.Write(c.Writer)
  2743. } else {
  2744. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2745. if err != nil {
  2746. logging.Error("GetDataByName err: ", err)
  2747. msg := geterrmsg(err.Error())
  2748. appG.Response(http.StatusOK, e.ERROR, msg)
  2749. } else {
  2750. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2751. }
  2752. }
  2753. } else {
  2754. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2755. }
  2756. }
  2757. // type lpplanStruct struct {
  2758. // Id int64 `xorm:"id"`
  2759. // Tmrname string `xorm:"tmrname"`
  2760. // Tmrid int64 `xorm:"tmrid"`
  2761. // Sort int64 `xorm:"sort"`
  2762. // Sel int64 `xorm:"sel"`
  2763. // Times int64 `xorm:"times"`
  2764. // Ftname string `xorm:"ftname"`
  2765. // Ftid int64 `xorm:"ftid"`
  2766. // Maxweight float64 `xorm:"maxweight"`
  2767. // Sumweight float64 `xorm:"sumweight"`
  2768. // Sumcowcount int64 `xorm:"sumcowcount"`
  2769. // Pastureid string `xorm:"pastureid"`
  2770. // Display string `xorm:"display"`
  2771. // Issplit int64 `xorm:"issplit"`
  2772. // BeginTime string `xorm:"begintime"`
  2773. // }
  2774. func UpdateFTdetail(c *gin.Context) {
  2775. appG := app.Gin{C: c}
  2776. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2777. tempval_ := make(map[string]interface{})
  2778. tempCommon := make(map[string]interface{})
  2779. tempval := make([]map[string]interface{}, 0)
  2780. fTChange := make(map[string]interface{}, 0)
  2781. fpdOldDataList := make([]map[string]interface{}, 0)
  2782. fpdDataList := make([]map[string]interface{}, 0)
  2783. fsion := gofasion.NewFasion(string(dataByte))
  2784. // parammaps := fsion.Get("parammaps")
  2785. createdate := time.Now().Format("2006-01-02 15:04:05")
  2786. err := json.Unmarshal(dataByte, &tempval_)
  2787. if err != nil {
  2788. appG.Response(http.StatusOK, e.ERROR, false)
  2789. return
  2790. }
  2791. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2792. tx := restful.Engine.NewSession()
  2793. if v, ok := tempval_["data"].([]interface{}); ok {
  2794. for _, Tvalue := range v {
  2795. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2796. if v1["name"] == "updateFPbyFTChange" {
  2797. fTChange = v1
  2798. continue
  2799. }
  2800. tempval = append(tempval, v1)
  2801. }
  2802. }
  2803. }
  2804. parammaps := fTChange["parammaps"].(map[string]interface{})
  2805. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2806. // if err != nil {
  2807. // logs.Error(err)
  2808. // appG.Response(http.StatusOK, e.ERROR, false)
  2809. // return
  2810. // }
  2811. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2812. // if err != nil {
  2813. // logs.Error(err)
  2814. // appG.Response(http.StatusOK, e.ERROR, false)
  2815. // return
  2816. // }
  2817. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2818. // if err != nil {
  2819. // logs.Error(err)
  2820. // appG.Response(http.StatusOK, e.ERROR, false)
  2821. // return
  2822. // }
  2823. err = tx.Begin()
  2824. if err != nil {
  2825. logging.Error("tx.Begin 事务启动失败__error:", err)
  2826. }
  2827. defer func() {
  2828. if err != nil {
  2829. if tx != nil {
  2830. tx.Rollback()
  2831. }
  2832. }
  2833. if tx != nil {
  2834. tx.Close()
  2835. }
  2836. }()
  2837. if err != nil {
  2838. } else {
  2839. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2840. tempCommon = v
  2841. }
  2842. 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 ,
  2843. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2844. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2845. UNION
  2846. 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 ,
  2847. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2848. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2849. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2850. if err == nil {
  2851. if tempv, exists := c.Get("jwt_username"); exists {
  2852. tempCommon["jwt_username"] = tempv.(string)
  2853. }
  2854. for _, paramvalue := range tempval {
  2855. if _, ok := paramvalue["resultname"]; !ok {
  2856. paramvalue["resultname"] = paramvalue["name"]
  2857. }
  2858. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2859. if err != nil {
  2860. logging.Error("ExecDataParam error:", err)
  2861. break
  2862. }
  2863. }
  2864. if err != nil {
  2865. msg := geterrmsg(err.Error())
  2866. appG.Response(http.StatusOK, e.ERROR, msg)
  2867. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2868. }
  2869. }
  2870. }
  2871. tx.Commit()
  2872. // go func() {
  2873. if fTChange != nil {
  2874. parammaps := fTChange["parammaps"].(map[string]interface{})
  2875. if parammaps["type"].(float64) == 1 {
  2876. _, err = tx.SQL(`UPDATE feedp fp
  2877. set
  2878. ccountratio = ccount *(ratio /100 ),
  2879. fp.ftweight= IFNULL(IF(
  2880. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2881. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2882. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2883. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2884. ),0),fp.feedweight = 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.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2887. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2888. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2889. ),0) +ifnull(fp.supplyweight,0)
  2890. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2891. _, err = tx.SQL(`UPDATE fpdetail fpd
  2892. INNER JOIN feedp fp
  2893. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2894. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2895. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2896. } else {
  2897. _, err = tx.SQL(`UPDATE feedp fp
  2898. SET ccountratio = ccount *(ratio /100 ),
  2899. fp.supplyweight= IFNULL(IF(
  2900. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2901. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2902. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2903. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2904. ),0),fp.feedweight = IFNULL(IF(
  2905. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2906. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2907. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2908. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2909. ),0) +ifnull(fp.supplyweight,0)
  2910. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2911. _, err = tx.SQL(`UPDATE fpdetail fpd
  2912. INNER JOIN feedp fp
  2913. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2914. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2915. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2916. }
  2917. fpdDataList, err = tx.SQL(`select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(ptsid ) ptsid ,
  2918. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2919. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2920. UNION
  2921. SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(ptsid ) ptsid ,
  2922. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2923. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2924. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2925. lpplanList := make([]*lpplanStruct, 0)
  2926. err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2927. if err != nil {
  2928. logs.Error(err, 1)
  2929. return
  2930. }
  2931. lppidlist := []string{}
  2932. for _, lpp := range lpplanList {
  2933. lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2934. }
  2935. if len(lppidlist) <= 0 {
  2936. appG.Response(http.StatusOK, e.SUCCESS, true)
  2937. return
  2938. }
  2939. lpplandtl1AllList := make([]*lpplandtl1, 0)
  2940. err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  2941. order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  2942. if err != nil {
  2943. // tx.Rollback()
  2944. logs.Error(err, 2, parammaps["pastureid"])
  2945. return
  2946. }
  2947. var wg sync.WaitGroup
  2948. for _, old := range fpdOldDataList {
  2949. for _, fpd := range fpdDataList {
  2950. wg.Add(1)
  2951. go func(old, fpd map[string]interface{}) {
  2952. updateLppandList := make([]*lpplandtl1, 0)
  2953. defer wg.Done()
  2954. if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  2955. fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  2956. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  2957. oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  2958. // if weight > oldweight {
  2959. // return
  2960. // }
  2961. var w float64
  2962. var status int
  2963. if weight < oldweight {
  2964. if weight >= 0 {
  2965. return
  2966. }
  2967. w = weight
  2968. status = 0
  2969. } else {
  2970. if oldweight > 0 {
  2971. return
  2972. }
  2973. w = weight
  2974. status = 1
  2975. }
  2976. // fweight = w
  2977. for _, lpp := range lpplanList {
  2978. var fweight float64
  2979. var lweight float64
  2980. lpplandtl1List := make([]*lpplandtl1, 0)
  2981. fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  2982. for _, lppland := range lpplandtl1AllList {
  2983. if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  2984. lpplandtl1List = append(lpplandtl1List, lppland)
  2985. }
  2986. }
  2987. if len(lpplandtl1List) == 0 {
  2988. continue
  2989. }
  2990. for _, lppland := range lpplandtl1List {
  2991. lweight += lppland.Lweight
  2992. }
  2993. if status == 0 {
  2994. if lweight <= 0 {
  2995. continue
  2996. }
  2997. } else {
  2998. if lpp.Maxweight <= lweight {
  2999. continue
  3000. }
  3001. }
  3002. for _, lppland := range lpplandtl1List {
  3003. if fpdid == lppland.Fpdid {
  3004. if status == 1 {
  3005. // if w <= lppland.Lweight {
  3006. if lpp.Maxweight <= lweight {
  3007. continue
  3008. }
  3009. if w+lweight <= lpp.Maxweight {
  3010. lppland.Lweight += w
  3011. lweight += w
  3012. fweight += w
  3013. w = 0
  3014. } else {
  3015. w = w - (lpp.Maxweight - lweight)
  3016. n := (lpp.Maxweight - lweight)
  3017. lppland.Lweight = lppland.Lweight + n
  3018. lweight += n
  3019. fweight += n
  3020. }
  3021. } else {
  3022. if lppland.Lweight == 0 {
  3023. continue
  3024. }
  3025. if w+lppland.Lweight >= 0 {
  3026. lppland.Lweight = lppland.Lweight + w
  3027. lweight = lweight + w
  3028. fweight = fweight + w
  3029. w = 0
  3030. } else {
  3031. w = w + lppland.Lweight
  3032. lweight = lweight - lppland.Lweight
  3033. fweight = fweight - lppland.Lweight
  3034. lppland.Lweight = 0
  3035. }
  3036. }
  3037. updateLppandList = append(updateLppandList, lppland)
  3038. break
  3039. }
  3040. }
  3041. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3042. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3043. WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3044. if err != nil {
  3045. // tx.Rollback()
  3046. logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3047. return
  3048. }
  3049. for _, lppland := range updateLppandList {
  3050. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3051. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3052. if err != nil {
  3053. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3054. // tx.Rollback()
  3055. logs.Error(err, 3)
  3056. return
  3057. }
  3058. // defer wg.Done()
  3059. }
  3060. updateLppandList = []*lpplandtl1{}
  3061. if w == 0 {
  3062. break
  3063. }
  3064. }
  3065. }
  3066. }(old, fpd)
  3067. }
  3068. }
  3069. wg.Wait()
  3070. }
  3071. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3072. if err != nil {
  3073. logs.Error(err)
  3074. appG.Response(http.StatusOK, e.ERROR, false)
  3075. return
  3076. }
  3077. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3078. if err != nil {
  3079. logs.Error(err)
  3080. appG.Response(http.StatusOK, e.ERROR, false)
  3081. return
  3082. }
  3083. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3084. if err != nil {
  3085. logs.Error(err)
  3086. appG.Response(http.StatusOK, e.ERROR, false)
  3087. return
  3088. }
  3089. now := createdate
  3090. // for _, oldFpd := range oldFpdDataList {
  3091. for _, newFpd := range newFpdDataList {
  3092. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3093. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3094. // go func() {
  3095. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3096. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3097. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3098. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3099. if err != nil {
  3100. logs.Error(err)
  3101. appG.Response(http.StatusOK, e.ERROR, false)
  3102. return
  3103. }
  3104. // }()
  3105. }
  3106. // break
  3107. // }
  3108. // }
  3109. // }
  3110. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3111. for _, newLpplandtl1 := range newLpplandtl1List {
  3112. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3113. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3114. // go func() {
  3115. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3116. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3117. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3118. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3119. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3120. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3121. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3122. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3123. if err != nil {
  3124. logs.Error(err)
  3125. appG.Response(http.StatusOK, e.ERROR, false)
  3126. return
  3127. }
  3128. // }()
  3129. // }
  3130. // break
  3131. // }
  3132. // }
  3133. }
  3134. // for _, oldFeedp := range oldFeedpList {
  3135. for _, newFeedp := range newFeedpList {
  3136. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3137. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3138. // go func() {
  3139. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3140. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3141. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3142. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3143. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3144. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3145. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3146. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3147. if err != nil {
  3148. logs.Error(err)
  3149. appG.Response(http.StatusOK, e.ERROR, false)
  3150. return
  3151. }
  3152. }
  3153. appG.Response(http.StatusOK, e.SUCCESS, true)
  3154. }
  3155. type lpplandtlInfo struct {
  3156. Id int64 `xorm:"id"`
  3157. Pastureid int64 `xorm:"pastureid"`
  3158. Lppid int64 `xorm:"lppid"`
  3159. Barid int64 `xorm:"barid"`
  3160. Barname string `xorm:"barname"`
  3161. Fpdid int64 `xorm:"fpdid"`
  3162. Fttype int64 `xorm:"fttype"`
  3163. Lweight float64 `xorm:"lweight"`
  3164. Sort int64 `xorm:"sort"`
  3165. Tmrid int64 `xorm:"tmrid"`
  3166. Tmrname string `xorm:"tmrname"`
  3167. Cowcount int64 `xorm:"cowcount"`
  3168. Ccountradio float64 `xorm:"ccountradio"`
  3169. Background string `xorm:"background"`
  3170. Lweighthis float64 `xorm:"lweighthis"`
  3171. Maxweight float64 `xorm:"maxweight"`
  3172. }
  3173. func UpdateFpdetailBar(c *gin.Context) {
  3174. appG := app.Gin{C: c}
  3175. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3176. fsion := gofasion.NewFasion(string(dataByte))
  3177. pastureid := fsion.Get("pastureid").ValueStr()
  3178. id := fsion.Get("id").ValueStr()
  3179. tx := restful.Engine.NewSession()
  3180. tx.Begin()
  3181. 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 `,
  3182. pastureid, id).Query().List()
  3183. if err != nil {
  3184. logs.Error(err)
  3185. }
  3186. for _, fpd := range fpdList {
  3187. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3188. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3189. pastureid, fpd["id"]).Query().List()
  3190. if err != nil {
  3191. tx.Rollback()
  3192. logs.Error(err)
  3193. appG.Response(http.StatusOK, e.ERROR, false)
  3194. return
  3195. }
  3196. var lweight float64
  3197. for _, lppland := range lpplandList {
  3198. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3199. lweight += lweight1
  3200. }
  3201. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3202. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3203. if fpdweight >= ptuse && lweight == ptuse {
  3204. continue
  3205. } else {
  3206. if lweight <= fpdweight {
  3207. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3208. if err != nil {
  3209. tx.Rollback()
  3210. logs.Error(err)
  3211. appG.Response(http.StatusOK, e.ERROR, false)
  3212. return
  3213. }
  3214. } else {
  3215. weight := fpdweight - lweight
  3216. for _, lppland := range lpplandList {
  3217. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3218. if weight >= lpplandlweight {
  3219. weight = weight - lpplandlweight
  3220. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3221. if err != nil {
  3222. tx.Rollback()
  3223. logs.Error(err)
  3224. appG.Response(http.StatusOK, e.ERROR, false)
  3225. return
  3226. }
  3227. } else {
  3228. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3229. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3230. // if err != nil {
  3231. // tx.Rollback()
  3232. // logs.Error(err)
  3233. // appG.Response(http.StatusOK, e.ERROR, false)
  3234. // return
  3235. // }
  3236. weight = 0
  3237. break
  3238. }
  3239. }
  3240. }
  3241. }
  3242. }
  3243. fsionData := fsion.Get("data").Array()
  3244. for _, list := range fsionData {
  3245. ftmap := make(map[string]interface{})
  3246. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3247. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3248. ftmap["times"] = list.Get("times").ValueInt64()
  3249. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3250. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3251. // fmt.Println(ftmap)
  3252. fpdDataList, err := tx.SQL(`
  3253. SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM((select ftid from feedp where barid =fpdetail.barid)) ptid,TRIM(ifnull(ptsid,-1) ) ptsid ,
  3254. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3255. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3256. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3257. if err != nil {
  3258. tx.Rollback()
  3259. logs.Error(err)
  3260. }
  3261. for _, fpd := range fpdDataList {
  3262. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3263. fttype := -1
  3264. if fpd["fttype"].(string) == "1" {
  3265. fttype = 1
  3266. }
  3267. var fweight float64
  3268. var lweight float64
  3269. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3270. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  3271. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3272. join tmr t on t.id = lpp.tmrid
  3273. where lppland.fpdid =?
  3274. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3275. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3276. if err != nil {
  3277. tx.Rollback()
  3278. logs.Error(err)
  3279. }
  3280. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3281. var w float64
  3282. var status int
  3283. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3284. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3285. if weight >= 0 {
  3286. continue
  3287. }
  3288. w = weight
  3289. status = 0
  3290. } else {
  3291. // continue
  3292. if weight <= 0 {
  3293. continue
  3294. }
  3295. w = weight
  3296. status = 1
  3297. }
  3298. // for _, lppland := range lpplandtl1List {
  3299. // lweight += lppland.Lweight
  3300. // }
  3301. for _, lppland := range lpplandtl1List {
  3302. lpplandInfo := new(lpplandtlInfo)
  3303. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3304. lweight = lpplandInfo.Lweight
  3305. if status == 1 {
  3306. // if w <= lppland.Lweight {
  3307. if lppland.Maxweight <= lweight {
  3308. continue
  3309. }
  3310. if w+lweight <= lppland.Maxweight {
  3311. lppland.Lweight += w
  3312. lweight += w
  3313. fweight += w
  3314. w = 0
  3315. } else {
  3316. w = w - (lppland.Maxweight - lweight)
  3317. n := (lppland.Maxweight - lweight)
  3318. lppland.Lweight = lppland.Lweight + n
  3319. lweight += n
  3320. fweight += n
  3321. }
  3322. } else {
  3323. if lppland.Lweight == 0 {
  3324. continue
  3325. }
  3326. if w+lppland.Lweight >= 0 {
  3327. lppland.Lweight = lppland.Lweight + w
  3328. lweight = lweight + w
  3329. fweight = fweight + w
  3330. w = 0
  3331. } else {
  3332. w = w + lppland.Lweight
  3333. lweight = lweight - lppland.Lweight
  3334. fweight = fweight - lppland.Lweight
  3335. lppland.Lweight = 0
  3336. }
  3337. }
  3338. if lppland.Lweight > 0 {
  3339. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3340. if err != nil {
  3341. tx.Rollback()
  3342. logs.Error(err)
  3343. return
  3344. }
  3345. } else {
  3346. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3347. if err != nil {
  3348. tx.Rollback()
  3349. logs.Error(err)
  3350. return
  3351. }
  3352. }
  3353. if w == 0 {
  3354. break
  3355. }
  3356. // break
  3357. }
  3358. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3359. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3360. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3361. if err != nil {
  3362. tx.Rollback()
  3363. logs.Error(err)
  3364. }
  3365. if w == 0 {
  3366. break
  3367. }
  3368. }
  3369. }
  3370. }
  3371. tx.Commit()
  3372. now := time.Now()
  3373. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3374. if err != nil {
  3375. logs.Error(err)
  3376. appG.Response(http.StatusOK, e.ERROR, false)
  3377. return
  3378. }
  3379. for _, newLpplandtl1 := range newLpplandtl1List {
  3380. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3381. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3382. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3383. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3384. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3385. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3386. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3387. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3388. if err != nil {
  3389. logs.Error(err)
  3390. appG.Response(http.StatusOK, e.ERROR, false)
  3391. return
  3392. }
  3393. }
  3394. appG.Response(http.StatusOK, e.SUCCESS, true)
  3395. }
  3396. func GetProcessAnalysis(c *gin.Context) {
  3397. appG := app.Gin{C: c}
  3398. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3399. fsion := gofasion.NewFasion(string(dataByte))
  3400. sqlnamestr := fsion.Get("name").ValueStr()
  3401. offset := fsion.Get("offset").ValueDefaultInt(0)
  3402. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3403. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3404. parammaps := fsion.Get("parammaps")
  3405. tx := restful.Engine.NewSession()
  3406. err := tx.Begin()
  3407. defer func() {
  3408. switch {
  3409. case err != nil:
  3410. logging.Error("tx.Begin 事务启动失败__error:", err)
  3411. if tx != nil {
  3412. tx.Rollback()
  3413. }
  3414. default:
  3415. if tx != nil {
  3416. err = tx.Commit()
  3417. }
  3418. }
  3419. if tx != nil {
  3420. tx.Close()
  3421. }
  3422. }()
  3423. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3424. s_params := make([]interface{}, 0)
  3425. paramslist := strings.Split(p, ",")
  3426. if len(paramslist) > 0 && p != "" {
  3427. for _, value := range paramslist {
  3428. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3429. if tempv, exists := c.Get("jwt_username"); exists {
  3430. s_params = append(s_params, tempv.(string))
  3431. } else {
  3432. s_params = append(s_params, "")
  3433. }
  3434. } else {
  3435. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3436. }
  3437. }
  3438. }
  3439. tmrtnameStr := ""
  3440. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3441. if len(tmrtnameStr) == 0 {
  3442. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3443. } else {
  3444. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3445. }
  3446. }
  3447. if len(tmrtnameStr) > 0 {
  3448. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3449. }
  3450. sql += " ORDER BY d.intime"
  3451. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3452. if err != nil {
  3453. logging.Error("GetDataByName err: ", err)
  3454. msg := geterrmsg(err.Error())
  3455. appG.Response(http.StatusOK, e.ERROR, msg)
  3456. } else {
  3457. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3458. }
  3459. }
  3460. func UpdateFeedtempletStatus(c *gin.Context) {
  3461. appG := app.Gin{C: c}
  3462. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3463. fsion := gofasion.NewFasion(string(dataByte))
  3464. parammaps := fsion.Get("parammaps")
  3465. tx := restful.Engine.NewSession()
  3466. tx.Begin()
  3467. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3468. if err != nil {
  3469. tx.Rollback()
  3470. logs.Error(err)
  3471. appG.Response(http.StatusOK, e.ERROR, err)
  3472. return
  3473. }
  3474. tx.Commit()
  3475. appG.Response(http.StatusOK, e.SUCCESS, true)
  3476. }
  3477. func AddFtdry(c *gin.Context) {
  3478. appG := app.Gin{C: c}
  3479. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3480. fsion := gofasion.NewFasion(string(dataByte))
  3481. sqlnamestr := fsion.Get("name").ValueStr()
  3482. s_params := make([]interface{}, 0)
  3483. tx := restful.Engine.NewSession()
  3484. err := tx.Begin()
  3485. defer func() {
  3486. switch {
  3487. case err != nil:
  3488. if tx != nil {
  3489. tx.Rollback()
  3490. }
  3491. default:
  3492. if tx != nil {
  3493. err = tx.Commit()
  3494. }
  3495. }
  3496. if tx != nil {
  3497. tx.Close()
  3498. }
  3499. }()
  3500. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3501. if sql != "" {
  3502. parammaps := fsion.Get("parammaps")
  3503. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3504. paramslist := strings.Split(p, ",")
  3505. if len(paramslist) > 0 && p != "" {
  3506. for _, value := range paramslist {
  3507. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3508. if tempv, exists := c.Get("jwt_username"); exists {
  3509. s_params = append(s_params, tempv.(string))
  3510. } else {
  3511. s_params = append(s_params, "")
  3512. }
  3513. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3514. ids, err := setting.SnowIds.NextId()
  3515. if err != nil {
  3516. ids = time.Now().UnixNano()
  3517. logging.Info("create SnowIds err", err)
  3518. }
  3519. s_params = append(s_params, ids)
  3520. } else {
  3521. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3522. }
  3523. }
  3524. }
  3525. var actweight float64
  3526. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3527. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3528. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3529. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3530. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3531. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3532. 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()
  3533. if err != nil {
  3534. logging.Error("AddFtdry err: ", err)
  3535. msg := geterrmsg(err.Error())
  3536. appG.Response(http.StatusOK, e.ERROR, msg)
  3537. }
  3538. if len(actweightList) > 0 {
  3539. for _, item := range actweightList {
  3540. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3541. if err != nil {
  3542. logging.Error("AddFtdry err: ", err)
  3543. msg := geterrmsg(err.Error())
  3544. appG.Response(http.StatusOK, e.ERROR, msg)
  3545. }
  3546. actweight = fl
  3547. }
  3548. } else {
  3549. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3550. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3551. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3552. if err != nil {
  3553. logging.Error("AddFtdry err: ", err)
  3554. msg := geterrmsg(err.Error())
  3555. appG.Response(http.StatusOK, e.ERROR, msg)
  3556. }
  3557. for _, item := range dryList {
  3558. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3559. if err != nil {
  3560. logging.Error("AddFtdry err: ", err)
  3561. msg := geterrmsg(err.Error())
  3562. appG.Response(http.StatusOK, e.ERROR, msg)
  3563. }
  3564. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3565. }
  3566. }
  3567. if sqlnamestr == "insertFtdry" {
  3568. s_params = append(s_params, actweight)
  3569. } else if sqlnamestr == "updateFtdry" {
  3570. sql = fmt.Sprintf(sql, actweight)
  3571. }
  3572. queryData, err := execDataBySqlT(sql, s_params, tx)
  3573. if err != nil {
  3574. logging.Error("AddFtdry err: ", err)
  3575. msg := geterrmsg(err.Error())
  3576. appG.Response(http.StatusOK, e.ERROR, msg)
  3577. } else {
  3578. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3579. }
  3580. } else {
  3581. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3582. }
  3583. }
  3584. func CheckDates(c *gin.Context) {
  3585. tx := restful.Engine.NewSession()
  3586. defer tx.Close()
  3587. appG := app.Gin{C: c}
  3588. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3589. tempval_ := make(map[string]interface{})
  3590. tempCommon := make(map[string]interface{})
  3591. tempval := make([]map[string]interface{}, 0)
  3592. err := json.Unmarshal(dataByte, &tempval_)
  3593. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3594. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3595. if err != nil {
  3596. } else {
  3597. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3598. tempCommon = v
  3599. }
  3600. if v, ok := tempval_["data"].([]interface{}); ok {
  3601. for _, Tvalue := range v {
  3602. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3603. tempval = append(tempval, v1)
  3604. }
  3605. }
  3606. }
  3607. if err == nil {
  3608. if tempv, exists := c.Get("jwt_username"); exists {
  3609. tempCommon["jwt_username"] = tempv.(string)
  3610. }
  3611. for _, paramvalue := range tempval {
  3612. if _, ok := paramvalue["resultname"]; !ok {
  3613. paramvalue["resultname"] = paramvalue["name"]
  3614. }
  3615. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3616. if err != nil {
  3617. logging.Error("ExecDataParam error:", err)
  3618. }
  3619. }
  3620. if err == nil {
  3621. vmsg := ""
  3622. for _, item := range tempval {
  3623. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3624. for _, childrenList := range list.([]interface{}) {
  3625. for k, children := range childrenList.(map[string]interface{}) {
  3626. if k != "children" {
  3627. continue
  3628. }
  3629. for _, v := range children.([]map[string]interface{}) {
  3630. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3631. if k1 == "list" {
  3632. for _, v2 := range v1.([]map[string]interface{}) {
  3633. if v2["vmsg"].(string) != "1" {
  3634. if len(vmsg) == 0 {
  3635. vmsg = v2["vmsg"].(string)
  3636. } else {
  3637. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3638. }
  3639. }
  3640. }
  3641. }
  3642. }
  3643. }
  3644. }
  3645. }
  3646. }
  3647. }
  3648. if len(vmsg) > 0 {
  3649. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3650. } else {
  3651. appG.Response(http.StatusOK, e.SUCCESS, true)
  3652. }
  3653. } else {
  3654. msg := geterrmsg(err.Error())
  3655. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3656. }
  3657. }
  3658. }
  3659. if err != nil {
  3660. msg := geterrmsg(err.Error())
  3661. appG.Response(http.StatusOK, e.ERROR, msg)
  3662. }
  3663. }
  3664. 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) {
  3665. sqlname := fasion["name"].(string)
  3666. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3667. if v, ok := fasion["type"]; ok {
  3668. sqltype = v.(string)
  3669. }
  3670. sql := ""
  3671. p := ""
  3672. s_params := make([]interface{}, 0)
  3673. if sqltype != "" {
  3674. sql, p = restful.GetSqlByName(sqlname, tx)
  3675. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3676. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3677. paramslist := strings.Split(p, ",")
  3678. if len(paramslist) > 0 && p != "" {
  3679. for _, value := range paramslist {
  3680. ss := ""
  3681. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3682. ids, err := setting.SnowIds.NextId()
  3683. if err != nil {
  3684. ids = time.Now().UnixNano()
  3685. logging.Info("create SnowIds err", err)
  3686. }
  3687. s_params = append(s_params, ids)
  3688. } else {
  3689. if ss == "" && CommonParamMap != nil {
  3690. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3691. ss = valuestring
  3692. tempstrb := strings.IndexAny(valuestring, "@")
  3693. tempstre := strings.IndexAny(valuestring, ".")
  3694. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3695. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3696. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3697. }
  3698. } else {
  3699. ss = ""
  3700. }
  3701. }
  3702. }
  3703. if ss == "" && ParentParamMap != nil {
  3704. ss = getParamValue_(v, value, ParentParamMap)
  3705. }
  3706. if ss == "" && sameParamMap != nil {
  3707. ss = getParamValue(v, value, sameParamMap)
  3708. }
  3709. if ss == "" && ParamMap != nil {
  3710. ss = getParamValue(v, value, ParamMap)
  3711. }
  3712. s_params = append(s_params, ss)
  3713. }
  3714. }
  3715. }
  3716. }
  3717. }
  3718. if sql == "" {
  3719. sqltype = ""
  3720. }
  3721. if sql != "" {
  3722. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3723. if err != nil {
  3724. return nil, err
  3725. }
  3726. // fmt.Println(tempValParam)
  3727. return tempValParam.(map[string]interface{}), nil
  3728. } else {
  3729. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3730. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3731. if err != nil {
  3732. return nil, err
  3733. }
  3734. return nil, err
  3735. }
  3736. }
  3737. return nil, nil
  3738. }
  3739. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3740. var err error
  3741. subarray, ok := fasion["children"]
  3742. if ok {
  3743. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3744. tempVal_arrary := make([]map[string]interface{}, 0)
  3745. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3746. tempVal_ := make(map[string]interface{})
  3747. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3748. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3749. } else {
  3750. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3751. }
  3752. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3753. if err != nil {
  3754. return err
  3755. }
  3756. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3757. }
  3758. v.(map[string]interface{})["children"] = tempVal_arrary
  3759. }
  3760. }
  3761. return nil
  3762. }
  3763. func FpdImportExcel(c *gin.Context) {
  3764. appG := app.Gin{C: c}
  3765. inputdata := ""
  3766. c.Request.ParseForm()
  3767. params := c.Request.Form
  3768. file, _, err := c.Request.FormFile("file")
  3769. if err != nil {
  3770. appG.Response(http.StatusOK, e.ERROR, err)
  3771. return
  3772. }
  3773. sqlnamestrs := params.Get("name")
  3774. sheetname := params.Get("sheetname")
  3775. pastureid := params.Get("pastureid")
  3776. // importParams := params.Get("importParams")
  3777. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3778. // 必输项参数 (字符串格式 "field1,field2,field3")
  3779. requiredParams := params.Get("requiredParams")
  3780. // 日期参数
  3781. dateParams := params.Get("dateParams")
  3782. // 数字参数
  3783. numParams := params.Get("numParams")
  3784. //将字符串分割开
  3785. dateParamslist := strings.Split(dateParams, ",")
  3786. requiredParamslist := strings.Split(requiredParams, ",")
  3787. numParamslist := strings.Split(numParams, ",")
  3788. queryData := make([]interface{}, 0)
  3789. sqlslist := strings.Split(sqlnamestrs, ",")
  3790. xlsx1, err := excelize.OpenReader(file)
  3791. if err != nil {
  3792. fmt.Println(err)
  3793. return
  3794. }
  3795. ok := 0
  3796. error := 0
  3797. isdone := true
  3798. tx := restful.Engine.NewSession()
  3799. defer tx.Close()
  3800. 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
  3801. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3802. if err != nil {
  3803. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3804. return
  3805. }
  3806. rows := xlsx1.GetRows(sheetname)
  3807. // 限制10000条,多余的截取掉
  3808. if len(rows) > 10000 {
  3809. rows = rows[:10000]
  3810. }
  3811. dataList := make(map[string][]*upFpdetail, 0)
  3812. for i, row := range rows {
  3813. if i > 0 {
  3814. entry := make(map[string]interface{})
  3815. outentry := make(map[string]interface{})
  3816. for j, colCell := range rows[0] {
  3817. for k, colCell1 := range row {
  3818. if j == k {
  3819. outentry[colCell] = colCell1
  3820. entry[colCell] = colCell1
  3821. }
  3822. }
  3823. }
  3824. inputdata = ""
  3825. a := ""
  3826. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3827. //校验日期格式
  3828. for _, v := range dateParamslist {
  3829. if v == "" {
  3830. continue
  3831. }
  3832. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3833. dtime, err := TransfTime(d.(string))
  3834. if err != nil {
  3835. a = strings.Trim(v, " ")
  3836. break
  3837. }
  3838. outentry[strings.Trim(v, " ")] = dtime
  3839. }
  3840. }
  3841. if a != "" {
  3842. outentry["error_msg"] = a + " 格式错误"
  3843. error++
  3844. queryData = append(queryData, outentry)
  3845. continue
  3846. }
  3847. a = ""
  3848. //校验必填格式
  3849. for _, v := range requiredParamslist {
  3850. if v == "" {
  3851. continue
  3852. }
  3853. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3854. a = strings.Trim(v, " ")
  3855. break
  3856. }
  3857. }
  3858. if a != "" {
  3859. outentry["error_msg"] = a + " 未填或格式错误"
  3860. error++
  3861. queryData = append(queryData, outentry)
  3862. continue
  3863. }
  3864. a = ""
  3865. //校验数字格式
  3866. for _, v := range numParamslist {
  3867. if v == "" {
  3868. continue
  3869. }
  3870. d, ok := outentry[strings.Trim(v, " ")]
  3871. if !ok || d == "" {
  3872. outentry[strings.Trim(v, " ")] = 0
  3873. } else {
  3874. var fl float64
  3875. switch d.(type) {
  3876. case string:
  3877. fl, err = strconv.ParseFloat(d.(string), 64)
  3878. }
  3879. if err != nil || fl < 0 {
  3880. a = strings.Trim(v, " ")
  3881. break
  3882. }
  3883. }
  3884. }
  3885. if a != "" {
  3886. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3887. error++
  3888. queryData = append(queryData, outentry)
  3889. continue
  3890. }
  3891. errExist := false
  3892. for _, sqlnamestr := range sqlslist {
  3893. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3894. paramslist := strings.Split(paramslists, ",")
  3895. if len(paramslist) > 0 {
  3896. s_params := make([]interface{}, 0)
  3897. for _, value := range paramslist {
  3898. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3899. if tempv, exists := c.Get("jwt_username"); exists {
  3900. s_params = append(s_params, tempv.(string))
  3901. } else {
  3902. s_params = append(s_params, "")
  3903. }
  3904. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3905. s_params = append(s_params, pastureid)
  3906. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3907. ids, err := setting.SnowIds.NextId()
  3908. if err != nil {
  3909. ids = time.Now().UnixNano()
  3910. logging.Info("create SnowIds err", err)
  3911. }
  3912. s_params = append(s_params, ids)
  3913. } else {
  3914. if outentry[strings.Trim(value, " ")] == nil {
  3915. s_params = append(s_params, "")
  3916. } else {
  3917. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3918. }
  3919. }
  3920. }
  3921. outentry["input"] = inputdata
  3922. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3923. if err != nil {
  3924. errExist = true
  3925. // if tx != nil {
  3926. // tx.Rollback()
  3927. // }
  3928. // if tx != nil {
  3929. // tx.Close()
  3930. // }
  3931. msg := geterrmsg(err.Error())
  3932. outentry["error_msg"] = msg
  3933. error++
  3934. queryData = append(queryData, outentry)
  3935. isdone = true
  3936. break
  3937. } else {
  3938. if len(returnmsgmap1) > 0 {
  3939. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3940. // if tx != nil {
  3941. // tx.Rollback()
  3942. // }
  3943. // if tx != nil {
  3944. // tx.Close()
  3945. // }
  3946. msg := geterrmsg(va.(string))
  3947. outentry["error_msg"] = msg
  3948. error++
  3949. queryData = append(queryData, outentry)
  3950. isdone = true
  3951. break
  3952. }
  3953. }
  3954. isdone = false
  3955. }
  3956. }
  3957. }
  3958. if !errExist {
  3959. dataexcel := make(map[string]interface{}, 0)
  3960. if _, ok := outentry["栏舍名称"]; ok {
  3961. dataexcel["barname"] = outentry["栏舍名称"]
  3962. }
  3963. if _, ok := outentry["实际牛头数"]; ok {
  3964. dataexcel["ccount"] = outentry["实际牛头数"]
  3965. }
  3966. if _, ok := outentry["系数(%)"]; ok {
  3967. dataexcel["ratio"] = outentry["系数(%)"]
  3968. }
  3969. if _, ok := outentry["配方模板"]; ok {
  3970. dataexcel["ftname"] = outentry["配方模板"]
  3971. }
  3972. if _, ok := outentry["补料配方"]; ok {
  3973. dataexcel["ptsfname"] = outentry["补料配方"]
  3974. }
  3975. if _, ok := outentry["第一班比例(%)"]; ok {
  3976. dataexcel["1"] = outentry["第一班比例(%)"]
  3977. }
  3978. if _, ok := outentry["第二班比例(%)"]; ok {
  3979. dataexcel["2"] = outentry["第二班比例(%)"]
  3980. }
  3981. if _, ok := outentry["第三班比例(%)"]; ok {
  3982. dataexcel["3"] = outentry["第三班比例(%)"]
  3983. }
  3984. if _, ok := outentry["第四班比例(%)"]; ok {
  3985. dataexcel["4"] = outentry["第四班比例(%)"]
  3986. }
  3987. if _, ok := outentry["第五班比例(%)"]; ok {
  3988. dataexcel["5"] = outentry["第五班比例(%)"]
  3989. }
  3990. if _, ok := outentry["第六班比例(%)"]; ok {
  3991. dataexcel["6"] = outentry["第六班比例(%)"]
  3992. }
  3993. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3994. if err != nil {
  3995. logs.Error(err)
  3996. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3997. return
  3998. }
  3999. if !existbar {
  4000. continue
  4001. }
  4002. _, err = tx.SQL(` update feedp fp set barname = (select bname from bar where bname = ? and pastureid = ? ) where barid = (select id from bar where bname = ? and pastureid = ? )`, dataexcel["barname"], pastureid, dataexcel["barname"], pastureid).Execute()
  4003. if err != nil {
  4004. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4005. return
  4006. }
  4007. _, err = tx.SQL(` update fpdetail fp set barname = (select bname from bar where bname = ? and pastureid = ? ) where barid = (select id from bar where bname = ? and pastureid = ? )`, dataexcel["barname"], pastureid, dataexcel["barname"], pastureid).Execute()
  4008. if err != nil {
  4009. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4010. return
  4011. }
  4012. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4013. if err != nil {
  4014. logs.Error(err)
  4015. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4016. return
  4017. }
  4018. if !existft {
  4019. continue
  4020. }
  4021. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4022. if err != nil {
  4023. logs.Error(err)
  4024. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4025. return
  4026. }
  4027. if !ftexist {
  4028. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4029. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4030. if err != nil {
  4031. logs.Error(err)
  4032. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4033. return
  4034. }
  4035. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4036. if err != nil {
  4037. logs.Error(err)
  4038. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4039. return
  4040. }
  4041. }
  4042. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4043. if err != nil {
  4044. logs.Error(err)
  4045. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4046. return
  4047. }
  4048. if !exist {
  4049. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4050. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4051. if err != nil {
  4052. logs.Error(err)
  4053. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4054. return
  4055. }
  4056. }
  4057. var feedpargs []interface{}
  4058. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4059. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4060. if _, ok := dataexcel["ftname"]; ok {
  4061. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4062. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4063. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4064. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4065. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4066. } else {
  4067. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4068. }
  4069. if _, ok := dataexcel["ptsfname"]; ok {
  4070. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4071. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4072. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4073. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4074. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4075. } else {
  4076. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4077. }
  4078. upFeedpSql += " where barname = ? and pastureid = ? "
  4079. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4080. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4081. if err != nil {
  4082. logs.Error(err)
  4083. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4084. return
  4085. }
  4086. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4087. if err != nil {
  4088. logs.Error(err)
  4089. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4090. return
  4091. }
  4092. if !exist1 {
  4093. _, 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) `,
  4094. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4095. if err != nil {
  4096. logs.Error(err)
  4097. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4098. return
  4099. }
  4100. }
  4101. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4102. if err != nil {
  4103. logs.Error(err)
  4104. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4105. return
  4106. }
  4107. if !exist2 {
  4108. _, 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) `,
  4109. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4110. if err != nil {
  4111. logs.Error(err)
  4112. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4113. return
  4114. }
  4115. }
  4116. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4117. if err != nil {
  4118. logs.Error(err)
  4119. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4120. return
  4121. }
  4122. if !exist3 {
  4123. _, 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) `,
  4124. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4125. if err != nil {
  4126. logs.Error(err)
  4127. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4128. return
  4129. }
  4130. }
  4131. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4132. if err != nil {
  4133. logs.Error(err)
  4134. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4135. return
  4136. }
  4137. if !exist4 {
  4138. _, 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) `,
  4139. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4140. if err != nil {
  4141. logs.Error(err)
  4142. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4143. return
  4144. }
  4145. }
  4146. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4147. if err != nil {
  4148. logs.Error(err)
  4149. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4150. return
  4151. }
  4152. if !exist5 {
  4153. _, 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) `,
  4154. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4155. if err != nil {
  4156. logs.Error(err)
  4157. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4158. return
  4159. }
  4160. }
  4161. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4162. if err != nil {
  4163. logs.Error(err)
  4164. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4165. return
  4166. }
  4167. if !exist6 {
  4168. _, 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) `,
  4169. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4170. if err != nil {
  4171. logs.Error(err)
  4172. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4173. return
  4174. }
  4175. }
  4176. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4177. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4178. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4179. and pastureid = ? and times = ?`
  4180. var fpdargs1 []interface{}
  4181. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4182. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4183. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4184. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4185. if err != nil {
  4186. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4187. return
  4188. }
  4189. var fpdargs2 []interface{}
  4190. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4191. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4192. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4193. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4194. if err != nil {
  4195. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4196. return
  4197. }
  4198. var fpdargs3 []interface{}
  4199. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4200. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4201. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4202. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4203. if err != nil {
  4204. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4205. return
  4206. }
  4207. var fpdargs4 []interface{}
  4208. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4209. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4210. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4211. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4212. if err != nil {
  4213. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4214. return
  4215. }
  4216. var fpdargs5 []interface{}
  4217. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4218. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4219. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4220. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4221. if err != nil {
  4222. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4223. return
  4224. }
  4225. var fpdargs6 []interface{}
  4226. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4227. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4228. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4229. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4230. if err != nil {
  4231. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4232. return
  4233. }
  4234. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4235. 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()
  4236. if err != nil {
  4237. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4238. return
  4239. }
  4240. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4241. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4242. upFpdetailList := make([]*upFpdetail, 0)
  4243. for _, newfpd := range newList {
  4244. for _, oldfpd := range oldFpdList {
  4245. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4246. var oldweight, newweight float64
  4247. if oldfpd["weight"] != nil {
  4248. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4249. }
  4250. if newfpd["weight"] != nil {
  4251. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4252. }
  4253. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4254. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4255. Old: oldweight,
  4256. New: newweight,
  4257. Times: newfpd["times"].(int64),
  4258. Ptid: newfpd["ptid"].(int64),
  4259. Fweight: fweight,
  4260. Id: oldfpd["id"].(int64),
  4261. })
  4262. break
  4263. }
  4264. }
  4265. }
  4266. // fmt.Println(dataexcel["barname"])
  4267. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4268. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4269. }
  4270. }
  4271. if !isdone {
  4272. ok++
  4273. isdone = true
  4274. }
  4275. }
  4276. for barname, v := range dataList {
  4277. updateFpdetailByBar(pastureid, barname, v)
  4278. }
  4279. data := make(map[string]interface{})
  4280. data["result"] = queryData
  4281. data["success"] = ok
  4282. data["err_count"] = error
  4283. appG.Response(http.StatusOK, e.SUCCESS, data)
  4284. }
  4285. type upFpdetail struct {
  4286. Old float64
  4287. New float64
  4288. Times int64
  4289. Ptid int64
  4290. Fweight float64
  4291. Id int64
  4292. // Ptsid string
  4293. }
  4294. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  4295. tx := restful.Engine.NewSession()
  4296. defer tx.Close()
  4297. tx.Begin()
  4298. 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 `,
  4299. pastureid, barname).Query().List()
  4300. if err != nil {
  4301. logs.Error(err)
  4302. }
  4303. for _, fpd := range fpdList {
  4304. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  4305. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  4306. pastureid, fpd["id"], fpd["times"]).Query().List()
  4307. if err != nil {
  4308. tx.Rollback()
  4309. logs.Error(err)
  4310. return err
  4311. }
  4312. var lweight float64
  4313. for _, lppland := range lpplandList {
  4314. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4315. lweight += lweight1
  4316. }
  4317. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4318. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4319. if fpdweight >= ptuse && lweight == ptuse {
  4320. continue
  4321. } else {
  4322. if lweight <= fpdweight {
  4323. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  4324. if err != nil {
  4325. tx.Rollback()
  4326. logs.Error(err)
  4327. return err
  4328. }
  4329. } else {
  4330. weight := lweight - fpdweight
  4331. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  4332. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  4333. if err != nil {
  4334. tx.Rollback()
  4335. logs.Error(err)
  4336. return err
  4337. }
  4338. for _, lppland := range lpplandList {
  4339. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4340. if weight >= lpplandlweight {
  4341. weight = weight - lpplandlweight
  4342. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  4343. if err != nil {
  4344. tx.Rollback()
  4345. logs.Error(err)
  4346. return err
  4347. }
  4348. } else {
  4349. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4350. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  4351. if err != nil {
  4352. tx.Rollback()
  4353. logs.Error(err)
  4354. return err
  4355. }
  4356. weight = 0
  4357. break
  4358. }
  4359. }
  4360. }
  4361. }
  4362. }
  4363. for _, list := range dataList {
  4364. ftmap := make(map[string]interface{})
  4365. ftmap["old"] = list.Old
  4366. ftmap["new"] = list.New
  4367. ftmap["times"] = list.Times
  4368. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  4369. ftmap["ptsid"] = ""
  4370. // fmt.Println(ftmap)
  4371. // 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 ,
  4372. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  4373. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  4374. // UNION
  4375. fpdDataList, err := tx.SQL(`
  4376. 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 ,
  4377. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  4378. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  4379. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  4380. if err != nil {
  4381. tx.Rollback()
  4382. logs.Error(err)
  4383. }
  4384. for _, fpd := range fpdDataList {
  4385. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  4386. // fttype := -1
  4387. // if fpd["fttype"].(string) == "1" {
  4388. fttype := 1
  4389. // }
  4390. var fweight float64
  4391. var lweight float64
  4392. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4393. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  4394. join lpplandtl1 lppland on lpp.id = lppland.lppid
  4395. join tmr t on t.id = lpp.tmrid
  4396. where lppland.fpdid =?
  4397. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4398. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  4399. if err != nil {
  4400. tx.Rollback()
  4401. logs.Error(err)
  4402. }
  4403. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  4404. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  4405. // barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:1 id:4828050527277810688 isfill:0 pastureid:1705635208 ptid:83 ptsid:-1 times:1 tratio:48.000 weight:32.0
  4406. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4407. var w float64
  4408. var status int
  4409. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  4410. if weight >= 0 {
  4411. continue
  4412. }
  4413. w = weight
  4414. status = 0
  4415. } else {
  4416. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  4417. // continue
  4418. // }
  4419. w = weight
  4420. status = 1
  4421. }
  4422. // for _, lppland := range lpplandtl1List {
  4423. // lweight += lppland.Lweight
  4424. // }
  4425. for _, lppland := range lpplandtl1List {
  4426. lpplandInfo := new(lpplandtlInfo)
  4427. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  4428. lweight = lpplandInfo.Lweight
  4429. if status == 1 {
  4430. // if w <= lppland.Lweight {
  4431. if lppland.Maxweight <= lweight {
  4432. continue
  4433. }
  4434. if w+lweight <= lppland.Maxweight {
  4435. lppland.Lweight += w
  4436. lweight += w
  4437. fweight += w
  4438. w = 0
  4439. } else {
  4440. w = w - (lppland.Maxweight - lweight)
  4441. n := (lppland.Maxweight - lweight)
  4442. lppland.Lweight = lppland.Lweight + n
  4443. lweight += n
  4444. fweight += n
  4445. }
  4446. } else {
  4447. if lppland.Lweight == 0 {
  4448. continue
  4449. }
  4450. if w+lppland.Lweight >= 0 {
  4451. lppland.Lweight = lppland.Lweight + w
  4452. lweight = lweight + w
  4453. fweight = fweight + w
  4454. w = 0
  4455. } else {
  4456. w = w + lppland.Lweight
  4457. lweight = lweight - lppland.Lweight
  4458. fweight = fweight - lppland.Lweight
  4459. lppland.Lweight = 0
  4460. }
  4461. }
  4462. if lppland.Lweight > 0 {
  4463. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4464. if err != nil {
  4465. tx.Rollback()
  4466. logs.Error(err)
  4467. return err
  4468. }
  4469. } else {
  4470. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  4471. if err != nil {
  4472. tx.Rollback()
  4473. logs.Error(err)
  4474. return err
  4475. }
  4476. }
  4477. if w == 0 {
  4478. break
  4479. }
  4480. }
  4481. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4482. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4483. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  4484. if err != nil {
  4485. tx.Rollback()
  4486. logs.Error(err)
  4487. }
  4488. if w == 0 {
  4489. break
  4490. }
  4491. }
  4492. }
  4493. }
  4494. // for _, data := range dataList {
  4495. // fttype := -1
  4496. // if data.Ptid != -1 {
  4497. // fttype = 1
  4498. // }
  4499. // var fweight float64
  4500. // var lweight float64
  4501. // lpplandtl1List := make([]*lpplandtlInfo, 0)
  4502. // err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4503. // join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4504. // and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4505. // data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  4506. // if err != nil {
  4507. // tx.Rollback()
  4508. // logs.Error(err)
  4509. // return err
  4510. // }
  4511. // weight := data.Fweight
  4512. // // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4513. // var w float64
  4514. // var status int
  4515. // if data.New < data.Old {
  4516. // if weight >= 0 {
  4517. // continue
  4518. // }
  4519. // w = weight
  4520. // status = 0
  4521. // } else {
  4522. // // if weight-(data.New-data.Old) > 0 {
  4523. // // continue
  4524. // // }
  4525. // w = data.New - data.Old
  4526. // status = 1
  4527. // }
  4528. // for _, lppland := range lpplandtl1List {
  4529. // var lppdata lpplandtlInfo
  4530. // tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  4531. // lppland.Lppid, pastureid).GetFirst(&lppdata)
  4532. // if err != nil {
  4533. // tx.Rollback()
  4534. // logs.Error(err)
  4535. // return err
  4536. // }
  4537. // lweight = lppdata.Lweight
  4538. // if status == 1 {
  4539. // // if w <= lppland.Lweight {
  4540. // if lppland.Maxweight <= lweight {
  4541. // continue
  4542. // }
  4543. // if w+lweight <= lppland.Maxweight {
  4544. // lppland.Lweight += w
  4545. // lweight += w
  4546. // fweight += w
  4547. // w = 0
  4548. // } else {
  4549. // w = w - (lppland.Maxweight - lweight)
  4550. // n := (lppland.Maxweight - lweight)
  4551. // lppland.Lweight = lppland.Lweight + n
  4552. // lweight += n
  4553. // fweight += n
  4554. // }
  4555. // } else {
  4556. // if lppland.Lweight == 0 {
  4557. // continue
  4558. // }
  4559. // if w+lppland.Lweight >= 0 {
  4560. // lppland.Lweight = lppland.Lweight + w
  4561. // lweight = lweight + w
  4562. // fweight = fweight + w
  4563. // w = 0
  4564. // } else {
  4565. // w = w + lppland.Lweight
  4566. // lweight = lweight - lppland.Lweight
  4567. // fweight = fweight - lppland.Lweight
  4568. // lppland.Lweight = 0
  4569. // }
  4570. // }
  4571. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4572. // if err != nil {
  4573. // tx.Rollback()
  4574. // logs.Error(err)
  4575. // return err
  4576. // }
  4577. // break
  4578. // }
  4579. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4580. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4581. // WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  4582. // if err != nil {
  4583. // tx.Rollback()
  4584. // logs.Error(err)
  4585. // return err
  4586. // }
  4587. // // if w == 0 {
  4588. // // break
  4589. // // }
  4590. // // }
  4591. // }
  4592. err = tx.Commit()
  4593. if err != nil {
  4594. logs.Error(err)
  4595. tx.Rollback()
  4596. return err
  4597. }
  4598. now := time.Now()
  4599. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4600. if err != nil {
  4601. logs.Error(err)
  4602. return nil
  4603. }
  4604. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4605. if err != nil {
  4606. logs.Error(err)
  4607. return nil
  4608. }
  4609. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4610. if err != nil {
  4611. logs.Error(err)
  4612. return nil
  4613. }
  4614. for _, newLpplandtl1 := range newLpplandtl1List {
  4615. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4616. background,cowcount,ccountradio,lweighthis,createdate)
  4617. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4618. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  4619. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  4620. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  4621. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  4622. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  4623. if err != nil {
  4624. logs.Error(err)
  4625. // appG.Response(http.StatusOK, e.ERROR, false)
  4626. return err
  4627. }
  4628. }
  4629. for _, newFpd := range newFpdDataList {
  4630. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  4631. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  4632. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  4633. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  4634. if err != nil {
  4635. logs.Error(err)
  4636. // appG.Response(http.StatusOK, e.ERROR, false)
  4637. return err
  4638. }
  4639. }
  4640. for _, newFeedp := range newFeedpList {
  4641. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  4642. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  4643. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4644. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  4645. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  4646. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  4647. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  4648. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  4649. if err != nil {
  4650. logs.Error(err)
  4651. // appG.Response(http.StatusOK, e.ERROR, false)
  4652. return err
  4653. }
  4654. }
  4655. return nil
  4656. }
  4657. func DeleteFTdetail(c *gin.Context) {
  4658. appG := app.Gin{C: c}
  4659. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4660. fsion := gofasion.NewFasion(string(dataByte))
  4661. parammaps := fsion.Get("parammaps")
  4662. pastureid := parammaps.Get("pastureid").ValueStr()
  4663. ftid := parammaps.Get("ftid").ValueStr()
  4664. tx := restful.Engine.NewSession()
  4665. defer tx.Close()
  4666. tx.Begin()
  4667. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  4668. if err != nil {
  4669. tx.Rollback()
  4670. logs.Error(err)
  4671. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4672. return
  4673. }
  4674. if parammaps.Get("type").ValueStr() == "1" {
  4675. _, err := tx.SQL(`UPDATE feedp fp
  4676. set
  4677. fp.ftweight= IFNULL(IF(
  4678. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4679. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4680. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4681. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4682. ),0),fp.feedweight = IFNULL(IF(
  4683. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4684. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4685. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4686. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4687. ),0) +ifnull(fp.supplyweight,0)
  4688. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4689. if err != nil {
  4690. tx.Rollback()
  4691. logs.Error(err)
  4692. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4693. return
  4694. }
  4695. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  4696. _, err = tx.SQL(`
  4697. UPDATE fpdetail fpd
  4698. INNER JOIN feedp fp
  4699. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4700. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4701. ptuse= 0
  4702. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4703. if err != nil {
  4704. tx.Rollback()
  4705. logs.Error(err)
  4706. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4707. return
  4708. }
  4709. } else {
  4710. _, err := tx.SQL(`UPDATE feedp fp
  4711. SET
  4712. fp.supplyweight= IFNULL(IF(
  4713. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4714. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4715. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4716. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4717. ),0),fp.feedweight = IFNULL(IF(
  4718. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4719. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4720. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4721. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4722. ),0) + ifnull(fp.supplyweight,0)
  4723. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4724. if err != nil {
  4725. tx.Rollback()
  4726. logs.Error(err)
  4727. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4728. return
  4729. }
  4730. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4731. _, err = tx.SQL(`
  4732. UPDATE fpdetail fpd
  4733. INNER JOIN feedp fp
  4734. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4735. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4736. ptsrate = 0
  4737. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4738. if err != nil {
  4739. tx.Rollback()
  4740. logs.Error(err)
  4741. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4742. return
  4743. }
  4744. }
  4745. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  4746. if err != nil {
  4747. tx.Rollback()
  4748. logs.Error(err)
  4749. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4750. return
  4751. }
  4752. err = tx.Commit()
  4753. if err != nil {
  4754. tx.Rollback()
  4755. logs.Error(err)
  4756. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4757. return
  4758. }
  4759. appG.Response(http.StatusOK, e.SUCCESS, true)
  4760. }
  4761. func DeleteSpillageAll(c *gin.Context) {
  4762. appG := app.Gin{C: c}
  4763. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4764. fsion := gofasion.NewFasion(string(dataByte))
  4765. parammaps := fsion.Get("parammaps")
  4766. pastureid := parammaps.Get("pastureid").ValueStr()
  4767. times := parammaps.Get("times").ValueStr()
  4768. barid := parammaps.Get("barid").ValueStr()
  4769. tx := restful.Engine.NewSession()
  4770. defer tx.Close()
  4771. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  4772. if err != nil {
  4773. logs.Error(err)
  4774. appG.Response(http.StatusOK, e.ERROR, false)
  4775. return
  4776. }
  4777. now := time.Now()
  4778. for _, item := range lpplandtl1List {
  4779. go func(item map[string]interface{}) {
  4780. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4781. background,cowcount,ccountradio,lweighthis,createdate)
  4782. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4783. item["pastureid"], item["lppid"], item["barid"],
  4784. item["barname"], item["fpdid"], item["fttype"],
  4785. item["lweight"], item["sort"], item["tmrid"],
  4786. item["tmrname"], item["background"], item["cowcount"],
  4787. item["ccountradio"], item["lweighthis"], now).Execute()
  4788. if err != nil {
  4789. logs.Error(err)
  4790. appG.Response(http.StatusOK, e.ERROR, false)
  4791. return
  4792. }
  4793. }(item)
  4794. }
  4795. tx.Begin()
  4796. _, 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()
  4797. if err != nil {
  4798. tx.Rollback()
  4799. logs.Error(err)
  4800. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4801. return
  4802. }
  4803. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4804. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  4805. if err != nil {
  4806. tx.Rollback()
  4807. logs.Error(err)
  4808. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4809. return
  4810. }
  4811. err = tx.Commit()
  4812. if err != nil {
  4813. tx.Rollback()
  4814. logs.Error(err)
  4815. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4816. return
  4817. }
  4818. appG.Response(http.StatusOK, e.SUCCESS, true)
  4819. }
  4820. func GetTMRListEnableTypeAll(c *gin.Context) {
  4821. appG := app.Gin{C: c}
  4822. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4823. fsion := gofasion.NewFasion(string(dataByte))
  4824. parammaps := fsion.Get("parammaps")
  4825. pastureid := parammaps.Get("pastureid").ValueStr()
  4826. tx := restful.Engine.NewSession()
  4827. defer tx.Close()
  4828. dataList, err := tx.SQL(`SELECT
  4829. eqcode,
  4830. tname,
  4831. datacaptureno,
  4832. trim(tclassid) tclassid,
  4833. concat(tname,' / ',eqcode) tmrmix,
  4834. d.label tclassname,
  4835. maxstirfeed,
  4836. remark,
  4837. tmr.enable,
  4838. TRIM(tmr.id) id,
  4839. TRIM(tmr.pastureid)pastureid
  4840. FROM
  4841. tmr
  4842. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  4843. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  4844. ORDER BY id DESC`, pastureid).Query().List()
  4845. if err != nil {
  4846. logs.Error(err)
  4847. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4848. return
  4849. }
  4850. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  4851. if err != nil {
  4852. logs.Error(err)
  4853. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4854. return
  4855. }
  4856. var carNum int64
  4857. for _, sysopt := range sysoptData {
  4858. if sysopt["inforvalue"] == nil {
  4859. carNum = 1
  4860. } else {
  4861. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  4862. }
  4863. }
  4864. id := 200
  4865. n := 0
  4866. for i := carNum; i > 0; i-- {
  4867. id++
  4868. n++
  4869. data := make(map[string]interface{}, 0)
  4870. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  4871. data["tname"] = fmt.Sprintf("任意车%d", n)
  4872. data["datacaptureno"] = -2
  4873. data["tclassid"] = -2
  4874. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  4875. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  4876. data["maxstirfeed"] = 100000
  4877. data["remark"] = fmt.Sprintf("任意车%d", n)
  4878. data["enable"] = 1
  4879. data["id"] = fmt.Sprintf("%d", id)
  4880. data["pastureid"] = pastureid
  4881. dataList = append(dataList, data)
  4882. }
  4883. // UNION ALL
  4884. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  4885. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4886. }
  4887. func GetFeedpHistory(c *gin.Context) {
  4888. appG := app.Gin{C: c}
  4889. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4890. fsion := gofasion.NewFasion(string(dataByte))
  4891. // parammaps := fsion.Get("parammaps")
  4892. bar := fsion.Get("barname").ValueStr()
  4893. startDate := fsion.Get("startDate").ValueStr()
  4894. endDate := fsion.Get("endDate").ValueStr()
  4895. tx := restful.Engine.NewSession()
  4896. defer tx.Close()
  4897. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4898. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  4899. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  4900. if err != nil {
  4901. logs.Error(err)
  4902. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4903. return
  4904. }
  4905. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  4906. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  4907. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  4908. if err != nil {
  4909. logs.Error(err)
  4910. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4911. return
  4912. }
  4913. for _, feedp := range feedpList {
  4914. // LastftList, err := tx.SQL(` select tname ,id
  4915. // from feedtemplethistory where id = ?
  4916. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  4917. // if err != nil {
  4918. // logs.Error(err)
  4919. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4920. // return
  4921. // }
  4922. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4923. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  4924. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  4925. if err != nil {
  4926. logs.Error(err)
  4927. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4928. return
  4929. }
  4930. var ftname interface{}
  4931. ftnamestatus := 0
  4932. ftname = feedp["ftname"]
  4933. var lastftid int64
  4934. if len(nextfeedpList) > 0 {
  4935. for _, ft := range nextfeedpList {
  4936. if ft["ftname"].(string) != feedp["ftname"].(string) {
  4937. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  4938. lastftid = ft["ftid"].(int64)
  4939. ftnamestatus = 1
  4940. break
  4941. }
  4942. }
  4943. }
  4944. for i, fpd := range fpdList {
  4945. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4946. fpd["weightstatus"] = 0
  4947. fpd["tratiostatus"] = 0
  4948. fpd["ftnamestatus"] = ftnamestatus
  4949. for k, fpd2 := range fpdList {
  4950. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4951. if fpd["weight"].(string) != fpd2["weight"].(string) {
  4952. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4953. fpd["weightstatus"] = 1
  4954. }
  4955. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  4956. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  4957. fpd["tratiostatus"] = 1
  4958. }
  4959. break
  4960. }
  4961. }
  4962. fpd["barid"] = feedp["barid"]
  4963. fpd["barname"] = feedp["barname"]
  4964. fpd["ccount"] = feedp["ccount"]
  4965. fpd["ratio"] = feedp["ratio"]
  4966. fpd["ccountratio"] = feedp["ccountratio"]
  4967. fpd["ftid"] = feedp["ftid"]
  4968. fpd["ftname"] = ftname
  4969. fpd["ccountstatus"] = 0
  4970. fpd["ccountratiostatus"] = 0
  4971. fpd["ratiostatus"] = 0
  4972. fpd["ftnamestatus"] = 0
  4973. fpd["lastftid"] = lastftid
  4974. for _, next := range nextfeedpList {
  4975. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  4976. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  4977. fpd["ccountstatus"] = 1
  4978. }
  4979. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  4980. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  4981. fpd["ccountratiostatus"] = 1
  4982. }
  4983. if next["ratio"].(string) != fpd["ratio"].(string) {
  4984. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  4985. fpd["ratiostatus"] = 1
  4986. }
  4987. // if next["ftname"].(string) != fpd["ftname"].(string) {
  4988. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  4989. // fpd["ftnamestatus"] = 1
  4990. // }
  4991. }
  4992. }
  4993. }
  4994. }
  4995. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  4996. }
  4997. // func GetLpplandtl1History(c *gin.Context) {
  4998. // appG := app.Gin{C: c}
  4999. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5000. // fsion := gofasion.NewFasion(string(dataByte))
  5001. // // parammaps := fsion.Get("parammaps")
  5002. // barid := fsion.Get("barid").ValueStr()
  5003. // startDate := fsion.Get("startDate").ValueStr()
  5004. // endDate := fsion.Get("endDate").ValueStr()
  5005. // tx := restful.Engine.NewSession()
  5006. // defer tx.Close()
  5007. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5008. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5009. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5010. // // if err != nil {
  5011. // // logs.Error(err)
  5012. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5013. // // return
  5014. // // }
  5015. // // for _, feedp := range feedpList {
  5016. // // fmt.Println(feedp)
  5017. // // for i, fpd := range fpdList {
  5018. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5019. // // for k, fpd2 := range fpdList {
  5020. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5021. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5022. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5023. // // }
  5024. // // break
  5025. // // }
  5026. // // }
  5027. // // fpd["barid"] = feedp["barid"]
  5028. // // fpd["barname"] = feedp["barname"]
  5029. // // fpd["ccount"] = feedp["ccount"]
  5030. // // fpd["ratio"] = feedp["ratio"]
  5031. // // fpd["ccountratio"] = feedp["ccountratio"]
  5032. // // fpd["ftid"] = feedp["ftid"]
  5033. // // fpd["ftname"] = feedp["ftname"]
  5034. // // }
  5035. // // }
  5036. // // }
  5037. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5038. // }
  5039. func GetRemind(c *gin.Context) {
  5040. appG := app.Gin{C: c}
  5041. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5042. fsion := gofasion.NewFasion(string(dataByte))
  5043. parammaps := fsion.Get("parammaps")
  5044. pastureid := parammaps.Get("pastureid").ValueStr()
  5045. tx := restful.Engine.NewSession()
  5046. defer tx.Close()
  5047. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5048. if err != nil {
  5049. logs.Error(err)
  5050. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5051. return
  5052. }
  5053. // pastureid = "3"
  5054. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5055. if err != nil {
  5056. logs.Error(err)
  5057. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5058. return
  5059. }
  5060. defer resp.Body.Close()
  5061. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5062. buf.ReadFrom(resp.Body)
  5063. fmt.Println(string(buf.Bytes()))
  5064. respMap := make(map[string]interface{}, 0)
  5065. err = json.Unmarshal(buf.Bytes(), &respMap)
  5066. if err != nil {
  5067. logs.Error(err)
  5068. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5069. return
  5070. }
  5071. for _, data := range dataList {
  5072. r := make(map[string]interface{}, 0)
  5073. r["sys_name"] = ""
  5074. r["service_id"] = ""
  5075. r["pasture_id"] = ""
  5076. r["type_name"] = ""
  5077. r["remind_type_id"] = ""
  5078. r["remind_type"] = ""
  5079. r["push_date"] = ""
  5080. r["push_time"] = ""
  5081. r["interval_time"] = ""
  5082. r["push_limit"] = ""
  5083. r["template_id"] = ""
  5084. r["roles_id"] = ""
  5085. r["users_id"] = ""
  5086. r["date_type"] = ""
  5087. r["cycle_type"] = ""
  5088. data["data"] = r
  5089. for _, resp := range respMap["data"].([]interface{}) {
  5090. resp1 := resp.(map[string]interface{})
  5091. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5092. if resp1["push_time"] == nil {
  5093. resp1["push_time"] = ""
  5094. }
  5095. data["data"] = resp1
  5096. break
  5097. }
  5098. }
  5099. }
  5100. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5101. }
  5102. type NoticeMsgtype struct {
  5103. SysName string `json:"sys_name"`
  5104. PastureId int64 `json:"pasture_id"`
  5105. ServiceId int64 `json:"service_id"`
  5106. TypeName string `json:"type_name"`
  5107. RemindType int64 `json:"remind_type"`
  5108. PushDate int64 `json:"push_date"`
  5109. PushTime string `json:"push_time"`
  5110. IntervalTime int64 `json:"interval_time"`
  5111. PushLimit int64 `json:"push_limit"`
  5112. TemplateId string `json:"template_id"`
  5113. UsersId string `json:"users_id"`
  5114. DateType int64 `json:"date_type"`
  5115. CycleType int64 `json:"cycle_type"`
  5116. DelayTime int64 `json:"delay_time"`
  5117. Status int64 `json:"status"`
  5118. }
  5119. func UpdateRemind(c *gin.Context) {
  5120. appG := app.Gin{C: c}
  5121. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5122. parammaps := gofasion.NewFasion(string(dataByte))
  5123. // parammaps := fsion.Get("parammaps")
  5124. // user := parammaps.Get("user").ValueStr()
  5125. id := parammaps.Get("id").ValueInt64()
  5126. noticeMsgtype := new(NoticeMsgtype)
  5127. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  5128. noticeMsgtype.ServiceId = id
  5129. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  5130. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  5131. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  5132. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  5133. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  5134. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  5135. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  5136. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  5137. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  5138. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  5139. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  5140. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  5141. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  5142. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  5143. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  5144. //TODO
  5145. noticeMsgtype.SysName = "tmrWatch"
  5146. userList := parammaps.Get("user").Array()
  5147. var userstr []string
  5148. for _, user := range userList {
  5149. userstr = append(userstr, user.ValueStr())
  5150. }
  5151. tx := restful.Engine.NewSession()
  5152. defer tx.Close()
  5153. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  5154. if err != nil {
  5155. logs.Error(err)
  5156. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5157. return
  5158. }
  5159. // var jsonStr = []byte(noticeMsgtype
  5160. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  5161. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  5162. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  5163. req.Header.Set("Content-Type", "application/json")
  5164. client := &http.Client{}
  5165. resp, err := client.Do(req)
  5166. if err != nil {
  5167. logs.Error(err)
  5168. }
  5169. defer resp.Body.Close()
  5170. body, _ := ioutil.ReadAll(resp.Body)
  5171. fmt.Println("response Body:", string(body))
  5172. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  5173. if err != nil {
  5174. logs.Error(err)
  5175. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5176. return
  5177. }
  5178. defer getresp.Body.Close()
  5179. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5180. buf.ReadFrom(getresp.Body)
  5181. // fmt.Println(string(buf.Bytes()))
  5182. respMap := make(map[string]interface{}, 0)
  5183. err = json.Unmarshal(buf.Bytes(), &respMap)
  5184. if err != nil {
  5185. logs.Error(err)
  5186. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5187. return
  5188. }
  5189. for _, resp := range respMap["data"].([]interface{}) {
  5190. resp1 := resp.(map[string]interface{})
  5191. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  5192. if err != nil {
  5193. logs.Error(err)
  5194. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5195. return
  5196. }
  5197. }
  5198. appG.Response(http.StatusOK, e.SUCCESS, true)
  5199. }
  5200. func GetSpillageallHistory(c *gin.Context) {
  5201. appG := app.Gin{C: c}
  5202. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5203. parammaps := gofasion.NewFasion(string(dataByte))
  5204. barname := parammaps.Get("barname").ValueStr()
  5205. pastureid := parammaps.Get("pastureid").ValueStr()
  5206. startdate := parammaps.Get("startDate").ValueStr()
  5207. enddate := parammaps.Get("endDate").ValueStr()
  5208. tx := restful.Engine.NewSession()
  5209. defer tx.Close()
  5210. 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
  5211. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  5212. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  5213. if err != nil {
  5214. logs.Error(err)
  5215. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5216. return
  5217. }
  5218. respMap := make([]map[string]interface{}, 0)
  5219. data := make(map[interface{}]interface{})
  5220. for _, history := range historyList {
  5221. data[history["createdate"]] = history["createdate"]
  5222. }
  5223. createList := []string{}
  5224. for _, v := range data {
  5225. createList = append(createList, v.(string))
  5226. }
  5227. // sort.Sort()
  5228. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  5229. sort.Slice(createList, func(i, j int) bool {
  5230. return createList[i] > createList[j]
  5231. })
  5232. for _, v := range createList {
  5233. a := make(map[string]interface{})
  5234. a["createdate"] = data[v]
  5235. // createList = append(createList, v.(string))
  5236. respMap = append(respMap, a)
  5237. }
  5238. number := 0
  5239. dataMap := make([]interface{}, 0)
  5240. for k, resp := range respMap {
  5241. createdate := resp["createdate"].(string)
  5242. var nextcreatedate string
  5243. if len(respMap) > k+1 {
  5244. nextcreatedate = respMap[k+1]["createdate"].(string)
  5245. }
  5246. // dataList := make(map[string][]interface{})
  5247. // list := make(map[string]interface{})
  5248. times := make(map[interface{}]int)
  5249. for _, history := range historyList {
  5250. // List := make(map[interface{}][]interface{})
  5251. i := 0
  5252. if history["createdate"].(string) == createdate {
  5253. times[history["times"]]++
  5254. data := make(map[string]interface{})
  5255. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  5256. // exist := false
  5257. if nextcreatedate != "" {
  5258. for _, history1 := range historyList {
  5259. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  5260. history1["times"].(int64) == history["times"].(int64) {
  5261. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  5262. break
  5263. // exist = true
  5264. }
  5265. }
  5266. }
  5267. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5268. i++
  5269. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  5270. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  5271. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  5272. // resp["times"] = history["times"]
  5273. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5274. data1 := make(map[string]interface{})
  5275. data1["times"] = history["times"]
  5276. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5277. data1["createdate"] = resp["createdate"]
  5278. // fmt.Println(dataList)
  5279. dataMap = append(dataMap, data1)
  5280. }
  5281. if i > number {
  5282. number = i
  5283. }
  5284. // respMap = append(respMap, dataList)
  5285. }
  5286. // for k, data := range dataList {
  5287. // resp[k] = data
  5288. // }
  5289. // resp["data"] = dataList
  5290. }
  5291. // resp := make(map[string]interface{})
  5292. // sort.Strings(createList)
  5293. //
  5294. // for _, create := range createList {
  5295. // for _, r := range respMap {
  5296. // if create == r["createdate"].(string) {
  5297. // resp[create] = r
  5298. // break
  5299. // }
  5300. // }
  5301. // }
  5302. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  5303. var trainsList []interface{}
  5304. for i := 0; i < number; i++ {
  5305. trains := make(map[string]interface{})
  5306. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  5307. trains["prop"] = fmt.Sprintf("a%d", i+1)
  5308. trainsList = append(trainsList, trains)
  5309. }
  5310. respdata := make(map[string]interface{})
  5311. respdata["data"] = dataMap
  5312. respdata["trains"] = trainsList
  5313. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  5314. }
  5315. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  5316. appG := app.Gin{C: c}
  5317. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5318. parammaps := gofasion.NewFasion(string(dataByte))
  5319. ftid := parammaps.Get("ftid").ValueInt64()
  5320. lastftid := parammaps.Get("lastftid").ValueInt64()
  5321. pastureid := parammaps.Get("pastureid").ValueInt64()
  5322. // createdate := parammaps.Get("createdate").ValueStr()
  5323. tx := restful.Engine.NewSession()
  5324. defer tx.Close()
  5325. data := make(map[string]interface{})
  5326. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5327. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  5328. if err != nil {
  5329. logs.Error(err)
  5330. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5331. return
  5332. }
  5333. feedtemplet := make(map[string]interface{})
  5334. for _, f := range feedtempletList {
  5335. feedtemplet = f
  5336. }
  5337. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  5338. if err != nil {
  5339. logs.Error(err)
  5340. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5341. return
  5342. }
  5343. feedtemplet["fit"] = fitList
  5344. data["current"] = feedtemplet
  5345. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5346. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  5347. if err != nil {
  5348. logs.Error(err)
  5349. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5350. return
  5351. }
  5352. lastfeedtemplet := make(map[string]interface{})
  5353. for _, f := range lastfeedtempletList {
  5354. lastfeedtemplet = f
  5355. }
  5356. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  5357. if err != nil {
  5358. logs.Error(err)
  5359. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5360. return
  5361. }
  5362. lastfeedtemplet["fit"] = lastfitList
  5363. data["last"] = lastfeedtemplet
  5364. appG.Response(http.StatusOK, e.SUCCESS, data)
  5365. }
  5366. func GetFeedtempletHistory(c *gin.Context) {
  5367. appG := app.Gin{C: c}
  5368. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5369. parammaps := gofasion.NewFasion(string(dataByte))
  5370. ftid := parammaps.Get("ftid").ValueStr()
  5371. pastureid := parammaps.Get("pastureid").ValueInt64()
  5372. start := parammaps.Get("startdate").ValueStr()
  5373. end := parammaps.Get("enddate").ValueStr()
  5374. tx := restful.Engine.NewSession()
  5375. defer tx.Close()
  5376. 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 ?
  5377. and id = ? and pastureid = ? order by createdate desc `,
  5378. start, end, ftid, pastureid).Query().List()
  5379. if err != nil {
  5380. logs.Error(err)
  5381. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5382. return
  5383. }
  5384. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  5385. ftid, pastureid).Query().List()
  5386. if err != nil {
  5387. logs.Error(err)
  5388. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5389. return
  5390. }
  5391. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  5392. for i, ft := range ftList {
  5393. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  5394. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  5395. (select empname from user where id = fit.userId) empname,
  5396. 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
  5397. where fit.fitid = ?
  5398. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  5399. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  5400. if err != nil {
  5401. logs.Error(err)
  5402. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5403. return
  5404. }
  5405. ft["createdate"] = ft["createdate1"]
  5406. // data["tname"] = ft["tname"]
  5407. // data["tcode"] = ft["tcode"]
  5408. // data["tcolor"] = ft["tcolor"]
  5409. // data["fttype"] = ft["fttype"]
  5410. // data["ccname"] = ft["ccname"]
  5411. // data["source"] = ft["source"]
  5412. // data["version"] = ft["version"]
  5413. // data["remark"] = ft["remark"]
  5414. for n, ft2 := range ftList {
  5415. if i < n {
  5416. if ft["tname"].(string) != ft2["tname"].(string) {
  5417. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  5418. }
  5419. if _, ok := ft["tcode"]; ok {
  5420. if _, ok := ft2["tcode"]; ok {
  5421. if ft["tcode"].(string) != ft2["tcode"].(string) {
  5422. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  5423. }
  5424. }
  5425. }
  5426. if _, ok := ft["tcolor"]; ok {
  5427. if _, ok := ft2["tcolor"]; ok {
  5428. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  5429. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  5430. }
  5431. }
  5432. }
  5433. if _, ok := ft["fttype"]; ok {
  5434. if _, ok := ft2["fttype"]; ok {
  5435. if ft["fttype"].(string) != ft2["fttype"].(string) {
  5436. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  5437. }
  5438. }
  5439. }
  5440. if _, ok := ft["ccname"]; ok {
  5441. if _, ok := ft2["ccname"]; ok {
  5442. if ft["ccname"].(string) != ft2["ccname"].(string) {
  5443. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  5444. }
  5445. }
  5446. }
  5447. if _, ok := ft["source"]; ok {
  5448. if _, ok := ft2["source"]; ok {
  5449. if ft["source"].(string) != ft2["source"].(string) {
  5450. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  5451. }
  5452. }
  5453. }
  5454. if _, ok := ft["version"]; ok {
  5455. if _, ok := ft2["version"]; ok {
  5456. if ft["version"].(int64) != ft2["version"].(int64) {
  5457. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  5458. }
  5459. }
  5460. }
  5461. if _, ok := ft["remark"]; ok {
  5462. if _, ok := ft2["remark"]; ok {
  5463. if ft["remark"].(string) != ft2["remark"].(string) {
  5464. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  5465. }
  5466. }
  5467. }
  5468. break
  5469. }
  5470. }
  5471. dataList := make([]map[string]interface{}, 0)
  5472. if len(fithisList) > 0 {
  5473. for _, fit := range fithisList {
  5474. data := make(map[string]interface{})
  5475. data["feedgroup"] = fit["feedgroup"]
  5476. data["fname"] = fit["fname"]
  5477. data["empname"] = fit["empname"]
  5478. if fit["Eweight"] != nil {
  5479. if fit["Eweight"].(string) != fit["weight"].(string) {
  5480. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  5481. } else {
  5482. data["fweight"] = fit["Eweight"]
  5483. }
  5484. data["fweightstatus"] = 1
  5485. } else {
  5486. data["fweight"] = fit["weight"]
  5487. data["fweightstatus"] = 0
  5488. }
  5489. data["autosecond"] = fit["autosecond"]
  5490. // data["tname"] = ft["tname"]
  5491. // data["tcode"] = ft["tcode"]
  5492. // data["tcolor"] = ft["tcolor"]
  5493. // data["fttype"] = ft["fttype"]
  5494. // data["ccname"] = ft["ccname"]
  5495. // data["source"] = ft["source"]
  5496. // data["version"] = ft["version"]
  5497. // data["remark"] = ft["remark"]
  5498. // data["createdate"] = ft["createdate1"]
  5499. // ft["fit"] = data
  5500. dataList = append(dataList, data)
  5501. }
  5502. } else {
  5503. for _, fit := range ftdetailList {
  5504. data := make(map[string]interface{})
  5505. data["feedgroup"] = fit["feedgroup"]
  5506. data["fname"] = fit["fname"]
  5507. // if fit["Eweight"] != nil {
  5508. // data["weight"] = fit["Eweight"]
  5509. // } else {
  5510. data["fweight"] = fit["fweight"]
  5511. // }
  5512. data["autosecond"] = fit["autosecond"]
  5513. // ft["fit"] = data
  5514. dataList = append(dataList, data)
  5515. }
  5516. }
  5517. ft["fit"] = dataList
  5518. }
  5519. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  5520. }
  5521. func UpdateMaterialTMR(c *gin.Context) {
  5522. appG := app.Gin{C: c}
  5523. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5524. parammaps := gofasion.NewFasion(string(dataByte))
  5525. tmrid := parammaps.Get("tmrid").ValueStr()
  5526. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5527. lppid := parammaps.Get("lppid").ValueStr()
  5528. times := parammaps.Get("times").ValueStr()
  5529. pastureid := parammaps.Get("pastureid").ValueStr()
  5530. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  5531. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5532. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5533. tx := restful.Engine.NewSession()
  5534. defer tx.Close()
  5535. tx.Begin()
  5536. if tmrid != "1000" {
  5537. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5538. if err != nil {
  5539. logs.Error(err)
  5540. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5541. return
  5542. }
  5543. var maxstirfeed float64
  5544. for _, tmr := range tmrList {
  5545. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5546. }
  5547. if status == 0 {
  5548. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5549. if err != nil {
  5550. tx.Rollback()
  5551. logs.Error(err)
  5552. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5553. return
  5554. }
  5555. var lweight float64
  5556. for _, item := range lpplandtl1List {
  5557. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5558. lweight += fl
  5559. }
  5560. if lweight > maxstirfeed {
  5561. lweight = lweight - maxstirfeed
  5562. } else {
  5563. lweight = 0
  5564. }
  5565. if lweight > 0 {
  5566. lweight1 := lweight / float64(len(lpplandtl1List))
  5567. number := 0
  5568. for _, item := range lpplandtl1List {
  5569. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5570. if lweight1 >= fl {
  5571. number++
  5572. }
  5573. }
  5574. lweight := lweight / float64((len(lpplandtl1List) - number))
  5575. for _, item := range lpplandtl1List {
  5576. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5577. if lweight1 >= fl {
  5578. continue
  5579. }
  5580. if tmrtype == "1" {
  5581. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  5582. if err != nil {
  5583. tx.Rollback()
  5584. logs.Error(err)
  5585. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5586. return
  5587. }
  5588. } else if tmrtype == "2" {
  5589. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  5590. if err != nil {
  5591. tx.Rollback()
  5592. logs.Error(err)
  5593. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5594. return
  5595. }
  5596. }
  5597. if item["fttype"].(int64) == 0 {
  5598. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5599. if err != nil {
  5600. tx.Rollback()
  5601. logs.Error(err)
  5602. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5603. return
  5604. }
  5605. } else {
  5606. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5607. if err != nil {
  5608. tx.Rollback()
  5609. logs.Error(err)
  5610. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5611. return
  5612. }
  5613. }
  5614. }
  5615. } else {
  5616. for _, item := range lpplandtl1List {
  5617. // 自走式
  5618. if tmrtype == "1" {
  5619. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5620. if err != nil {
  5621. logs.Error(err)
  5622. tx.Rollback()
  5623. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5624. return
  5625. }
  5626. } else if tmrtype == "2" {
  5627. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5628. if err != nil {
  5629. logs.Error(err)
  5630. tx.Rollback()
  5631. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5632. return
  5633. }
  5634. }
  5635. }
  5636. }
  5637. } else if status == 1 {
  5638. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5639. if err != nil {
  5640. logs.Error(err)
  5641. tx.Rollback()
  5642. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5643. return
  5644. }
  5645. var lweight float64
  5646. for _, item := range lpplandtl1List {
  5647. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5648. lweight += fl
  5649. }
  5650. if lweight > maxstirfeed {
  5651. lweight = lweight - maxstirfeed
  5652. } else {
  5653. lweight = 0
  5654. }
  5655. for _, item := range lpplandtl1List {
  5656. if lweight > 0 {
  5657. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5658. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5659. if fl >= lweight {
  5660. item["lweight"] = fl - lweight
  5661. lweight = 0
  5662. if tmrtype == "1" {
  5663. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  5664. if err != nil {
  5665. logs.Error(err)
  5666. tx.Rollback()
  5667. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5668. return
  5669. }
  5670. } else if tmrtype == "2" {
  5671. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  5672. if err != nil {
  5673. logs.Error(err)
  5674. tx.Rollback()
  5675. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5676. return
  5677. }
  5678. }
  5679. if item["fttype"].(int64) == 0 {
  5680. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5681. if err != nil {
  5682. logs.Error(err)
  5683. tx.Rollback()
  5684. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5685. return
  5686. }
  5687. } else {
  5688. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5689. if err != nil {
  5690. logs.Error(err)
  5691. tx.Rollback()
  5692. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5693. return
  5694. }
  5695. }
  5696. } else {
  5697. lweight = lweight - fl
  5698. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  5699. if err != nil {
  5700. logs.Error(err)
  5701. tx.Rollback()
  5702. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5703. return
  5704. }
  5705. if item["fttype"].(int64) == 0 {
  5706. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5707. if err != nil {
  5708. logs.Error(err)
  5709. tx.Rollback()
  5710. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5711. return
  5712. }
  5713. } else {
  5714. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5715. if err != nil {
  5716. logs.Error(err)
  5717. tx.Rollback()
  5718. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5719. return
  5720. }
  5721. }
  5722. }
  5723. } else {
  5724. // 自走式
  5725. if tmrtype == "1" {
  5726. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5727. if err != nil {
  5728. logs.Error(err)
  5729. tx.Rollback()
  5730. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5731. return
  5732. }
  5733. } else if tmrtype == "2" {
  5734. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5735. if err != nil {
  5736. logs.Error(err)
  5737. tx.Rollback()
  5738. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5739. return
  5740. }
  5741. }
  5742. }
  5743. }
  5744. } else {
  5745. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  5746. if err != nil {
  5747. logs.Error(err)
  5748. tx.Rollback()
  5749. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5750. return
  5751. }
  5752. for _, item := range lpplandtl1List {
  5753. if item["fttype"].(int64) == 0 {
  5754. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5755. if err != nil {
  5756. logs.Error(err)
  5757. tx.Rollback()
  5758. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5759. return
  5760. }
  5761. } else {
  5762. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5763. if err != nil {
  5764. logs.Error(err)
  5765. tx.Rollback()
  5766. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5767. return
  5768. }
  5769. }
  5770. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  5771. if err != nil {
  5772. logs.Error(err)
  5773. tx.Rollback()
  5774. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5775. return
  5776. }
  5777. }
  5778. }
  5779. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  5780. if err != nil {
  5781. logs.Error(err)
  5782. tx.Rollback()
  5783. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5784. return
  5785. }
  5786. } else {
  5787. if status == 2 {
  5788. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  5789. if err != nil {
  5790. logs.Error(err)
  5791. tx.Rollback()
  5792. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5793. return
  5794. }
  5795. for _, item := range lpplandtl1List {
  5796. if item["fttype"].(int64) == 0 {
  5797. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5798. if err != nil {
  5799. logs.Error(err)
  5800. tx.Rollback()
  5801. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5802. return
  5803. }
  5804. } else {
  5805. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5806. if err != nil {
  5807. logs.Error(err)
  5808. tx.Rollback()
  5809. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5810. return
  5811. }
  5812. }
  5813. }
  5814. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  5815. if err != nil {
  5816. logs.Error(err)
  5817. tx.Rollback()
  5818. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5819. return
  5820. }
  5821. } else {
  5822. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  5823. if err != nil {
  5824. logs.Error(err)
  5825. tx.Rollback()
  5826. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5827. return
  5828. }
  5829. }
  5830. }
  5831. err := tx.Commit()
  5832. if err != nil {
  5833. logs.Error(err)
  5834. tx.Rollback()
  5835. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5836. return
  5837. }
  5838. appG.Response(http.StatusOK, e.SUCCESS, true)
  5839. }
  5840. func UpdateMaterialTMRDate(c *gin.Context) {
  5841. appG := app.Gin{C: c}
  5842. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5843. parammaps := gofasion.NewFasion(string(dataByte))
  5844. tmrid := parammaps.Get("tmrid").ValueStr()
  5845. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5846. lppid := parammaps.Get("lppid").ValueStr()
  5847. times := parammaps.Get("times").ValueStr()
  5848. pastureid := parammaps.Get("pastureid").ValueStr()
  5849. date := parammaps.Get("date").ValueStr()
  5850. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5851. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5852. tx := restful.Engine.NewSession()
  5853. defer tx.Close()
  5854. tx.Begin()
  5855. if tmrid != "1000" {
  5856. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5857. if err != nil {
  5858. logs.Error(err)
  5859. tx.Rollback()
  5860. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5861. return
  5862. }
  5863. var maxstirfeed float64
  5864. for _, tmr := range tmrList {
  5865. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5866. }
  5867. if status == 0 {
  5868. 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()
  5869. if err != nil {
  5870. logs.Error(err)
  5871. tx.Rollback()
  5872. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5873. return
  5874. }
  5875. var lweight float64
  5876. for _, item := range lpplandtl1List {
  5877. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5878. lweight += fl
  5879. }
  5880. if lweight > maxstirfeed {
  5881. lweight = lweight - maxstirfeed
  5882. } else {
  5883. lweight = 0
  5884. }
  5885. if lweight > 0 {
  5886. lweight1 := lweight / float64(len(lpplandtl1List))
  5887. number := 0
  5888. for _, item := range lpplandtl1List {
  5889. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5890. if lweight1 >= fl {
  5891. number++
  5892. }
  5893. }
  5894. lweight := lweight / float64((len(lpplandtl1List) - number))
  5895. for _, item := range lpplandtl1List {
  5896. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5897. if lweight1 >= fl {
  5898. continue
  5899. }
  5900. if tmrtype == "1" {
  5901. _, 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()
  5902. if err != nil {
  5903. logs.Error(err)
  5904. tx.Rollback()
  5905. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5906. return
  5907. }
  5908. } else if tmrtype == "2" {
  5909. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  5910. if err != nil {
  5911. logs.Error(err)
  5912. tx.Rollback()
  5913. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5914. return
  5915. }
  5916. }
  5917. if item["fttype"].(int64) == 0 {
  5918. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5919. if err != nil {
  5920. logs.Error(err)
  5921. tx.Rollback()
  5922. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5923. return
  5924. }
  5925. } else {
  5926. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], 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. }
  5934. }
  5935. } else {
  5936. for _, item := range lpplandtl1List {
  5937. // 自走式
  5938. if tmrtype == "1" {
  5939. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5940. if err != nil {
  5941. logs.Error(err)
  5942. tx.Rollback()
  5943. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5944. return
  5945. }
  5946. } else if tmrtype == "2" {
  5947. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5948. if err != nil {
  5949. logs.Error(err)
  5950. tx.Rollback()
  5951. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5952. return
  5953. }
  5954. }
  5955. }
  5956. }
  5957. } else if status == 1 {
  5958. 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()
  5959. if err != nil {
  5960. logs.Error(err)
  5961. tx.Rollback()
  5962. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5963. return
  5964. }
  5965. var lweight float64
  5966. for _, item := range lpplandtl1List {
  5967. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5968. lweight += fl
  5969. }
  5970. if lweight > maxstirfeed {
  5971. lweight = lweight - maxstirfeed
  5972. } else {
  5973. lweight = 0
  5974. }
  5975. for _, item := range lpplandtl1List {
  5976. if lweight > 0 {
  5977. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5978. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5979. if fl >= lweight {
  5980. item["lweight"] = fl - lweight
  5981. lweight = 0
  5982. if tmrtype == "1" {
  5983. _, 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()
  5984. if err != nil {
  5985. logs.Error(err)
  5986. tx.Rollback()
  5987. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5988. return
  5989. }
  5990. } else if tmrtype == "2" {
  5991. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  5992. if err != nil {
  5993. logs.Error(err)
  5994. tx.Rollback()
  5995. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5996. return
  5997. }
  5998. }
  5999. if item["fttype"].(int64) == 0 {
  6000. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6001. if err != nil {
  6002. logs.Error(err)
  6003. tx.Rollback()
  6004. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6005. return
  6006. }
  6007. } else {
  6008. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6009. if err != nil {
  6010. logs.Error(err)
  6011. tx.Rollback()
  6012. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6013. return
  6014. }
  6015. }
  6016. } else {
  6017. lweight = lweight - fl
  6018. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6019. if err != nil {
  6020. logs.Error(err)
  6021. tx.Rollback()
  6022. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6023. return
  6024. }
  6025. if item["fttype"].(int64) == 0 {
  6026. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6027. if err != nil {
  6028. logs.Error(err)
  6029. tx.Rollback()
  6030. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6031. return
  6032. }
  6033. } else {
  6034. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6035. if err != nil {
  6036. logs.Error(err)
  6037. tx.Rollback()
  6038. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6039. return
  6040. }
  6041. }
  6042. }
  6043. } else {
  6044. // 自走式
  6045. if tmrtype == "1" {
  6046. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6047. if err != nil {
  6048. logs.Error(err)
  6049. tx.Rollback()
  6050. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6051. return
  6052. }
  6053. } else if tmrtype == "2" {
  6054. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6055. if err != nil {
  6056. logs.Error(err)
  6057. tx.Rollback()
  6058. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6059. return
  6060. }
  6061. }
  6062. }
  6063. }
  6064. } else {
  6065. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6066. if err != nil {
  6067. logs.Error(err)
  6068. tx.Rollback()
  6069. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6070. return
  6071. }
  6072. for _, item := range lpplandtl1List {
  6073. if item["fttype"].(int64) == 0 {
  6074. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6075. if err != nil {
  6076. logs.Error(err)
  6077. tx.Rollback()
  6078. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6079. return
  6080. }
  6081. } else {
  6082. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6083. if err != nil {
  6084. logs.Error(err)
  6085. tx.Rollback()
  6086. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6087. return
  6088. }
  6089. }
  6090. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6091. if err != nil {
  6092. logs.Error(err)
  6093. tx.Rollback()
  6094. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6095. return
  6096. }
  6097. }
  6098. }
  6099. _, 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()
  6100. if err != nil {
  6101. logs.Error(err)
  6102. tx.Rollback()
  6103. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6104. return
  6105. }
  6106. } else {
  6107. if status == 2 {
  6108. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  6109. if err != nil {
  6110. logs.Error(err)
  6111. tx.Rollback()
  6112. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6113. return
  6114. }
  6115. for _, item := range lpplandtl1List {
  6116. if item["fttype"].(int64) == 0 {
  6117. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6118. if err != nil {
  6119. logs.Error(err)
  6120. tx.Rollback()
  6121. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6122. return
  6123. }
  6124. } else {
  6125. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6126. if err != nil {
  6127. logs.Error(err)
  6128. tx.Rollback()
  6129. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6130. return
  6131. }
  6132. }
  6133. }
  6134. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  6135. if err != nil {
  6136. logs.Error(err)
  6137. tx.Rollback()
  6138. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6139. return
  6140. }
  6141. } else {
  6142. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  6143. if err != nil {
  6144. logs.Error(err)
  6145. tx.Rollback()
  6146. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6147. return
  6148. }
  6149. }
  6150. }
  6151. err := tx.Commit()
  6152. if err != nil {
  6153. logs.Error(err)
  6154. tx.Rollback()
  6155. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6156. return
  6157. }
  6158. appG.Response(http.StatusOK, e.SUCCESS, true)
  6159. }
  6160. func Decimal(value float64) float64 {
  6161. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  6162. return value
  6163. }
  6164. func UpdateDailyData(c *gin.Context) {
  6165. appG := app.Gin{C: c}
  6166. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6167. parammaps := gofasion.NewFasion(string(dataByte))
  6168. pid := parammaps.Get("pid").ValueDefaultStr("0")
  6169. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  6170. sort := parammaps.Get("sort").ValueDefaultStr("0")
  6171. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  6172. date := parammaps.Get("date").ValueStr()
  6173. tx := restful.Engine.NewSession()
  6174. defer tx.Close()
  6175. count, err := tx.SQL(`select count(1) from downloadedplan where pid in(select pid from downloadedplan where id= ? ) and havebutton = 1 and mydate = ?`, pid, date).Count()
  6176. if err != nil {
  6177. logs.Error("UpdateDailyData-error-0:", err)
  6178. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  6179. return
  6180. }
  6181. if count > 0 {
  6182. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  6183. return
  6184. }
  6185. tx.Begin()
  6186. if location == 0 {
  6187. fid := parammaps.Get("fid").ValueStr()
  6188. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  6189. if err != nil {
  6190. logs.Error("UpdateDailyData-error-1:", err)
  6191. tx.Rollback()
  6192. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6193. return
  6194. }
  6195. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6196. if err != nil {
  6197. logs.Error("UpdateDailyData-error-1:", err)
  6198. tx.Rollback()
  6199. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6200. return
  6201. }
  6202. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  6203. if err != nil {
  6204. fmt.Println("Error:", err)
  6205. return
  6206. }
  6207. actualWeight := weight - num
  6208. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  6209. if err != nil {
  6210. logs.Error("UpdateDailyData-error-2:", err)
  6211. tx.Rollback()
  6212. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6213. return
  6214. }
  6215. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  6216. if err != nil {
  6217. logs.Error("UpdateDailyData-error-3:", err)
  6218. tx.Rollback()
  6219. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6220. return
  6221. }
  6222. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6223. if err != nil {
  6224. logs.Error("UpdateDailyData-error-4:", err)
  6225. tx.Rollback()
  6226. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6227. return
  6228. }
  6229. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6230. if err != nil {
  6231. logs.Error("UpdateDailyData-error-5:", err)
  6232. tx.Rollback()
  6233. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6234. return
  6235. }
  6236. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6237. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6238. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6239. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6240. if err != nil {
  6241. fmt.Println("Error:", err)
  6242. return
  6243. }
  6244. // actual := actualWeight / float64(len(downloadedplanList))
  6245. for _, item := range downloadedplanList {
  6246. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6247. if err != nil {
  6248. fmt.Println("Error:", err)
  6249. return
  6250. }
  6251. actual := itemLweight / lweight * actualWeight
  6252. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6253. if err != nil {
  6254. logs.Error("UpdateDailyData-error-6:", err)
  6255. tx.Rollback()
  6256. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6257. return
  6258. }
  6259. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6260. if err != nil {
  6261. logs.Error("UpdateDailyData-error-7:", err)
  6262. tx.Rollback()
  6263. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6264. return
  6265. }
  6266. _, 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()
  6267. if err != nil {
  6268. logs.Error("UpdateDailyData-error-8:", err)
  6269. tx.Rollback()
  6270. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6271. return
  6272. }
  6273. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6274. if err != nil {
  6275. logs.Error("UpdateDailyData-error-9:", err)
  6276. tx.Rollback()
  6277. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6278. return
  6279. }
  6280. }
  6281. } else {
  6282. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6283. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6284. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6285. // if err != nil {
  6286. // fmt.Println("Error:", err)
  6287. // return
  6288. // }
  6289. for _, item := range downloadedplanList {
  6290. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6291. if err != nil {
  6292. logs.Error("UpdateDailyData-error-6:", err)
  6293. tx.Rollback()
  6294. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6295. return
  6296. }
  6297. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6298. item["lweight"], actualWeight, item["id"]).Execute()
  6299. if err != nil {
  6300. logs.Error("UpdateDailyData-error-7:", err)
  6301. tx.Rollback()
  6302. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6303. return
  6304. }
  6305. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6306. where pid = ?`, item["id"]).Execute()
  6307. if err != nil {
  6308. logs.Error("UpdateDailyData-error-8:", err)
  6309. tx.Rollback()
  6310. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6311. return
  6312. }
  6313. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6314. if err != nil {
  6315. logs.Error("UpdateDailyData-error-9:", err)
  6316. tx.Rollback()
  6317. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6318. return
  6319. }
  6320. }
  6321. }
  6322. } else {
  6323. fbarid := parammaps.Get("fbarid").ValueStr()
  6324. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  6325. if err != nil {
  6326. logs.Error("UpdateDailyData-error-10:", err)
  6327. tx.Rollback()
  6328. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6329. return
  6330. }
  6331. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6332. if err != nil {
  6333. logs.Error("UpdateDailyData-error-1:", err)
  6334. tx.Rollback()
  6335. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6336. return
  6337. }
  6338. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  6339. if err != nil {
  6340. fmt.Println("Error:", err)
  6341. return
  6342. }
  6343. actualWeight := weight - num
  6344. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  6345. if err != nil {
  6346. logs.Error("UpdateDailyData-error-11:", err)
  6347. tx.Rollback()
  6348. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6349. return
  6350. }
  6351. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  6352. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6353. if err != nil {
  6354. logs.Error("UpdateDailyData-error-12:", err)
  6355. tx.Rollback()
  6356. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6357. return
  6358. }
  6359. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6360. where pid = ? `, pid).Execute()
  6361. if err != nil {
  6362. logs.Error("UpdateDailyData-error-13:", err)
  6363. tx.Rollback()
  6364. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6365. return
  6366. }
  6367. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6368. if err != nil {
  6369. logs.Error("UpdateDailyData-error-14:", err)
  6370. tx.Rollback()
  6371. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6372. return
  6373. }
  6374. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6375. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6376. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6377. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6378. if err != nil {
  6379. fmt.Println("Error:", err)
  6380. return
  6381. }
  6382. for _, item := range downloadedplanList {
  6383. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6384. if err != nil {
  6385. fmt.Println("Error:", err)
  6386. return
  6387. }
  6388. actual := itemLweight / lweight * actualWeight
  6389. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6390. if err != nil {
  6391. logs.Error("UpdateDailyData-error-6:", err)
  6392. tx.Rollback()
  6393. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6394. return
  6395. }
  6396. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6397. if err != nil {
  6398. logs.Error("UpdateDailyData-error-7:", err)
  6399. tx.Rollback()
  6400. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6401. return
  6402. }
  6403. _, 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()
  6404. if err != nil {
  6405. logs.Error("UpdateDailyData-error-8:", err)
  6406. tx.Rollback()
  6407. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6408. return
  6409. }
  6410. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6411. if err != nil {
  6412. logs.Error("UpdateDailyData-error-9:", err)
  6413. tx.Rollback()
  6414. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6415. return
  6416. }
  6417. }
  6418. } else {
  6419. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6420. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6421. for _, item := range downloadedplanList {
  6422. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6423. // if err != nil {
  6424. // fmt.Println("Error:", err)
  6425. // return
  6426. // }
  6427. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6428. if err != nil {
  6429. logs.Error("UpdateDailyData-error-6:", err)
  6430. tx.Rollback()
  6431. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6432. return
  6433. }
  6434. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6435. item["lweight"], actualWeight, item["id"]).Execute()
  6436. if err != nil {
  6437. logs.Error("UpdateDailyData-error-7:", err)
  6438. tx.Rollback()
  6439. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6440. return
  6441. }
  6442. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6443. where pid = ?`, item["id"]).Execute()
  6444. if err != nil {
  6445. logs.Error("UpdateDailyData-error-8:", err)
  6446. tx.Rollback()
  6447. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6448. return
  6449. }
  6450. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6451. if err != nil {
  6452. logs.Error("UpdateDailyData-error-9:", err)
  6453. tx.Rollback()
  6454. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6455. return
  6456. }
  6457. }
  6458. }
  6459. }
  6460. err = tx.Commit()
  6461. if err != nil {
  6462. logs.Error("UpdateDailyData-error-20:", err)
  6463. tx.Rollback()
  6464. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6465. return
  6466. }
  6467. appG.Response(http.StatusOK, e.SUCCESS, true)
  6468. }
  6469. func GetFormulaStatistics(c *gin.Context) {
  6470. appG := app.Gin{C: c}
  6471. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6472. parammaps := gofasion.NewFasion(string(dataByte))
  6473. startTime := parammaps.Get("startTime").ValueStr()
  6474. endTime := parammaps.Get("endTime").ValueStr()
  6475. pastureId := parammaps.Get("pastureId").ValueStr()
  6476. tx := restful.Engine.NewSession()
  6477. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  6478. if err != nil {
  6479. logs.Error("GetFormulaStatistics-error-1:", err)
  6480. tx.Rollback()
  6481. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6482. return
  6483. }
  6484. var feedtemplet, dateList []string
  6485. for _, f := range feedtempletList {
  6486. feedtemplet = append(feedtemplet, f["tname"].(string))
  6487. }
  6488. layout := "2006-01-02"
  6489. // s := "2023-05-01"
  6490. // e := "2023-05-23"
  6491. start, err := time.Parse(layout, startTime)
  6492. if err != nil {
  6493. fmt.Println(err)
  6494. return
  6495. }
  6496. end, err := time.Parse(layout, endTime)
  6497. if err != nil {
  6498. fmt.Println(err)
  6499. return
  6500. }
  6501. end = end.AddDate(0, 0, 1)
  6502. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  6503. dateList = append(dateList, d.Format("2006-01-02"))
  6504. }
  6505. downloadedplanList, err := tx.SQL(`select count(1) total,ft.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  6506. join feedtempletdate ft on ft.id = d.tempid and ft.date = d.mydate where d.mydate between ? and ? and d.lpplantype in(0,1) and d.iscompleted = 1 and d.pastureId= ?
  6507. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  6508. if err != nil {
  6509. logs.Error("GetFormulaStatistics-error-2:", err)
  6510. tx.Rollback()
  6511. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6512. return
  6513. }
  6514. var data2 [][]interface{}
  6515. for _, f := range feedtemplet {
  6516. var data1 []interface{}
  6517. for _, date := range dateList {
  6518. exist := false
  6519. for _, item := range downloadedplanList {
  6520. if date == item["mydate"].(string) && f == item["tname"].(string) {
  6521. data1 = append(data1, item["total"])
  6522. exist = true
  6523. break
  6524. }
  6525. }
  6526. if !exist {
  6527. data1 = append(data1, 0)
  6528. }
  6529. }
  6530. data2 = append(data2, data1)
  6531. }
  6532. //前端让加的
  6533. feedtemplet = append(feedtemplet, "")
  6534. {
  6535. var data1 []interface{}
  6536. for _, f := range dateList {
  6537. // f = f + "\n"
  6538. fmt.Println(f)
  6539. data1 = append(data1, 0)
  6540. }
  6541. data2 = append(data2, data1)
  6542. }
  6543. resp := make(map[string]interface{}, 0)
  6544. resp["xdata"] = dateList
  6545. resp["data1"] = feedtemplet
  6546. resp["data2"] = data2
  6547. appG.Response(http.StatusOK, e.SUCCESS, resp)
  6548. }
  6549. func GetPlanData(c *gin.Context) {
  6550. appG := app.Gin{C: c}
  6551. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6552. fsion := gofasion.NewFasion(string(dataByte))
  6553. sqlnamestr := fsion.Get("name").ValueStr()
  6554. sqlnamestr1 := fsion.Get("name1").ValueStr()
  6555. offset := fsion.Get("offset").ValueDefaultInt(0)
  6556. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  6557. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  6558. month := fsion.Get("month").ValueDefaultStr("map")
  6559. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  6560. tx := restful.Engine.NewSession()
  6561. err := tx.Begin()
  6562. defer func() {
  6563. switch {
  6564. case err != nil:
  6565. if tx != nil {
  6566. tx.Rollback()
  6567. }
  6568. default:
  6569. if tx != nil {
  6570. err = tx.Commit()
  6571. }
  6572. }
  6573. if tx != nil {
  6574. tx.Close()
  6575. }
  6576. }()
  6577. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  6578. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  6579. if sql != "" {
  6580. s_params := make([]interface{}, 0)
  6581. if fsion.HasKey("parammaps") {
  6582. parammaps := fsion.Get("parammaps")
  6583. paramslist := strings.Split(p, ",")
  6584. if len(paramslist) > 0 && p != "" {
  6585. for _, value := range paramslist {
  6586. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  6587. if tempv, exists := c.Get("jwt_username"); exists {
  6588. s_params = append(s_params, tempv.(string))
  6589. } else {
  6590. s_params = append(s_params, "")
  6591. }
  6592. } else {
  6593. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6594. }
  6595. }
  6596. }
  6597. }
  6598. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6599. if err != nil {
  6600. appG.Response(http.StatusOK, e.ERROR, err.Error())
  6601. } else {
  6602. paramslist1 := strings.Split(p1, ",")
  6603. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6604. s_params1 := make([]interface{}, 0)
  6605. if len(paramslist1) > 0 && p1 != "" {
  6606. for _, v := range paramslist1 {
  6607. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  6608. }
  6609. }
  6610. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  6611. for _, item := range arr {
  6612. trgaddressList := []string{}
  6613. if _, ok := item["trgaddress"]; ok {
  6614. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  6615. for _, str := range trgaddressList1 {
  6616. if str != "" {
  6617. trgaddressList = append(trgaddressList, str)
  6618. }
  6619. }
  6620. }
  6621. item["trgaddressList"] = trgaddressList
  6622. }
  6623. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  6624. }
  6625. // var wg sync.WaitGroup
  6626. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6627. // wg.Add(1)
  6628. // go func(value map[string]interface{}) {
  6629. // defer wg.Done()
  6630. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  6631. // }(value)
  6632. // }
  6633. // wg.Wait()
  6634. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6635. }
  6636. } else {
  6637. appG.Response(http.StatusOK, e.SUCCESS, nil)
  6638. }
  6639. }
  6640. func PostPlanData(c *gin.Context) {
  6641. appG := app.Gin{C: c}
  6642. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6643. fsion := gofasion.NewFasion(string(dataByte))
  6644. logging.Info("PostRJSBData err: ", string(dataByte))
  6645. s_params := make([]interface{}, 0)
  6646. tx := restful.Engine.NewSession()
  6647. err := tx.Begin()
  6648. defer func() {
  6649. switch {
  6650. case err != nil:
  6651. if tx != nil {
  6652. tx.Rollback()
  6653. }
  6654. default:
  6655. if tx != nil {
  6656. err = tx.Commit()
  6657. }
  6658. }
  6659. if tx != nil {
  6660. tx.Close()
  6661. }
  6662. }()
  6663. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  6664. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  6665. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  6666. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  6667. if !fsion.HasKey("parammaps") {
  6668. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  6669. return
  6670. }
  6671. parammaps := fsion.Get("parammaps")
  6672. // paramslist := strings.Split(p, ",")
  6673. // if len(paramslist) > 0 && p != "" {
  6674. // for _, value := range paramslist {
  6675. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6676. // }
  6677. // }
  6678. // _, err = tx.SQL(sql, s_params...).Execute()
  6679. // if err != nil {
  6680. // logging.Error("PostRJSBData err: ", err)
  6681. // msg := geterrmsg(err.Error())
  6682. // appG.Response(http.StatusOK, e.ERROR, msg)
  6683. // return
  6684. // }
  6685. s_params = make([]interface{}, 0)
  6686. paramslist := strings.Split(p1, ",")
  6687. if len(paramslist) > 0 && p1 != "" {
  6688. for _, value := range paramslist {
  6689. // if value == "ID" {
  6690. // id := parammaps.Get("ID").ValueStr()
  6691. // pastureid := parammaps.Get("pastureid").ValueStr()
  6692. // 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
  6693. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  6694. // if err != nil {
  6695. // logging.Error("PostRJSBData err: ", err)
  6696. // msg := geterrmsg(err.Error())
  6697. // appG.Response(http.StatusOK, e.ERROR, msg)
  6698. // return
  6699. // }
  6700. // for _, item := range datalist {
  6701. // id = item["id"]
  6702. // }
  6703. // s_params = append(s_params, id)
  6704. // } else {
  6705. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6706. // }
  6707. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6708. }
  6709. }
  6710. _, err = tx.SQL(sql1, s_params...).Execute()
  6711. if err != nil {
  6712. logging.Error("PostRJSBData1 err: ", err)
  6713. msg := geterrmsg(err.Error())
  6714. appG.Response(http.StatusOK, e.ERROR, msg)
  6715. return
  6716. }
  6717. s_params = make([]interface{}, 0)
  6718. paramslist = strings.Split(p2, ",")
  6719. if len(paramslist) > 0 && p2 != "" {
  6720. for _, value := range paramslist {
  6721. if value == "ID" {
  6722. id := parammaps.Get("ID").ValueStr()
  6723. pastureid := parammaps.Get("pastureid").ValueStr()
  6724. 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
  6725. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  6726. if err != nil {
  6727. logging.Error("PostRJSBData err: ", err)
  6728. msg := geterrmsg(err.Error())
  6729. appG.Response(http.StatusOK, e.ERROR, msg)
  6730. return
  6731. }
  6732. for _, item := range datalist {
  6733. id = item["id"]
  6734. }
  6735. s_params = append(s_params, id)
  6736. } else {
  6737. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6738. }
  6739. }
  6740. }
  6741. _, err = tx.SQL(sql2, s_params...).Execute()
  6742. if err != nil {
  6743. logging.Error("PostRJSBData2 err: ", err)
  6744. msg := geterrmsg(err.Error())
  6745. appG.Response(http.StatusOK, e.ERROR, msg)
  6746. return
  6747. }
  6748. s_params = make([]interface{}, 0)
  6749. paramslist = strings.Split(p3, ",")
  6750. if len(paramslist) > 0 && p3 != "" {
  6751. for _, value := range paramslist {
  6752. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6753. }
  6754. }
  6755. _, err = tx.SQL(sql3, s_params...).Execute()
  6756. if err != nil {
  6757. logging.Error("PostRJSBData3 err: ", err)
  6758. msg := geterrmsg(err.Error())
  6759. appG.Response(http.StatusOK, e.ERROR, msg)
  6760. return
  6761. }
  6762. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  6763. }
  6764. func CheckFeedTrgaddress(c *gin.Context) {
  6765. appG := app.Gin{C: c}
  6766. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6767. fsion := gofasion.NewFasion(string(dataByte))
  6768. fclassid := fsion.Get("fclassid").ValueStr()
  6769. feedId := fsion.Get("feedId").ValueStr()
  6770. backup1 := fsion.Get("backup1").ValueStr()
  6771. backup1List := strings.Split(backup1, ",")
  6772. tx := restful.Engine.NewSession()
  6773. defer tx.Close()
  6774. // if backup1 != "" {
  6775. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  6776. for _, feed := range feedList {
  6777. if feed["backup1"] == "" {
  6778. continue
  6779. }
  6780. feedbackupList := strings.Split(feed["backup1"], ",")
  6781. for _, feedbackup := range feedbackupList {
  6782. for _, backup := range backup1List {
  6783. if feedbackup == backup {
  6784. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  6785. return
  6786. }
  6787. }
  6788. }
  6789. }
  6790. // }
  6791. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  6792. }
  6793. func ThiGetDataByName(c *gin.Context) {
  6794. appG := app.Gin{C: c}
  6795. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6796. fsion := gofasion.NewFasion(string(dataByte))
  6797. sqlnamestr := fsion.Get("name").ValueStr()
  6798. offset := fsion.Get("offset").ValueDefaultInt(0)
  6799. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  6800. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  6801. tx := restful.Engine.NewSession()
  6802. err := tx.Begin()
  6803. defer func() {
  6804. switch {
  6805. case err != nil:
  6806. logging.Error("tx.Begin 事务启动失败__error:", err)
  6807. if tx != nil {
  6808. tx.Rollback()
  6809. }
  6810. default:
  6811. if tx != nil {
  6812. err = tx.Commit()
  6813. }
  6814. }
  6815. if tx != nil {
  6816. tx.Close()
  6817. }
  6818. }()
  6819. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  6820. if sql != "" {
  6821. s_params := make([]interface{}, 0)
  6822. if fsion.HasKey("parammaps") {
  6823. parammaps := fsion.Get("parammaps")
  6824. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  6825. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  6826. }
  6827. paramslist := strings.Split(p, ",")
  6828. if len(paramslist) > 0 && p != "" {
  6829. for _, value := range paramslist {
  6830. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  6831. if tempv, exists := c.Get("jwt_username"); exists {
  6832. s_params = append(s_params, tempv.(string))
  6833. } else {
  6834. s_params = append(s_params, "")
  6835. }
  6836. } else {
  6837. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6838. }
  6839. }
  6840. }
  6841. } else if fsion.HasKey("params") {
  6842. params := fsion.Get("params").Array()
  6843. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  6844. for _, v_params := range params {
  6845. s_params = append(s_params, v_params.ValueStr())
  6846. }
  6847. }
  6848. if returntype == "xlsx" {
  6849. var xlsxfile *xlsx.File
  6850. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  6851. //c.File("c:/dd.xlsx")
  6852. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  6853. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  6854. c.Header("Content-Transfer-Encoding", "binary")
  6855. _ = xlsxfile.Write(c.Writer)
  6856. } else {
  6857. if sqlnamestr == "getHomepageStr" {
  6858. parammaps := fsion.Get("parammaps")
  6859. pastureid := parammaps.Get("pastureid").ValueStr()
  6860. var montimeList []float64
  6861. var montime float64
  6862. var wg sync.WaitGroup
  6863. now := time.Now()
  6864. for i := 0; i < 30; i++ {
  6865. wg.Add(1)
  6866. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  6867. go func(nowstr string) {
  6868. defer wg.Done()
  6869. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  6870. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  6871. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  6872. montimeList = append(montimeList, m)
  6873. }(nowstr)
  6874. }
  6875. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6876. if err != nil {
  6877. logging.Error("GetDataByName err: ", err)
  6878. msg := geterrmsg(err.Error())
  6879. appG.Response(http.StatusOK, e.ERROR, msg)
  6880. }
  6881. wg.Wait()
  6882. for _, m := range montimeList {
  6883. montime += m
  6884. }
  6885. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  6886. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6887. return
  6888. }
  6889. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6890. if err != nil {
  6891. logging.Error("GetDataByName err: ", err)
  6892. msg := geterrmsg(err.Error())
  6893. appG.Response(http.StatusOK, e.ERROR, msg)
  6894. } else {
  6895. if sqlnamestr == "getFeedTrgaddressList" {
  6896. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6897. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  6898. trgaddressList := []string{}
  6899. for _, str := range trgaddressList1 {
  6900. if str != "" {
  6901. trgaddressList = append(trgaddressList, str)
  6902. }
  6903. }
  6904. item["trgaddressList"] = trgaddressList
  6905. }
  6906. }
  6907. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6908. }
  6909. }
  6910. } else {
  6911. appG.Response(http.StatusOK, e.SUCCESS, nil)
  6912. }
  6913. }
  6914. // func ToggleCcount(c *gin.Context) {
  6915. // appG := app.Gin{C: c}
  6916. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6917. // fsion := gofasion.NewFasion(string(dataByte))
  6918. // // 0 实际 1 软件
  6919. // status := fsion.Get("status").ValueDefaultInt64(0)
  6920. // pastureId := fsion.Get("pastureId").ValueStr()
  6921. // tx := restful.Engine.NewSession()
  6922. // err := tx.Begin()
  6923. // defer func() {
  6924. // switch {
  6925. // case err != nil:
  6926. // logging.Error("tx.Begin 事务启动失败__error:", err)
  6927. // if tx != nil {
  6928. // tx.Rollback()
  6929. // }
  6930. // default:
  6931. // if tx != nil {
  6932. // err = tx.Commit()
  6933. // }
  6934. // }
  6935. // if tx != nil {
  6936. // tx.Close()
  6937. // }
  6938. // }()
  6939. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  6940. // if err != nil {
  6941. // logs.Error(err)
  6942. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6943. // return
  6944. // }
  6945. // for _, bar := range barList {
  6946. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  6947. // if err != nil {
  6948. // logs.Error(err)
  6949. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6950. // return
  6951. // }
  6952. // if !exist {
  6953. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  6954. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  6955. // if err != nil {
  6956. // logs.Error(err)
  6957. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6958. // return
  6959. // }
  6960. // }
  6961. // }
  6962. // if status == 0 {
  6963. // tx.Exec(`update feedp set ccount = actualcount `)
  6964. // }else{
  6965. // tx.Exec(`update feedp set ccount = softccount `)
  6966. // }
  6967. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  6968. // if err != nil {
  6969. // logs.Error(err)
  6970. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6971. // return
  6972. // }
  6973. // for _, feedpData :=range feedpList{
  6974. // var feedpargs []interface{}
  6975. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  6976. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  6977. // if _, ok := feedpData["ftname"]; ok {
  6978. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  6979. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  6980. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  6981. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  6982. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  6983. // } else {
  6984. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  6985. // }
  6986. // if _, ok := feedpData["ptsfname"]; ok {
  6987. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  6988. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  6989. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  6990. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  6991. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  6992. // } else {
  6993. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  6994. // }
  6995. // upFeedpSql += " where barname = ? and pastureid = ? "
  6996. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  6997. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  6998. // if err != nil {
  6999. // logs.Error(err)
  7000. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7001. // return
  7002. // }
  7003. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7004. // if err != nil {
  7005. // logs.Error(err)
  7006. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7007. // return
  7008. // }
  7009. // if !exist1 {
  7010. // _, 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) `,
  7011. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7012. // if err != nil {
  7013. // logs.Error(err)
  7014. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7015. // return
  7016. // }
  7017. // }
  7018. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7019. // if err != nil {
  7020. // logs.Error(err)
  7021. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7022. // return
  7023. // }
  7024. // if !exist2 {
  7025. // _, 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) `,
  7026. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7027. // if err != nil {
  7028. // logs.Error(err)
  7029. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7030. // return
  7031. // }
  7032. // }
  7033. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7034. // if err != nil {
  7035. // logs.Error(err)
  7036. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7037. // return
  7038. // }
  7039. // if !exist3 {
  7040. // _, 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) `,
  7041. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7042. // if err != nil {
  7043. // logs.Error(err)
  7044. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7045. // return
  7046. // }
  7047. // }
  7048. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7049. // if err != nil {
  7050. // logs.Error(err)
  7051. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7052. // return
  7053. // }
  7054. // if !exist4 {
  7055. // _, 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) `,
  7056. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7057. // if err != nil {
  7058. // logs.Error(err)
  7059. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7060. // return
  7061. // }
  7062. // }
  7063. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7064. // if err != nil {
  7065. // logs.Error(err)
  7066. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7067. // return
  7068. // }
  7069. // if !exist5 {
  7070. // _, 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) `,
  7071. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7072. // if err != nil {
  7073. // logs.Error(err)
  7074. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7075. // return
  7076. // }
  7077. // }
  7078. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7079. // if err != nil {
  7080. // logs.Error(err)
  7081. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7082. // return
  7083. // }
  7084. // if !exist6 {
  7085. // _, 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) `,
  7086. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7087. // if err != nil {
  7088. // logs.Error(err)
  7089. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7090. // return
  7091. // }
  7092. // }
  7093. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7094. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7095. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7096. // and pastureid = ? and times = ?`
  7097. // var fpdargs1 []interface{}
  7098. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7099. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7100. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7101. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7102. // if err != nil {
  7103. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7104. // return
  7105. // }
  7106. // var fpdargs2 []interface{}
  7107. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7108. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7109. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7110. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7111. // if err != nil {
  7112. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7113. // return
  7114. // }
  7115. // var fpdargs3 []interface{}
  7116. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7117. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7118. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7119. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7120. // if err != nil {
  7121. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7122. // return
  7123. // }
  7124. // var fpdargs4 []interface{}
  7125. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7126. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7127. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7128. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7129. // if err != nil {
  7130. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7131. // return
  7132. // }
  7133. // var fpdargs5 []interface{}
  7134. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7135. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7136. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7137. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7138. // if err != nil {
  7139. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7140. // return
  7141. // }
  7142. // var fpdargs6 []interface{}
  7143. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7144. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7145. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7146. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7147. // if err != nil {
  7148. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7149. // return
  7150. // }
  7151. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7152. // 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()
  7153. // if err != nil {
  7154. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7155. // return
  7156. // }
  7157. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7158. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7159. // upFpdetailList := make([]*upFpdetail, 0)
  7160. // for _, newfpd := range newList {
  7161. // for _, oldfpd := range oldFpdList {
  7162. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7163. // var oldweight, newweight float64
  7164. // if oldfpd["weight"] != nil {
  7165. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7166. // }
  7167. // if newfpd["weight"] != nil {
  7168. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7169. // }
  7170. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7171. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  7172. // Old: oldweight,
  7173. // New: newweight,
  7174. // Times: newfpd["times"].(int64),
  7175. // Ptid: newfpd["ptid"].(int64),
  7176. // Fweight: fweight,
  7177. // Id: oldfpd["id"].(int64),
  7178. // })
  7179. // break
  7180. // }
  7181. // }
  7182. // }
  7183. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  7184. // }
  7185. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  7186. // }
  7187. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  7188. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  7189. if err != nil {
  7190. return err
  7191. }
  7192. for _, item := range feedpList {
  7193. // if item["ftid"].(string) != data["ftid"].(string) {
  7194. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  7195. if err != nil {
  7196. return err
  7197. }
  7198. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  7199. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  7200. if err != nil {
  7201. return err
  7202. }
  7203. // }
  7204. }
  7205. return nil
  7206. }
  7207. func PostPlanDatas(c *gin.Context) {
  7208. appG := app.Gin{C: c}
  7209. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7210. fsions := gofasion.NewFasion(string(dataByte))
  7211. logging.Info("PostRJSBDatas err: ", string(dataByte))
  7212. tx := restful.Engine.NewSession()
  7213. err := tx.Begin()
  7214. defer func() {
  7215. switch {
  7216. case err != nil:
  7217. if tx != nil {
  7218. tx.Rollback()
  7219. }
  7220. default:
  7221. if tx != nil {
  7222. err = tx.Commit()
  7223. }
  7224. }
  7225. if tx != nil {
  7226. tx.Close()
  7227. }
  7228. }()
  7229. pastureId := fsions.Get("pastureid").ValueStr()
  7230. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7231. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  7232. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  7233. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  7234. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7235. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7236. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7237. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7238. for _, parammaps := range fsions.Get("arrList").Array() {
  7239. fmt.Println(parammaps.Json())
  7240. if parammaps.Json() == "null" {
  7241. continue
  7242. }
  7243. // if !fsion.HasKey("arrList") {
  7244. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7245. // return
  7246. // continue
  7247. // }
  7248. // parammaps := fsion.Get("arrList")
  7249. s_params := make([]interface{}, 0)
  7250. // paramslist := strings.Split(p, ",")
  7251. // if len(paramslist) > 0 && p != "" {
  7252. // for _, value := range paramslist {
  7253. // if value == "pastureid" {
  7254. // s_params = append(s_params, pastureId)
  7255. // } else {
  7256. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7257. // }
  7258. // }
  7259. // }
  7260. // _, err = tx.SQL(sql, s_params...).Execute()
  7261. // if err != nil {
  7262. // logging.Error("PostRJSBData err: ", err)
  7263. // msg := geterrmsg(err.Error())
  7264. // appG.Response(http.StatusOK, e.ERROR, msg)
  7265. // return
  7266. // }
  7267. s_params = make([]interface{}, 0)
  7268. paramslist := strings.Split(p1, ",")
  7269. if len(paramslist) > 0 && p1 != "" {
  7270. for _, value := range paramslist {
  7271. // if value == "ID" {
  7272. // id := parammaps.Get("ID").ValueStr()
  7273. // pastureid := parammaps.Get("pastureid").ValueStr()
  7274. // 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
  7275. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7276. // if err != nil {
  7277. // logging.Error("PostRJSBData err: ", err)
  7278. // msg := geterrmsg(err.Error())
  7279. // appG.Response(http.StatusOK, e.ERROR, msg)
  7280. // return
  7281. // }
  7282. // for _, item := range datalist {
  7283. // id = item["id"]
  7284. // }
  7285. // s_params = append(s_params, id)
  7286. // } else {
  7287. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7288. // }
  7289. if value == "pastureid" {
  7290. s_params = append(s_params, pastureId)
  7291. } else {
  7292. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7293. }
  7294. }
  7295. }
  7296. _, err = tx.SQL(sql1, s_params...).Execute()
  7297. if err != nil {
  7298. logging.Error("PostRJSBData1 err: ", err)
  7299. msg := geterrmsg(err.Error())
  7300. appG.Response(http.StatusOK, e.ERROR, msg)
  7301. return
  7302. }
  7303. s_params = make([]interface{}, 0)
  7304. paramslist = strings.Split(p2, ",")
  7305. if len(paramslist) > 0 && p2 != "" {
  7306. for _, value := range paramslist {
  7307. if value == "ID" {
  7308. id := parammaps.Get("ID").ValueStr()
  7309. pastureid := parammaps.Get("pastureid").ValueStr()
  7310. 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
  7311. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7312. if err != nil {
  7313. logging.Error("PostRJSBData err: ", err)
  7314. msg := geterrmsg(err.Error())
  7315. appG.Response(http.StatusOK, e.ERROR, msg)
  7316. return
  7317. }
  7318. for _, item := range datalist {
  7319. id = item["id"]
  7320. }
  7321. s_params = append(s_params, id)
  7322. } else if value == "pastureid" {
  7323. s_params = append(s_params, pastureId)
  7324. } else {
  7325. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7326. }
  7327. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7328. }
  7329. }
  7330. _, err = tx.SQL(sql2, s_params...).Execute()
  7331. if err != nil {
  7332. logging.Error("PostRJSBData2 err: ", err)
  7333. msg := geterrmsg(err.Error())
  7334. appG.Response(http.StatusOK, e.ERROR, msg)
  7335. return
  7336. }
  7337. s_params = make([]interface{}, 0)
  7338. paramslist = strings.Split(p3, ",")
  7339. if len(paramslist) > 0 && p3 != "" {
  7340. for _, value := range paramslist {
  7341. if value == "pastureid" {
  7342. s_params = append(s_params, pastureId)
  7343. } else {
  7344. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7345. }
  7346. }
  7347. }
  7348. _, err = tx.SQL(sql3, s_params...).Execute()
  7349. if err != nil {
  7350. logging.Error("PostRJSBData3 err: ", err)
  7351. msg := geterrmsg(err.Error())
  7352. appG.Response(http.StatusOK, e.ERROR, msg)
  7353. return
  7354. }
  7355. }
  7356. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7357. }
  7358. func FpdBatchEdit(c *gin.Context) {
  7359. appG := app.Gin{C: c}
  7360. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7361. fsions := gofasion.NewFasion(string(dataByte))
  7362. barList := fsions.Get("barList").Array()
  7363. pastureid := fsions.Get("pastureId").ValueStr()
  7364. tx := restful.Engine.NewSession()
  7365. defer tx.Close()
  7366. 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
  7367. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7368. if err != nil {
  7369. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7370. return
  7371. }
  7372. for _, barFsions := range barList {
  7373. dataexcel := make(map[string]interface{}, 0)
  7374. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  7375. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  7376. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  7377. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  7378. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  7379. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  7380. continue
  7381. }
  7382. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  7383. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  7384. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  7385. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  7386. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  7387. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  7388. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  7389. if err != nil {
  7390. logs.Error(err)
  7391. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7392. return
  7393. }
  7394. if !ftexist {
  7395. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  7396. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7397. if err != nil {
  7398. logs.Error(err)
  7399. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7400. return
  7401. }
  7402. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7403. if err != nil {
  7404. logs.Error(err)
  7405. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7406. return
  7407. }
  7408. }
  7409. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7410. if err != nil {
  7411. logs.Error(err)
  7412. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7413. return
  7414. }
  7415. if !exist {
  7416. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7417. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  7418. if err != nil {
  7419. logs.Error(err)
  7420. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7421. return
  7422. }
  7423. }
  7424. var feedpargs []interface{}
  7425. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7426. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  7427. if _, ok := dataexcel["ftname"]; ok {
  7428. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  7429. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7430. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7431. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7432. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  7433. } else {
  7434. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7435. }
  7436. if _, ok := dataexcel["ptsfname"]; ok {
  7437. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  7438. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7439. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7440. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7441. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  7442. } else {
  7443. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7444. }
  7445. upFeedpSql += " where barname = ? and pastureid = ? "
  7446. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  7447. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7448. if err != nil {
  7449. logs.Error(err)
  7450. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7451. return
  7452. }
  7453. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  7454. if err != nil {
  7455. logs.Error(err)
  7456. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7457. return
  7458. }
  7459. if !exist1 {
  7460. _, 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) `,
  7461. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7462. if err != nil {
  7463. logs.Error(err)
  7464. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7465. return
  7466. }
  7467. }
  7468. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  7469. if err != nil {
  7470. logs.Error(err)
  7471. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7472. return
  7473. }
  7474. if !exist2 {
  7475. _, 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) `,
  7476. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7477. if err != nil {
  7478. logs.Error(err)
  7479. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7480. return
  7481. }
  7482. }
  7483. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  7484. if err != nil {
  7485. logs.Error(err)
  7486. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7487. return
  7488. }
  7489. if !exist3 {
  7490. _, 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) `,
  7491. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7492. if err != nil {
  7493. logs.Error(err)
  7494. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7495. return
  7496. }
  7497. }
  7498. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  7499. if err != nil {
  7500. logs.Error(err)
  7501. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7502. return
  7503. }
  7504. if !exist4 {
  7505. _, 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) `,
  7506. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7507. if err != nil {
  7508. logs.Error(err)
  7509. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7510. return
  7511. }
  7512. }
  7513. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  7514. if err != nil {
  7515. logs.Error(err)
  7516. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7517. return
  7518. }
  7519. if !exist5 {
  7520. _, 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) `,
  7521. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7522. if err != nil {
  7523. logs.Error(err)
  7524. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7525. return
  7526. }
  7527. }
  7528. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  7529. if err != nil {
  7530. logs.Error(err)
  7531. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7532. return
  7533. }
  7534. if !exist6 {
  7535. _, 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) `,
  7536. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  7537. if err != nil {
  7538. logs.Error(err)
  7539. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7540. return
  7541. }
  7542. }
  7543. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7544. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7545. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7546. and pastureid = ? and times = ?`
  7547. var fpdargs1 []interface{}
  7548. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7549. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7550. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7551. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7552. if err != nil {
  7553. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7554. return
  7555. }
  7556. var fpdargs2 []interface{}
  7557. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7558. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7559. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7560. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7561. if err != nil {
  7562. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7563. return
  7564. }
  7565. var fpdargs3 []interface{}
  7566. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7567. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7568. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7569. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7570. if err != nil {
  7571. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7572. return
  7573. }
  7574. var fpdargs4 []interface{}
  7575. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7576. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7577. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7578. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7579. if err != nil {
  7580. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7581. return
  7582. }
  7583. var fpdargs5 []interface{}
  7584. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7585. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7586. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7587. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7588. if err != nil {
  7589. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7590. return
  7591. }
  7592. var fpdargs6 []interface{}
  7593. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7594. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7595. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7596. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7597. if err != nil {
  7598. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7599. return
  7600. }
  7601. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7602. 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()
  7603. if err != nil {
  7604. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7605. return
  7606. }
  7607. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7608. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7609. upFpdetailList := make([]*upFpdetail, 0)
  7610. for _, newfpd := range newList {
  7611. for _, oldfpd := range oldFpdList {
  7612. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7613. var oldweight, newweight float64
  7614. if oldfpd["weight"] != nil {
  7615. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7616. }
  7617. if newfpd["weight"] != nil {
  7618. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7619. }
  7620. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7621. upFpdetailList = append(upFpdetailList, &upFpdetail{
  7622. Old: oldweight,
  7623. New: newweight,
  7624. Times: newfpd["times"].(int64),
  7625. Ptid: newfpd["ptid"].(int64),
  7626. Fweight: fweight,
  7627. Id: oldfpd["id"].(int64),
  7628. })
  7629. break
  7630. }
  7631. }
  7632. }
  7633. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  7634. }
  7635. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7636. }
  7637. func UdBarSync(c *gin.Context) {
  7638. appG := app.Gin{C: c}
  7639. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7640. fsions := gofasion.NewFasion(string(dataByte))
  7641. pastureid := fsions.Get("pastureId").ValueStr()
  7642. tx := restful.Engine.NewSession()
  7643. defer tx.Close()
  7644. pastureinfo := new(udPastureInfo)
  7645. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  7646. if err != nil {
  7647. logs.Error(err)
  7648. return
  7649. }
  7650. gm.UdBarSync(pastureid, pastureinfo.Werks)
  7651. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7652. }
  7653. func UdFeedSync(c *gin.Context) {
  7654. appG := app.Gin{C: c}
  7655. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7656. fsions := gofasion.NewFasion(string(dataByte))
  7657. pastureid := fsions.Get("pastureId").ValueStr()
  7658. tx := restful.Engine.NewSession()
  7659. defer tx.Close()
  7660. pastureinfo := new(udPastureInfo)
  7661. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7662. if err != nil {
  7663. logs.Error(err)
  7664. return
  7665. }
  7666. gm.UdFeedSync(pastureid, pastureinfo.Werks)
  7667. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7668. }
  7669. func UdFeedtempletPush(c *gin.Context) {
  7670. appG := app.Gin{C: c}
  7671. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7672. fsions := gofasion.NewFasion(string(dataByte))
  7673. pastureid := fsions.Get("pastureId").ValueStr()
  7674. date := fsions.Get("date").ValueStr()
  7675. tx := restful.Engine.NewSession()
  7676. defer tx.Close()
  7677. pastureinfo := new(udPastureInfo)
  7678. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7679. if err != nil {
  7680. logs.Error(err)
  7681. return
  7682. }
  7683. gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  7684. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7685. }
  7686. func UdUtirPush(c *gin.Context) {
  7687. appG := app.Gin{C: c}
  7688. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7689. fsions := gofasion.NewFasion(string(dataByte))
  7690. pastureid := fsions.Get("pastureId").ValueStr()
  7691. date := fsions.Get("date").ValueStr()
  7692. tx := restful.Engine.NewSession()
  7693. defer tx.Close()
  7694. pastureinfo := new(udPastureInfo)
  7695. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7696. if err != nil {
  7697. logs.Error(err)
  7698. return
  7699. }
  7700. gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  7701. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7702. }
  7703. func UdBarFeedRemainPush(c *gin.Context) {
  7704. appG := app.Gin{C: c}
  7705. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7706. fsions := gofasion.NewFasion(string(dataByte))
  7707. pastureid := fsions.Get("pastureId").ValueStr()
  7708. date := fsions.Get("date").ValueStr()
  7709. tx := restful.Engine.NewSession()
  7710. defer tx.Close()
  7711. pastureinfo := new(udPastureInfo)
  7712. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7713. if err != nil {
  7714. logs.Error(err)
  7715. return
  7716. }
  7717. gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  7718. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7719. }
  7720. func UdMaterialIssuePush(c *gin.Context) {
  7721. appG := app.Gin{C: c}
  7722. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7723. fsions := gofasion.NewFasion(string(dataByte))
  7724. pastureid := fsions.Get("pastureId").ValueStr()
  7725. date := fsions.Get("date").ValueStr()
  7726. tx := restful.Engine.NewSession()
  7727. defer tx.Close()
  7728. pastureinfo := new(udPastureInfo)
  7729. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  7730. if err != nil {
  7731. logs.Error(err)
  7732. return
  7733. }
  7734. gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  7735. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7736. }
  7737. func DelFeedTemplet(c *gin.Context) {
  7738. appG := app.Gin{C: c}
  7739. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7740. fsions := gofasion.NewFasion(string(dataByte))
  7741. ftId := fsions.Get("ftId").ValueStr()
  7742. // userId := fsions.Get("userId").ValueStr()
  7743. tx := restful.Engine.NewSession()
  7744. defer tx.Close()
  7745. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  7746. if err != nil {
  7747. logs.Error(err)
  7748. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  7749. return
  7750. }
  7751. // barIdList, err := tx.SQL(`select barid from feedp where ftid = ? `, ftId).QueryString()
  7752. // if err != nil {
  7753. // logs.Error(err)
  7754. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  7755. // return
  7756. // }
  7757. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  7758. if err != nil {
  7759. logs.Error(err)
  7760. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  7761. return
  7762. }
  7763. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  7764. if err != nil {
  7765. logs.Error(err)
  7766. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  7767. return
  7768. }
  7769. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  7770. if count > 0 {
  7771. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  7772. if err != nil {
  7773. logs.Error(err)
  7774. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  7775. return
  7776. }
  7777. }
  7778. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  7779. if err != nil {
  7780. logs.Error(err)
  7781. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  7782. return
  7783. }
  7784. // var barIdStr []string
  7785. // for _, bar := range barIdList {
  7786. // barIdStr = append(barIdStr, bar["barid"])
  7787. // }
  7788. // if len(barIdStr) > 0 {
  7789. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  7790. // if err != nil {
  7791. // logs.Error(err)
  7792. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  7793. // return
  7794. // }
  7795. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  7796. // if err != nil {
  7797. // logs.Error(err)
  7798. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  7799. // return
  7800. // }
  7801. // now := time.Now()
  7802. // for _, newFpd := range newFpdDataList {
  7803. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  7804. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  7805. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  7806. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  7807. // if err != nil {
  7808. // logs.Error(err)
  7809. // appG.Response(http.StatusOK, e.ERROR, false)
  7810. // return
  7811. // }
  7812. // }
  7813. // for _, newFeedp := range newFeedpList {
  7814. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  7815. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  7816. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  7817. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  7818. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  7819. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  7820. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  7821. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  7822. // if err != nil {
  7823. // logs.Error(err)
  7824. // appG.Response(http.StatusOK, e.ERROR, false)
  7825. // return
  7826. // }
  7827. // }
  7828. // }
  7829. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7830. }
  7831. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  7832. data := fasion["parammaps"].(map[string]interface{})
  7833. plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(0,1,2) ").Count()
  7834. fmt.Println(err)
  7835. plancount1, err := tx.SQL(`SELECT
  7836. count( 1 )
  7837. FROM
  7838. (
  7839. SELECT
  7840. d.id
  7841. FROM
  7842. downloadedplan d
  7843. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  7844. JOIN downloadplandtl1_exec d1e ON d1e.pid = d.id
  7845. JOIN downloadplandtl2 d2 ON d2.pid = d.id
  7846. WHERE
  7847. d.mydate = ?
  7848. AND d.havebutton = 0
  7849. AND lpplantype IN ( 0, 1, 2 )
  7850. AND ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id ) =
  7851. ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.pid and (select count(1) from downloadplandtl2 where pid = dd2.pid and fname = dd2.fname ) = 1 )
  7852. GROUP BY
  7853. d.id
  7854. ) d
  7855. `,
  7856. data["startTime"]).Count()
  7857. fmt.Println(err)
  7858. if plancount != plancount1 && number < 10 {
  7859. number++
  7860. ExecDataParam(fasion, CommonParamMap, ParamMap, nil, nil, tx)
  7861. checkPlan(tx, fasion, CommonParamMap, ParamMap, number)
  7862. }
  7863. }
  7864. func EditPlanSort(c *gin.Context) {
  7865. appG := app.Gin{C: c}
  7866. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7867. fsions := gofasion.NewFasion(string(dataByte))
  7868. planIdStr := fsions.Get("planId").ValueStr()
  7869. mydate := fsions.Get("mydate").ValueStr()
  7870. sort := fsions.Get("sort").ValueStr()
  7871. tx := restful.Engine.NewSession()
  7872. defer tx.Close()
  7873. tx.Begin()
  7874. type downloadedplan struct {
  7875. Id int64 `xorm:"id"`
  7876. Sort int `xorm:"sort"`
  7877. Pid int64 `xorm:"pid"`
  7878. }
  7879. planInfo := new(downloadedplan)
  7880. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  7881. if err != nil {
  7882. logs.Error(err)
  7883. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7884. tx.Rollback()
  7885. return
  7886. }
  7887. sort1, _ := strconv.Atoi(sort)
  7888. if sort1 == planInfo.Sort {
  7889. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  7890. tx.Rollback()
  7891. return
  7892. }
  7893. count1, err := tx.SQL(` select count(1) from downloadedplan where pid = (select pid from downloadedplan where sort = ? and mydate = ? ) and mydate = ? `, sort, mydate, mydate).Count()
  7894. if err != nil {
  7895. logs.Error(err)
  7896. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7897. tx.Rollback()
  7898. return
  7899. }
  7900. if count1 == 0 {
  7901. tx.Rollback()
  7902. logs.Error(err)
  7903. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  7904. return
  7905. }
  7906. count, err := tx.SQL(` select count(1) from downloadedplan where pid = (select pid from downloadedplan where sort = ? and mydate = ? ) and havebutton = 1 and mydate = ? `, sort, mydate, mydate).Count()
  7907. if err != nil {
  7908. logs.Error(err)
  7909. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7910. tx.Rollback()
  7911. return
  7912. }
  7913. if count > 0 {
  7914. tx.Rollback()
  7915. logs.Error(err)
  7916. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  7917. return
  7918. }
  7919. if planInfo.Sort > sort1 {
  7920. minSortList, err := tx.SQL(`select min(d.sort) sort from downloadedplan d where d.mydate = ? and d.pid = (select pid from downloadedplan where sort = ? and mydate = ? ) `, mydate, sort, mydate).QueryString()
  7921. if err != nil {
  7922. logs.Error(err)
  7923. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7924. tx.Rollback()
  7925. return
  7926. }
  7927. var minSort, pidCount int
  7928. for _, sort := range minSortList {
  7929. minSort, _ = strconv.Atoi(sort["sort"])
  7930. }
  7931. planList := make([]*downloadedplan, 0)
  7932. err = tx.SQL(`select id,d.sort sort,d.pid from downloadedplan d where d.mydate = ? and sort >= ? order by sort`, mydate, minSort).Find(&planList)
  7933. if err != nil {
  7934. logs.Error(err)
  7935. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7936. tx.Rollback()
  7937. return
  7938. }
  7939. planPid := planInfo.Pid
  7940. planList1 := make([]*downloadedplan, 0)
  7941. planList2 := make([]*downloadedplan, 0)
  7942. for _, plan := range planList {
  7943. if plan.Pid == planPid {
  7944. pidCount++
  7945. planList1 = append(planList1, plan)
  7946. } else {
  7947. planList2 = append(planList2, plan)
  7948. }
  7949. }
  7950. planList1 = append(planList1, planList2...)
  7951. for i, plan := range planList1 {
  7952. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  7953. if err != nil {
  7954. logs.Error(err)
  7955. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  7956. tx.Rollback()
  7957. return
  7958. }
  7959. }
  7960. } else {
  7961. maxSortList, err := tx.SQL(`select max(d.sort) sort from downloadedplan d where d.mydate = ? and d.pid = (select pid from downloadedplan where sort = ? and mydate = ? ) `, mydate, sort, mydate).QueryString()
  7962. if err != nil {
  7963. logs.Error(err)
  7964. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7965. tx.Rollback()
  7966. return
  7967. }
  7968. var maxSort int
  7969. for _, sort := range maxSortList {
  7970. maxSort, _ = strconv.Atoi(sort["sort"])
  7971. }
  7972. planList := make([]*downloadedplan, 0)
  7973. err = tx.SQL(`select id,d.sort sort,d.pid from downloadedplan d where d.mydate = ? and sort <= ? order by sort`, mydate, maxSort).Find(&planList)
  7974. if err != nil {
  7975. logs.Error(err)
  7976. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  7977. tx.Rollback()
  7978. return
  7979. }
  7980. planPid := planInfo.Pid
  7981. planList1 := make([]*downloadedplan, 0)
  7982. planList2 := make([]*downloadedplan, 0)
  7983. for _, plan := range planList {
  7984. if plan.Pid == planPid {
  7985. // pidCount++
  7986. planList1 = append(planList1, plan)
  7987. } else {
  7988. planList2 = append(planList2, plan)
  7989. }
  7990. }
  7991. planList2 = append(planList2, planList1...)
  7992. for i, plan := range planList2 {
  7993. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  7994. if err != nil {
  7995. logs.Error(err)
  7996. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  7997. tx.Rollback()
  7998. return
  7999. }
  8000. }
  8001. }
  8002. err = tx.Commit()
  8003. if err != nil {
  8004. logs.Error(err)
  8005. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8006. tx.Rollback()
  8007. return
  8008. }
  8009. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8010. }
  8011. func EditDownloadedplanArtificial(c *gin.Context) {
  8012. appG := app.Gin{C: c}
  8013. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8014. fsions := gofasion.NewFasion(string(dataByte))
  8015. planIdStr := fsions.Get("planId").ValueStr()
  8016. tx := restful.Engine.NewSession()
  8017. defer tx.Close()
  8018. tx.Begin()
  8019. planIdList := strings.Split(planIdStr, ",")
  8020. for _, planId := range planIdList {
  8021. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? and havebutton != 1`, planId)
  8022. if err != nil {
  8023. logs.Error(err)
  8024. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8025. tx.Rollback()
  8026. return
  8027. }
  8028. }
  8029. err := tx.Commit()
  8030. if err != nil {
  8031. logs.Error(err)
  8032. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8033. tx.Rollback()
  8034. return
  8035. }
  8036. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8037. }
  8038. type PlanRFID struct {
  8039. RFID string `json:"RFID"`
  8040. Lweight string `json:"lweight"`
  8041. Gear string `json:"gear"`
  8042. Speed string `json:"speed"`
  8043. }
  8044. func GetPlanRFID(c *gin.Context) {
  8045. appG := app.Gin{C: c}
  8046. RFIDStr := c.Query("RFID")
  8047. planRFIDList := make([]*PlanRFID, 0)
  8048. planRFIDList = append(planRFIDList, &PlanRFID{
  8049. RFID: RFIDStr,
  8050. Lweight: "1411.1",
  8051. Gear: "1",
  8052. Speed: "10",
  8053. })
  8054. planRFIDList = append(planRFIDList, &PlanRFID{
  8055. RFID: RFIDStr,
  8056. Lweight: "1322.1",
  8057. Gear: "1",
  8058. Speed: "10",
  8059. })
  8060. planRFIDList = append(planRFIDList, &PlanRFID{
  8061. RFID: RFIDStr,
  8062. Lweight: "1904.1",
  8063. Gear: "1",
  8064. Speed: "10",
  8065. })
  8066. planRFIDList = append(planRFIDList, &PlanRFID{
  8067. RFID: RFIDStr,
  8068. Lweight: "1870.1",
  8069. Gear: "1",
  8070. Speed: "10",
  8071. })
  8072. planRFIDList = append(planRFIDList, &PlanRFID{
  8073. RFID: RFIDStr,
  8074. Lweight: "2041.1",
  8075. Gear: "1",
  8076. Speed: "10",
  8077. })
  8078. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  8079. }
  8080. type tmrEquipmentMuster struct {
  8081. A string
  8082. N string
  8083. }
  8084. func GetTmrEquipmentMuster(c *gin.Context) {
  8085. appG := app.Gin{C: c}
  8086. id := c.Query("id")
  8087. tx := restful.Engine.NewSession()
  8088. defer tx.Close()
  8089. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  8090. if err != nil {
  8091. logs.Error(err)
  8092. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8093. return
  8094. }
  8095. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  8096. for _, data := range dataList {
  8097. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  8098. for _, g := range tmrEquipmentMusterList {
  8099. a, _ := strconv.ParseFloat(g.A, 64)
  8100. n, _ := strconv.ParseFloat(g.N, 64)
  8101. a1, n1 := ddmmtoddd(a, n)
  8102. g.A = fmt.Sprintf("%f", n1)
  8103. g.N = fmt.Sprintf("%f", a1)
  8104. }
  8105. }
  8106. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  8107. }
  8108. func ddmmtoddd(lng, lat float64) (float64, float64) {
  8109. lngDegree := fmt.Sprintf("%f", lng/100)
  8110. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  8111. lngDegreeInt := int(lngDegreefloat * 1000000)
  8112. dd := lngDegreeInt / 100 * 100 / 60
  8113. fmt.Println(dd)
  8114. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  8115. latDegree := fmt.Sprintf("%f", lat/100)
  8116. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  8117. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  8118. latDegreeInt := int(latDegreefloat * 1000000)
  8119. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  8120. a, _ := strconv.ParseFloat(lngStr, 64)
  8121. b, _ := strconv.ParseFloat(latStr, 64)
  8122. return coordtransform.WGS84toGCJ02(b, a)
  8123. }