ops.go 289 KB

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