ops.go 331 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "os"
  12. "path"
  13. "regexp"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. "tmr-watch/conf/setting"
  20. "tmr-watch/http/handle/gm"
  21. "tmr-watch/http/handle/restful"
  22. "tmr-watch/module"
  23. "tmr-watch/pkg/app"
  24. "tmr-watch/pkg/e"
  25. "tmr-watch/pkg/logging"
  26. "github.com/360EntSecGroup-Skylar/excelize"
  27. "github.com/Anderson-Lu/gofasion/gofasion"
  28. "github.com/astaxie/beego/logs"
  29. "github.com/gin-gonic/gin"
  30. "github.com/qichengzx/coordtransform"
  31. "github.com/tealeg/xlsx"
  32. "github.com/xormplus/xorm"
  33. )
  34. // @Summary 根据SQL执行得到数据集
  35. // @Tags getData
  36. // @Accept json
  37. // @Produce json
  38. // @Param sql query string true "sql"
  39. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  40. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  41. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  42. // @Router /data/getdata [POST]
  43. func GetData(c *gin.Context) {
  44. appG := app.Gin{C: c}
  45. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  46. fsion := gofasion.NewFasion(string(dataByte))
  47. sqlstr := fsion.Get("sql").ValueStr()
  48. offset := fsion.Get("offset").ValueDefaultInt(0)
  49. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  50. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  51. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  52. if err != nil {
  53. appG.Response(http.StatusOK, e.ERROR, err.Error())
  54. } else {
  55. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  56. }
  57. }
  58. func Testpartitions(c *gin.Context) {
  59. appG := app.Gin{C: c}
  60. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  61. fsion := gofasion.NewFasion(string(dataByte))
  62. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  63. user := fsion.Get("user").ValueStr() //获取新数据库用户
  64. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  65. host := fsion.Get("host").ValueStr() //获取新数据库名称
  66. port := fsion.Get("port").ValueStr() //获取新数据库名称
  67. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  68. if sqls == nil || err1 != nil {
  69. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  70. }
  71. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  72. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  73. mydb, err := sql.Open("mysql", connecting) //连接新连接
  74. if err != nil {
  75. println("err1", err.Error())
  76. }
  77. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  78. if err != nil {
  79. println("err2", err.Error())
  80. }
  81. mydb.Close()
  82. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  83. mydb, err = sql.Open("mysql", connecting)
  84. if err != nil {
  85. println("err3", err.Error())
  86. }
  87. defer mydb.Close()
  88. if err == nil {
  89. mydb.SetMaxOpenConns(10)
  90. mydb.SetMaxIdleConns(10)
  91. }
  92. errmsg := ""
  93. if err == nil {
  94. //tx ,_ :=mydb.Begin()
  95. for _, sqlstr := range sqlstrs {
  96. //println("sqlstr---",sqlstr)
  97. if sqlstr == "" {
  98. continue
  99. }
  100. _, err = mydb.Exec(sqlstr)
  101. if err != nil {
  102. println("err4", err.Error())
  103. errmsg = err.Error()
  104. //err1 :=tx.Rollback()
  105. }
  106. }
  107. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  108. //err =tx.Commit()
  109. }
  110. if errmsg == "" {
  111. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  112. } else {
  113. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  114. }
  115. }
  116. func TestData(c *gin.Context) {
  117. appG := app.Gin{C: c}
  118. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  119. fsion := gofasion.NewFasion(string(dataByte))
  120. sqlstr := fsion.Get("sql").ValueStr()
  121. token := ""
  122. if tempv, exists := c.Get("jwt_username"); exists {
  123. token = tempv.(string)
  124. }
  125. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  126. }
  127. // @Summary 根据APISQL表中SQL执行得到数据集
  128. // @Tags GetDataByName
  129. // @Accept json
  130. // @Produce json
  131. // @Param sqlname body string true "sqlname"
  132. // @Param offset body int true "offset"
  133. // @Param pagecount body int true "pagecount"
  134. // @Param returntype body string true "returntype"
  135. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  136. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  137. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  138. // @Router /data/GetDataByName [POST]
  139. func GetDataByName(c *gin.Context) {
  140. appG := app.Gin{C: c}
  141. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  142. fsion := gofasion.NewFasion(string(dataByte))
  143. sqlnamestr := fsion.Get("name").ValueStr()
  144. offset := fsion.Get("offset").ValueDefaultInt(0)
  145. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  146. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  147. tx := restful.Engine.NewSession()
  148. err := tx.Begin()
  149. defer func() {
  150. switch {
  151. case err != nil:
  152. logging.Error("tx.Begin 事务启动失败__error:", err)
  153. if tx != nil {
  154. tx.Rollback()
  155. }
  156. default:
  157. if tx != nil {
  158. err = tx.Commit()
  159. }
  160. }
  161. if tx != nil {
  162. tx.Close()
  163. }
  164. }()
  165. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  166. if sql != "" {
  167. s_params := make([]interface{}, 0)
  168. if fsion.HasKey("parammaps") {
  169. parammaps := fsion.Get("parammaps")
  170. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  171. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  172. }
  173. paramslist := strings.Split(p, ",")
  174. if len(paramslist) > 0 && p != "" {
  175. for _, value := range paramslist {
  176. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  177. if tempv, exists := c.Get("jwt_username"); exists {
  178. s_params = append(s_params, tempv.(string))
  179. } else {
  180. s_params = append(s_params, "")
  181. }
  182. } else {
  183. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  184. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  185. // tmrNameList := []string{}
  186. // for _, tmr := range tmrArray {
  187. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  188. // }
  189. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  190. // } else {
  191. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  192. // }
  193. }
  194. }
  195. }
  196. } else if fsion.HasKey("params") {
  197. params := fsion.Get("params").Array()
  198. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  199. for _, v_params := range params {
  200. s_params = append(s_params, v_params.ValueStr())
  201. }
  202. }
  203. if returntype == "xlsx" {
  204. var xlsxfile *xlsx.File
  205. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  206. //c.File("c:/dd.xlsx")
  207. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  208. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  209. c.Header("Content-Transfer-Encoding", "binary")
  210. _ = xlsxfile.Write(c.Writer)
  211. } else {
  212. if sqlnamestr == "getHomepageStr" {
  213. parammaps := fsion.Get("parammaps")
  214. pastureid := parammaps.Get("pastureid").ValueStr()
  215. var montimeList []float64
  216. var montime float64
  217. var wg sync.WaitGroup
  218. now := time.Now()
  219. for i := 0; i < 30; i++ {
  220. wg.Add(1)
  221. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  222. go func(nowstr string) {
  223. defer wg.Done()
  224. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  225. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  226. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  227. montimeList = append(montimeList, m)
  228. }(nowstr)
  229. }
  230. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  231. if err != nil {
  232. logging.Error("GetDataByName err: ", err)
  233. msg := geterrmsg(err.Error())
  234. appG.Response(http.StatusOK, e.ERROR, msg)
  235. }
  236. wg.Wait()
  237. for _, m := range montimeList {
  238. montime += m
  239. }
  240. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  241. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  242. return
  243. }
  244. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  245. if err != nil {
  246. logging.Error("GetDataByName err: ", err)
  247. msg := geterrmsg(err.Error())
  248. appG.Response(http.StatusOK, e.ERROR, msg)
  249. } else {
  250. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  251. }
  252. }
  253. } else {
  254. appG.Response(http.StatusOK, e.SUCCESS, nil)
  255. }
  256. }
  257. // @Summary 根据APISQL表中SQL执行得到数据集
  258. // @Tags GetDataByName
  259. // @Accept json
  260. // @Produce json
  261. // @Param sqlname body string true "sqlname"
  262. // @Param offset body int true "offset"
  263. // @Param pagecount body int true "pagecount"
  264. // @Param returntype body string true "returntype"
  265. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  266. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  267. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  268. // @Router /data/GetDataByName [POST]
  269. func GetDataBySqlIN(c *gin.Context) {
  270. appG := app.Gin{C: c}
  271. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  272. fsion := gofasion.NewFasion(string(dataByte))
  273. sqlnamestr := fsion.Get("name").ValueStr()
  274. offset := fsion.Get("offset").ValueDefaultInt(0)
  275. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  276. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  277. tx := restful.Engine.NewSession()
  278. err := tx.Begin()
  279. defer func() {
  280. switch {
  281. case err != nil:
  282. logging.Error("tx.Begin 事务启动失败__error:", err)
  283. if tx != nil {
  284. tx.Rollback()
  285. }
  286. default:
  287. if tx != nil {
  288. err = tx.Commit()
  289. }
  290. }
  291. if tx != nil {
  292. tx.Close()
  293. }
  294. }()
  295. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  296. if sql != "" {
  297. s_params := make([]interface{}, 0)
  298. if fsion.HasKey("parammaps") {
  299. parammaps := fsion.Get("parammaps")
  300. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  301. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  302. }
  303. paramslist := strings.Split(p, ",")
  304. if len(paramslist) > 0 && p != "" {
  305. for _, value := range paramslist {
  306. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  307. if tempv, exists := c.Get("jwt_username"); exists {
  308. s_params = append(s_params, tempv.(string))
  309. } else {
  310. s_params = append(s_params, "")
  311. }
  312. } else {
  313. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  314. }
  315. }
  316. }
  317. } else if fsion.HasKey("params") {
  318. params := fsion.Get("params").Array()
  319. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  320. for _, v_params := range params {
  321. s_params = append(s_params, v_params.ValueStr())
  322. }
  323. }
  324. if returntype == "xlsx" {
  325. var xlsxfile *xlsx.File
  326. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  327. //c.File("c:/dd.xlsx")
  328. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  329. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  330. c.Header("Content-Transfer-Encoding", "binary")
  331. _ = xlsxfile.Write(c.Writer)
  332. } else {
  333. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  334. if err != nil {
  335. logging.Error("GetDataByName err: ", err)
  336. msg := geterrmsg(err.Error())
  337. appG.Response(http.StatusOK, e.ERROR, msg)
  338. } else {
  339. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  340. }
  341. }
  342. } else {
  343. appG.Response(http.StatusOK, e.SUCCESS, nil)
  344. }
  345. }
  346. // 错误处理
  347. // 将报错信息处理成汉字
  348. func geterrmsg(errstr string) (msgstr string) {
  349. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  350. rs := []rune(errstr)
  351. if hzRegexp.MatchString(string(rs[0])) {
  352. msgstr = errstr
  353. return
  354. }
  355. if strings.Contains(errstr, "Duplicate entry") {
  356. strs := strings.Split(errstr, ` key '`)
  357. if len(strs) > 1 {
  358. if len(strs[len(strs)-1]) > 1 {
  359. errstr = "Duplicate entry :" + strs[len(strs)-1]
  360. }
  361. }
  362. }
  363. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  364. if err != nil {
  365. msgstr = errstr
  366. return
  367. }
  368. if msg == nil || len(msg) == 0 {
  369. var param []interface{}
  370. param = append(param, errstr, errstr)
  371. go func() {
  372. tx := restful.Engine.NewSession()
  373. err := tx.Begin()
  374. defer func() {
  375. switch {
  376. case err != nil:
  377. logging.Error("tx.Begin 事务启动失败__error:", err)
  378. if tx != nil {
  379. tx.Rollback()
  380. }
  381. default:
  382. if tx != nil {
  383. err = tx.Commit()
  384. }
  385. }
  386. if tx != nil {
  387. tx.Close()
  388. }
  389. }()
  390. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  391. if err != nil {
  392. logging.Error("insert into err_msg(err,msg) err", err)
  393. }
  394. }()
  395. msgstr = errstr
  396. } else {
  397. msgstr = msg[0]["msg"]
  398. }
  399. return
  400. }
  401. // @Summary 根据APISQL表中SQL执行得到数据集
  402. // @Tags GetDataByNameForm
  403. // @Accept json
  404. // @Produce json
  405. // @Param sqlname body json true "sqlname"
  406. // @Param offset query int true "offset"
  407. // @Param pagecount query int true "pagecount"
  408. // @Param returntype query string true "returntype"
  409. // @Param s formData json true "ss"
  410. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  411. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  412. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  413. // @Router /data/GetDataByNameForm [POST]
  414. func GetDataByNameForm(c *gin.Context) {
  415. appG := app.Gin{C: c}
  416. //sqlnamestr := c.PostForm("measureNumber")
  417. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  418. //fsion := gofasion.NewFasion(string(dataByte))
  419. //sqlnamestr := fsion.Get("name").ValueStr()
  420. //offset := fsion.Get("offset").ValueInt()
  421. //pagecount := fsion.Get("pagecount").ValueInt()
  422. //returntype := fsion.Get("returntype").ValueStr()
  423. //params := fsion.Get("params").Array()
  424. c.Request.ParseForm()
  425. params := c.Request.Form
  426. offset := 0
  427. pageSize_ := 0
  428. returntype := params.Get("page")
  429. if returntype == "" {
  430. returntype = "0"
  431. }
  432. if tempv, exists := c.Get("jwt_username"); exists {
  433. params.Set("JwtUserName", tempv.(string))
  434. } else {
  435. params.Set("JwtUserName", "")
  436. }
  437. sqlnamestr := params.Get("name")
  438. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  439. s_params := make([]interface{}, 0)
  440. if returntype == "1" {
  441. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  442. if error != nil {
  443. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  444. }
  445. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  446. if error != nil {
  447. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  448. }
  449. pageSize_ = pageSize
  450. offset = pageNum
  451. }
  452. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  453. paramslist := strings.Split(p, ",")
  454. if len(paramslist) > 0 && p != "" {
  455. for _, value := range paramslist {
  456. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  457. }
  458. }
  459. if sql != "" {
  460. if returntype == "xlsx" {
  461. var xlsxfile *xlsx.File
  462. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  463. c.Header("Content-Type", "application/octet-stream")
  464. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  465. c.Header("Content-Transfer-Encoding", "binary")
  466. _ = xlsxfile.Write(c.Writer)
  467. } else {
  468. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  469. if err != nil {
  470. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  471. } else {
  472. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  473. }
  474. }
  475. } else {
  476. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  477. }
  478. }
  479. // @Summary 递归获取所有
  480. // @Tags menu
  481. // @Accept json
  482. // @Produce json
  483. // @Param Ton query string true "Ton"
  484. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  485. // @Router /authdata/GetRoleMenus [GET]
  486. func GetRecuDataByName(c *gin.Context) {
  487. appG := app.Gin{C: c}
  488. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  489. fsion := gofasion.NewFasion(string(dataByte))
  490. sqlnamestr := fsion.Get("name").ValueStr()
  491. parentidname := fsion.Get("idname").ValueStr()
  492. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  493. params := make(map[string]interface{})
  494. s_params := make([]interface{}, 0)
  495. if fsion.HasKey("params") {
  496. for _, v_params := range fsion.Get("params").Array() {
  497. s_params = append(s_params, v_params.ValueStr())
  498. }
  499. params["params"] = s_params
  500. } else {
  501. jparams := fsion.Get("parammaps")
  502. paramslist := strings.Split(p, ",")
  503. if len(paramslist) > 0 && p != "" {
  504. for _, value := range paramslist {
  505. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  506. if tempv, exists := c.Get("jwt_username"); exists {
  507. params[value] = tempv.(string)
  508. } else {
  509. params[value] = ""
  510. }
  511. } else {
  512. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  513. }
  514. }
  515. }
  516. }
  517. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  518. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  519. if err != nil {
  520. appG.Response(http.StatusOK, e.ERROR, err.Error())
  521. }
  522. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  523. }
  524. // @Summary 根据APISQL表中SQL执行得到数据集
  525. // @Tags GetDataByNames
  526. // @Accept json
  527. // @Produce json
  528. // @RequestBody sqlname query string true "sqlname"
  529. // @Param offset query int true "offset"
  530. // @Param pagecount query int true "pagecount"
  531. // @Param returntype query string true "returntype"
  532. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  533. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  534. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  535. // @Router /data/GetDataByNames [POST]
  536. func GetDataByNames(c *gin.Context) {
  537. appG := app.Gin{C: c}
  538. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  539. fsion := gofasion.NewFasion(string(dataByte))
  540. sqlParams := fsion.Array()
  541. queryData := make(map[string]interface{})
  542. for _, v := range sqlParams {
  543. fsion2 := gofasion.NewFasion(v.Json())
  544. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  545. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  546. if sql == "" {
  547. errorm := make(map[string]interface{})
  548. errorm["code"] = e.ERROR
  549. errorm["message"] = "sql没找到"
  550. queryData[fsion2.Get("name").ValueStr()] = errorm
  551. continue
  552. } else if sql != "" {
  553. offset := fsion2.Get("offset").ValueInt()
  554. pagecount := fsion2.Get("pagecount").ValueInt()
  555. returntype := fsion2.Get("returntype").ValueStr()
  556. s_params := make([]interface{}, 0)
  557. if fsion2.HasKey("parammaps") {
  558. parammaps := fsion2.Get("parammaps")
  559. paramslist := strings.Split(p, ",")
  560. if len(paramslist) > 0 && p != "" {
  561. for _, value := range paramslist {
  562. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  563. if tempv, exists := c.Get("jwt_username"); exists {
  564. s_params = append(s_params, tempv.(string))
  565. } else {
  566. s_params = append(s_params, "")
  567. }
  568. } else {
  569. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  570. }
  571. }
  572. }
  573. } else if fsion2.HasKey("params") {
  574. params := fsion2.Get("params").Array()
  575. for _, v_params := range params {
  576. s_params = append(s_params, v_params.ValueStr())
  577. }
  578. }
  579. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  580. if err != nil {
  581. errorm := make(map[string]interface{})
  582. errorm["code"] = e.ERROR
  583. errorm["message"] = err.Error()
  584. queryData[fsion2.Get("name").ValueStr()] = errorm
  585. logging.Error("GetDataByNames err: ", err)
  586. continue
  587. } else {
  588. queryData[fsion2.Get("name").ValueStr()] = queryData1
  589. }
  590. }
  591. }
  592. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  593. }
  594. // @Summary 根据APISQL表中SQL执行得到数据集
  595. // @Tags PostDataByNameForm
  596. // @Accept json
  597. // @Produce json
  598. // @Param sqlname query string true "sqlname"
  599. // @Param offset query int true "offset"
  600. // @Param pagecount query int true "pagecount"
  601. // @Param returntype query string true "returntype"
  602. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  603. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  604. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  605. // @Router /data/PostDataByNameForm [POST]
  606. func PostDataByNameForm(c *gin.Context) {
  607. appG := app.Gin{C: c}
  608. c.Request.ParseForm()
  609. params := c.Request.Form
  610. sqlnamestr := params.Get("name")
  611. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  612. s_params := make([]interface{}, 0)
  613. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  614. paramslist := strings.Split(p, ",")
  615. if len(paramslist) > 0 {
  616. for _, value := range paramslist {
  617. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  618. }
  619. }
  620. if sql != "" {
  621. queryData, err := execDataBySql(sql, s_params)
  622. if err != nil {
  623. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  624. } else {
  625. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  626. }
  627. } else {
  628. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  629. }
  630. }
  631. // GetReportform 将数据集转换格式
  632. // @Tags PostDataByNameForm
  633. // @Accept json
  634. // @Produce json
  635. // @Param sqlname query string true "sqlname"
  636. // @Param offset query int true "offset"
  637. // @Param pagecount query int true "pagecount"
  638. // @Param returntype query string true "returntype"
  639. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  640. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  641. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  642. func GetReportform(c *gin.Context) {
  643. appG := app.Gin{C: c}
  644. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  645. fsion := gofasion.NewFasion(string(dataByte))
  646. sqlnamestr := fsion.Get("name").ValueStr()
  647. checked := fsion.Get("checked").ValueStr()
  648. offset := fsion.Get("offset").ValueDefaultInt(0)
  649. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  650. parammaps := fsion.Get("parammaps")
  651. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  652. mode := parammaps.Get("mode").ValueDefaultInt(0)
  653. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  654. tx := restful.Engine.NewSession()
  655. err := tx.Begin()
  656. defer func() {
  657. switch {
  658. case err != nil:
  659. if tx != nil {
  660. tx.Rollback()
  661. }
  662. default:
  663. if tx != nil {
  664. err = tx.Commit()
  665. }
  666. }
  667. if tx != nil {
  668. tx.Close()
  669. }
  670. }()
  671. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  672. if err != nil {
  673. appG.Response(http.StatusOK, e.ERROR, err.Error())
  674. } else {
  675. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  676. }
  677. }
  678. // GetUpkeepPlan 保养计划
  679. func GetUpkeepPlan(c *gin.Context) {
  680. appG := app.Gin{C: c}
  681. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  682. fsion := gofasion.NewFasion(string(dataByte))
  683. sqlnamestr := fsion.Get("name").ValueStr()
  684. offset := fsion.Get("offset").ValueDefaultInt(0)
  685. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  686. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  687. month := fsion.Get("month").ValueDefaultStr("map")
  688. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  689. tx := restful.Engine.NewSession()
  690. err := tx.Begin()
  691. defer func() {
  692. switch {
  693. case err != nil:
  694. if tx != nil {
  695. tx.Rollback()
  696. }
  697. default:
  698. if tx != nil {
  699. err = tx.Commit()
  700. }
  701. }
  702. if tx != nil {
  703. tx.Close()
  704. }
  705. }()
  706. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  707. if sql != "" {
  708. s_params := make([]interface{}, 0)
  709. if fsion.HasKey("parammaps") {
  710. parammaps := fsion.Get("parammaps")
  711. paramslist := strings.Split(p, ",")
  712. if len(paramslist) > 0 && p != "" {
  713. for _, value := range paramslist {
  714. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  715. if tempv, exists := c.Get("jwt_username"); exists {
  716. s_params = append(s_params, tempv.(string))
  717. } else {
  718. s_params = append(s_params, "")
  719. }
  720. } else {
  721. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  722. }
  723. }
  724. }
  725. } else if fsion.HasKey("params") {
  726. params := fsion.Get("params").Array()
  727. for _, v_params := range params {
  728. s_params = append(s_params, v_params.ValueStr())
  729. }
  730. }
  731. if returntype == "xlsx" {
  732. var xlsxfile *xlsx.File
  733. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  734. //c.File("c:/dd.xlsx")
  735. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  736. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  737. c.Header("Content-Transfer-Encoding", "binary")
  738. _ = xlsxfile.Write(c.Writer)
  739. } else {
  740. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  741. if err != nil {
  742. appG.Response(http.StatusOK, e.ERROR, err.Error())
  743. } else {
  744. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  745. if v, ok := value["id"]; ok {
  746. //month = "2020-03"
  747. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  748. if seviceplans != nil {
  749. for _, va := range seviceplans { //根据保养计划获取保养单
  750. //day,_ :=strconv.Atoi(va["day"])
  751. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  752. //buk := make(map[string]map[string]string)
  753. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  754. jstr := ""
  755. if bu["plantime"][8:9] == "0" {
  756. jstr = "m" + bu["plantime"][9:]
  757. } else {
  758. jstr = "m" + bu["plantime"][8:]
  759. }
  760. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  761. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  762. } else {
  763. if bu["flowCompeleted"] >= "2" {
  764. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  765. } else {
  766. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  767. }
  768. }
  769. }
  770. }
  771. }
  772. }
  773. }
  774. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  775. }
  776. }
  777. } else {
  778. appG.Response(http.StatusOK, e.SUCCESS, nil)
  779. }
  780. }
  781. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  782. // todo 优化性能 children统一查询
  783. // @Tags PostDataByNameForm
  784. // @Accept json
  785. // @Produce json
  786. // @Param sqlname query string true "sqlname"
  787. // @Param offset query int true "offset"
  788. // @Param pagecount query int true "pagecount"
  789. // @Param returntype query string true "returntype"
  790. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  791. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  792. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  793. func GetArrList(c *gin.Context) {
  794. appG := app.Gin{C: c}
  795. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  796. fsion := gofasion.NewFasion(string(dataByte))
  797. sqlnamestr := fsion.Get("name").ValueStr()
  798. sqlnamestr1 := fsion.Get("name1").ValueStr()
  799. offset := fsion.Get("offset").ValueDefaultInt(0)
  800. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  801. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  802. month := fsion.Get("month").ValueDefaultStr("map")
  803. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  804. tx := restful.Engine.NewSession()
  805. err := tx.Begin()
  806. defer func() {
  807. switch {
  808. case err != nil:
  809. if tx != nil {
  810. tx.Rollback()
  811. }
  812. default:
  813. if tx != nil {
  814. err = tx.Commit()
  815. }
  816. }
  817. if tx != nil {
  818. tx.Close()
  819. }
  820. }()
  821. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  822. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  823. if sql != "" {
  824. s_params := make([]interface{}, 0)
  825. if fsion.HasKey("parammaps") {
  826. parammaps := fsion.Get("parammaps")
  827. paramslist := strings.Split(p, ",")
  828. if len(paramslist) > 0 && p != "" {
  829. for _, value := range paramslist {
  830. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  831. if tempv, exists := c.Get("jwt_username"); exists {
  832. s_params = append(s_params, tempv.(string))
  833. } else {
  834. s_params = append(s_params, "")
  835. }
  836. } else {
  837. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  838. }
  839. }
  840. }
  841. }
  842. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  843. if err != nil {
  844. appG.Response(http.StatusOK, e.ERROR, err.Error())
  845. } else {
  846. paramslist1 := strings.Split(p1, ",")
  847. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  848. s_params1 := make([]interface{}, 0)
  849. if len(paramslist1) > 0 && p1 != "" {
  850. for _, v := range paramslist1 {
  851. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  852. }
  853. }
  854. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  855. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  856. }
  857. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  858. }
  859. } else {
  860. appG.Response(http.StatusOK, e.SUCCESS, nil)
  861. }
  862. }
  863. func GetAccount(c *gin.Context) {
  864. appG := app.Gin{C: c}
  865. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  866. fsion := gofasion.NewFasion(string(dataByte))
  867. sqlnamestr := fsion.Get("name").ValueStr()
  868. offset := fsion.Get("offset").ValueDefaultInt(0)
  869. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  870. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  871. tx := restful.Engine.NewSession()
  872. err := tx.Begin()
  873. defer func() {
  874. switch {
  875. case err != nil:
  876. logging.Error("tx.Begin 事务启动失败__error:", err)
  877. if tx != nil {
  878. tx.Rollback()
  879. }
  880. default:
  881. if tx != nil {
  882. err = tx.Commit()
  883. }
  884. }
  885. if tx != nil {
  886. tx.Close()
  887. }
  888. }()
  889. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  890. if sql != "" {
  891. s_params := make([]interface{}, 0)
  892. if fsion.HasKey("parammaps") {
  893. parammaps := fsion.Get("parammaps")
  894. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  895. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  896. }
  897. paramslist := strings.Split(p, ",")
  898. if len(paramslist) > 0 && p != "" {
  899. for _, value := range paramslist {
  900. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  901. if tempv, exists := c.Get("jwt_username"); exists {
  902. s_params = append(s_params, tempv.(string))
  903. } else {
  904. s_params = append(s_params, "")
  905. }
  906. } else {
  907. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  908. }
  909. }
  910. }
  911. } else if fsion.HasKey("params") {
  912. params := fsion.Get("params").Array()
  913. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  914. for _, v_params := range params {
  915. s_params = append(s_params, v_params.ValueStr())
  916. }
  917. }
  918. if returntype == "xlsx" {
  919. var xlsxfile *xlsx.File
  920. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  921. //c.File("c:/dd.xlsx")
  922. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  923. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  924. c.Header("Content-Transfer-Encoding", "binary")
  925. _ = xlsxfile.Write(c.Writer)
  926. } else {
  927. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  928. if err != nil {
  929. logging.Error("GetDataByName err: ", err)
  930. msg := geterrmsg(err.Error())
  931. appG.Response(http.StatusOK, e.ERROR, msg)
  932. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  933. } else {
  934. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  935. }
  936. }
  937. } else {
  938. appG.Response(http.StatusOK, e.SUCCESS, nil)
  939. }
  940. }
  941. // PostDataByName 根据APISQL表中SQL执行得到数据集
  942. // @Accept json
  943. // @Produce json
  944. // @Param sqlname query string true "sqlname"
  945. // @Param offset query int true "offset"
  946. // @Param pagecount query int true "pagecount"
  947. // @Param returntype query string true "returntype"
  948. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  949. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  950. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  951. // @Router /data/PostDataByName [POST]
  952. func PostDataByName(c *gin.Context) {
  953. appG := app.Gin{C: c}
  954. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  955. fsion := gofasion.NewFasion(string(dataByte))
  956. var err error
  957. queryData, err := module.PostDataByName(c, fsion)
  958. if err != nil {
  959. appG.Response(http.StatusOK, e.ERROR, err.Error())
  960. return
  961. }
  962. var (
  963. keyWord string
  964. )
  965. switch fsion.Get("name").ValueStr() {
  966. case "insertFeedclass":
  967. keyWord = "feed"
  968. err = module.GroupCategorySync(keyWord, fsion)
  969. case "deleteFeedclass":
  970. keyWord = "feed_delete"
  971. err = module.GroupCategoryDelete(keyWord, fsion)
  972. case "insertCowclass":
  973. keyWord = "cow"
  974. err = module.GroupCategorySync(keyWord, fsion)
  975. case "deleteCowclass":
  976. keyWord = "cow_delete"
  977. err = module.GroupCategoryDelete(keyWord, fsion)
  978. // case "updateFT":
  979. // FtdetailSurplus(fsion)
  980. // case "updateFeed":
  981. // FeedSurplus(fsion)
  982. default:
  983. }
  984. if err != nil {
  985. logging.Error(keyWord, err)
  986. }
  987. if queryData != nil {
  988. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  989. return
  990. }
  991. appG.Response(http.StatusOK, e.SUCCESS, nil)
  992. }
  993. //人脸识别/格润富德接口
  994. func GetRJSBData(c *gin.Context) {
  995. appG := app.Gin{C: c}
  996. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  997. fsion := gofasion.NewFasion(string(dataByte))
  998. sqlnamestr := fsion.Get("name").ValueStr()
  999. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1000. offset := fsion.Get("offset").ValueDefaultInt(0)
  1001. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1002. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1003. month := fsion.Get("month").ValueDefaultStr("map")
  1004. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1005. tx := restful.Engine.NewSession()
  1006. err := tx.Begin()
  1007. defer func() {
  1008. switch {
  1009. case err != nil:
  1010. if tx != nil {
  1011. tx.Rollback()
  1012. }
  1013. default:
  1014. if tx != nil {
  1015. err = tx.Commit()
  1016. }
  1017. }
  1018. if tx != nil {
  1019. tx.Close()
  1020. }
  1021. }()
  1022. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1023. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1024. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1025. if sql != "" {
  1026. s_params := make([]interface{}, 0)
  1027. if fsion.HasKey("parammaps") {
  1028. parammaps := fsion.Get("parammaps")
  1029. paramslist := strings.Split(p, ",")
  1030. if len(paramslist) > 0 && p != "" {
  1031. for _, value := range paramslist {
  1032. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1033. if tempv, exists := c.Get("jwt_username"); exists {
  1034. s_params = append(s_params, tempv.(string))
  1035. } else {
  1036. s_params = append(s_params, "")
  1037. }
  1038. } else {
  1039. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1040. }
  1041. }
  1042. }
  1043. }
  1044. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1045. if err != nil {
  1046. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1047. } else {
  1048. paramslist1 := strings.Split(p1, ",")
  1049. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1050. s_params1 := make([]interface{}, 0)
  1051. if len(paramslist1) > 0 && p1 != "" {
  1052. for _, v := range paramslist1 {
  1053. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1054. }
  1055. }
  1056. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1057. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1058. }
  1059. var wg sync.WaitGroup
  1060. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1061. wg.Add(1)
  1062. go func(value map[string]interface{}) {
  1063. defer wg.Done()
  1064. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1065. }(value)
  1066. }
  1067. wg.Wait()
  1068. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1069. }
  1070. } else {
  1071. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1072. }
  1073. }
  1074. func PostRJSBData(c *gin.Context) {
  1075. appG := app.Gin{C: c}
  1076. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1077. fsion := gofasion.NewFasion(string(dataByte))
  1078. logging.Info("PostRJSBData err: ", string(dataByte))
  1079. s_params := make([]interface{}, 0)
  1080. tx := restful.Engine.NewSession()
  1081. err := tx.Begin()
  1082. defer func() {
  1083. switch {
  1084. case err != nil:
  1085. if tx != nil {
  1086. tx.Rollback()
  1087. }
  1088. default:
  1089. if tx != nil {
  1090. err = tx.Commit()
  1091. }
  1092. }
  1093. if tx != nil {
  1094. tx.Close()
  1095. }
  1096. }()
  1097. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1098. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1099. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1100. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1101. if !fsion.HasKey("parammaps") {
  1102. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1103. return
  1104. }
  1105. parammaps := fsion.Get("parammaps")
  1106. paramslist := strings.Split(p, ",")
  1107. if len(paramslist) > 0 && p != "" {
  1108. for _, value := range paramslist {
  1109. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1110. }
  1111. }
  1112. _, err = tx.SQL(sql, s_params...).Execute()
  1113. if err != nil {
  1114. logging.Error("PostRJSBData err: ", err)
  1115. msg := geterrmsg(err.Error())
  1116. // appG.Response(http.StatusOK, e.ERROR, msg)
  1117. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1118. return
  1119. }
  1120. s_params = make([]interface{}, 0)
  1121. paramslist = strings.Split(p1, ",")
  1122. if len(paramslist) > 0 && p1 != "" {
  1123. for _, value := range paramslist {
  1124. // if value == "ID" {
  1125. // id := parammaps.Get("ID").ValueStr()
  1126. // pastureid := parammaps.Get("pastureid").ValueStr()
  1127. // 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
  1128. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1129. // if err != nil {
  1130. // logging.Error("PostRJSBData err: ", err)
  1131. // msg := geterrmsg(err.Error())
  1132. // appG.Response(http.StatusOK, e.ERROR, msg)
  1133. // return
  1134. // }
  1135. // for _, item := range datalist {
  1136. // id = item["id"]
  1137. // }
  1138. // s_params = append(s_params, id)
  1139. // } else {
  1140. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1141. // }
  1142. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1143. }
  1144. }
  1145. _, err = tx.SQL(sql1, s_params...).Execute()
  1146. if err != nil {
  1147. logging.Error("PostRJSBData1 err: ", err)
  1148. msg := geterrmsg(err.Error())
  1149. appG.Response(http.StatusOK, e.ERROR, msg)
  1150. return
  1151. }
  1152. s_params = make([]interface{}, 0)
  1153. paramslist = strings.Split(p2, ",")
  1154. if len(paramslist) > 0 && p2 != "" {
  1155. for _, value := range paramslist {
  1156. if value == "ID" {
  1157. id := parammaps.Get("ID").ValueStr()
  1158. pastureid := parammaps.Get("pastureid").ValueStr()
  1159. 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
  1160. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1161. if err != nil {
  1162. logging.Error("PostRJSBData err: ", err)
  1163. msg := geterrmsg(err.Error())
  1164. appG.Response(http.StatusOK, e.ERROR, msg)
  1165. return
  1166. }
  1167. for _, item := range datalist {
  1168. id = item["id"]
  1169. }
  1170. s_params = append(s_params, id)
  1171. } else {
  1172. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1173. }
  1174. }
  1175. }
  1176. _, err = tx.SQL(sql2, s_params...).Execute()
  1177. if err != nil {
  1178. logging.Error("PostRJSBData2 err: ", err)
  1179. msg := geterrmsg(err.Error())
  1180. appG.Response(http.StatusOK, e.ERROR, msg)
  1181. return
  1182. }
  1183. s_params = make([]interface{}, 0)
  1184. paramslist = strings.Split(p3, ",")
  1185. if len(paramslist) > 0 && p3 != "" {
  1186. for _, value := range paramslist {
  1187. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1188. }
  1189. }
  1190. _, err = tx.SQL(sql3, s_params...).Execute()
  1191. if err != nil {
  1192. logging.Error("PostRJSBData3 err: ", err)
  1193. msg := geterrmsg(err.Error())
  1194. appG.Response(http.StatusOK, e.ERROR, msg)
  1195. return
  1196. }
  1197. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1198. }
  1199. func PostRJSBDatas(c *gin.Context) {
  1200. appG := app.Gin{C: c}
  1201. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1202. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1203. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1204. tx := restful.Engine.NewSession()
  1205. err := tx.Begin()
  1206. defer func() {
  1207. switch {
  1208. case err != nil:
  1209. if tx != nil {
  1210. tx.Rollback()
  1211. }
  1212. default:
  1213. if tx != nil {
  1214. err = tx.Commit()
  1215. }
  1216. }
  1217. if tx != nil {
  1218. tx.Close()
  1219. }
  1220. }()
  1221. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1222. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1223. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1224. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1225. for _, fsion := range fsions {
  1226. if !fsion.HasKey("parammaps") {
  1227. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1228. return
  1229. }
  1230. parammaps := fsion.Get("parammaps")
  1231. ID := parammaps.Get("ID").ValueStr()
  1232. if ID == "" {
  1233. continue
  1234. }
  1235. s_params := make([]interface{}, 0)
  1236. paramslist := strings.Split(p, ",")
  1237. if len(paramslist) > 0 && p != "" {
  1238. for _, value := range paramslist {
  1239. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1240. }
  1241. }
  1242. _, err = tx.SQL(sql, s_params...).Execute()
  1243. if err != nil {
  1244. logging.Error("PostRJSBData err: ", err)
  1245. msg := geterrmsg(err.Error())
  1246. // appG.Response(http.StatusOK, e.ERROR, msg)
  1247. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1248. return
  1249. }
  1250. s_params = make([]interface{}, 0)
  1251. paramslist = strings.Split(p1, ",")
  1252. if len(paramslist) > 0 && p1 != "" {
  1253. for _, value := range paramslist {
  1254. // if value == "ID" {
  1255. // id := parammaps.Get("ID").ValueStr()
  1256. // pastureid := parammaps.Get("pastureid").ValueStr()
  1257. // 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
  1258. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1259. // if err != nil {
  1260. // logging.Error("PostRJSBData err: ", err)
  1261. // msg := geterrmsg(err.Error())
  1262. // appG.Response(http.StatusOK, e.ERROR, msg)
  1263. // return
  1264. // }
  1265. // for _, item := range datalist {
  1266. // id = item["id"]
  1267. // }
  1268. // s_params = append(s_params, id)
  1269. // } else {
  1270. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1271. // }
  1272. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1273. }
  1274. }
  1275. _, err = tx.SQL(sql1, s_params...).Execute()
  1276. if err != nil {
  1277. logging.Error("PostRJSBData1 err: ", err)
  1278. msg := geterrmsg(err.Error())
  1279. appG.Response(http.StatusOK, e.ERROR, msg)
  1280. return
  1281. }
  1282. s_params = make([]interface{}, 0)
  1283. paramslist = strings.Split(p2, ",")
  1284. if len(paramslist) > 0 && p2 != "" {
  1285. for _, value := range paramslist {
  1286. if value == "ID" {
  1287. id := parammaps.Get("ID").ValueStr()
  1288. pastureid := parammaps.Get("pastureid").ValueStr()
  1289. datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  1290. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1291. if err != nil {
  1292. logging.Error("PostRJSBData err: ", err)
  1293. msg := geterrmsg(err.Error())
  1294. appG.Response(http.StatusOK, e.ERROR, msg)
  1295. return
  1296. }
  1297. for _, item := range datalist {
  1298. id = item["id"]
  1299. }
  1300. s_params = append(s_params, id)
  1301. } else {
  1302. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1303. }
  1304. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1305. }
  1306. }
  1307. _, err = tx.SQL(sql2, s_params...).Execute()
  1308. if err != nil {
  1309. logging.Error("PostRJSBData2 err: ", err)
  1310. msg := geterrmsg(err.Error())
  1311. appG.Response(http.StatusOK, e.ERROR, msg)
  1312. return
  1313. }
  1314. s_params = make([]interface{}, 0)
  1315. paramslist = strings.Split(p3, ",")
  1316. if len(paramslist) > 0 && p3 != "" {
  1317. for _, value := range paramslist {
  1318. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1319. }
  1320. }
  1321. _, err = tx.SQL(sql3, s_params...).Execute()
  1322. if err != nil {
  1323. logging.Error("PostRJSBData3 err: ", err)
  1324. msg := geterrmsg(err.Error())
  1325. appG.Response(http.StatusOK, e.ERROR, msg)
  1326. return
  1327. }
  1328. }
  1329. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1330. }
  1331. // @Summary 根据APISQL表中SQL执行得到数据集
  1332. // @Tags ExecDataByConfig
  1333. // @Accept json
  1334. // @Produce json
  1335. // @Param sqlname query string true "sqlname"
  1336. // @Param offset query int true "offset"
  1337. // @Param pagecount query int true "pagecount"
  1338. // @Param returntype query string true "returntype"
  1339. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1340. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1341. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1342. // @Router /data/PostDataByName [POST]
  1343. func ExecDataByConfig(c *gin.Context) {
  1344. appG := app.Gin{C: c}
  1345. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1346. tempval_ := make(map[string]interface{})
  1347. tempCommon := make(map[string]interface{})
  1348. tempval := make([]map[string]interface{}, 0)
  1349. err := json.Unmarshal(dataByte, &tempval_)
  1350. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1351. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1352. if err != nil {
  1353. } else {
  1354. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1355. tempCommon = v
  1356. }
  1357. if v, ok := tempval_["data"].([]interface{}); ok {
  1358. for _, Tvalue := range v {
  1359. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1360. tempval = append(tempval, v1)
  1361. }
  1362. }
  1363. }
  1364. tx := restful.Engine.NewSession()
  1365. err := tx.Begin()
  1366. if err != nil {
  1367. logging.Error("tx.Begin 事务启动失败__error:", err)
  1368. }
  1369. defer func() {
  1370. switch {
  1371. case err != nil:
  1372. if tx != nil {
  1373. tx.Rollback()
  1374. }
  1375. default:
  1376. if tx != nil {
  1377. err = tx.Commit()
  1378. }
  1379. }
  1380. if tx != nil {
  1381. tx.Close()
  1382. }
  1383. }()
  1384. if err == nil {
  1385. if tempv, exists := c.Get("jwt_username"); exists {
  1386. tempCommon["jwt_username"] = tempv.(string)
  1387. }
  1388. for _, paramvalue := range tempval {
  1389. fmt.Println(paramvalue["name"])
  1390. if paramvalue["name"].(string) == "updateBigFP" {
  1391. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1392. if err != nil {
  1393. msg := geterrmsg(err.Error())
  1394. appG.Response(http.StatusOK, e.ERROR, msg)
  1395. return
  1396. }
  1397. }
  1398. }
  1399. for _, paramvalue := range tempval {
  1400. if _, ok := paramvalue["resultname"]; !ok {
  1401. paramvalue["resultname"] = paramvalue["name"]
  1402. }
  1403. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1404. if err != nil {
  1405. logging.Error("ExecDataParam error:", err)
  1406. break
  1407. }
  1408. if paramvalue["name"].(string) == "createdownloadedplan" {
  1409. checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1410. }
  1411. }
  1412. if err == nil {
  1413. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1414. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1415. } else {
  1416. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1417. }
  1418. } else {
  1419. msg := geterrmsg(err.Error())
  1420. appG.Response(http.StatusOK, e.ERROR, msg)
  1421. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1422. }
  1423. }
  1424. }
  1425. if err != nil {
  1426. msg := geterrmsg(err.Error())
  1427. appG.Response(http.StatusOK, e.ERROR, msg)
  1428. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1429. }
  1430. }
  1431. func interfacetostring(val interface{}) string {
  1432. switch val.(type) {
  1433. case string:
  1434. ss := val.(string)
  1435. return ss
  1436. break
  1437. case int:
  1438. ss := val.(int)
  1439. return strconv.Itoa(ss)
  1440. break
  1441. case int64:
  1442. ss := val.(int64)
  1443. return strconv.FormatInt(ss, 10)
  1444. break
  1445. case float64:
  1446. ss := val.(float64)
  1447. return strconv.FormatFloat(ss, 'E', -1, 32)
  1448. break
  1449. }
  1450. return ""
  1451. }
  1452. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1453. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1454. tempstrb := strings.IndexAny(valuestring, "@")
  1455. tempstre := strings.IndexAny(valuestring, ".")
  1456. if tempstrb > -1 && tempstre > -1 {
  1457. for _, ParamMapList := range ParamMap {
  1458. if v, ok := ParamMapList["resultname"]; ok {
  1459. if v == valuestring[tempstrb+1:tempstre] {
  1460. if v1, ok := ParamMapList["resultmaps"]; ok {
  1461. if newA, ok := v1.([]map[string]interface{}); ok {
  1462. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1463. } else if newA, ok := v1.(map[string]interface{}); ok {
  1464. return interfacetostring(newA[valuestring[tempstre+1:]])
  1465. }
  1466. }
  1467. }
  1468. }
  1469. }
  1470. } else {
  1471. return valuestring
  1472. }
  1473. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1474. return strconv.FormatInt(int64(valuestring), 10)
  1475. }
  1476. return ""
  1477. }
  1478. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1479. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1480. tempstrb := strings.IndexAny(valuestring, "@")
  1481. tempstre := strings.IndexAny(valuestring, ".")
  1482. if tempstrb > -1 && tempstre > -1 {
  1483. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1484. if s, ok := v.(string); ok {
  1485. return s
  1486. } else if s, ok := v.(float64); ok {
  1487. return strconv.FormatFloat(s, 'f', -1, 64)
  1488. // return strconv.FormatInt(int64(s), 10)
  1489. }
  1490. }
  1491. }
  1492. }
  1493. return ""
  1494. }
  1495. 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) {
  1496. sqlname := fasion["name"].(string)
  1497. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1498. if v, ok := fasion["type"]; ok {
  1499. sqltype = v.(string)
  1500. }
  1501. sql := ""
  1502. p := ""
  1503. s_params := make([]interface{}, 0)
  1504. if sqltype != "" {
  1505. sql, p = restful.GetSqlByName(sqlname, tx)
  1506. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1507. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1508. paramslist := strings.Split(p, ",")
  1509. if len(paramslist) > 0 && p != "" {
  1510. for _, value := range paramslist {
  1511. ss := ""
  1512. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1513. ids, err := setting.SnowIds.NextId()
  1514. if err != nil {
  1515. ids = time.Now().UnixNano()
  1516. logging.Info("create SnowIds err", err)
  1517. }
  1518. s_params = append(s_params, ids)
  1519. } else {
  1520. if ss == "" && CommonParamMap != nil {
  1521. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1522. ss = valuestring
  1523. tempstrb := strings.IndexAny(valuestring, "@")
  1524. tempstre := strings.IndexAny(valuestring, ".")
  1525. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1526. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1527. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1528. }
  1529. } else {
  1530. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1531. ss = ""
  1532. }
  1533. }
  1534. }
  1535. }
  1536. if ss == "" && ParentParamMap != nil {
  1537. ss = getParamValue_(v, value, ParentParamMap)
  1538. }
  1539. if ss == "" && sameParamMap != nil {
  1540. ss = getParamValue(v, value, sameParamMap)
  1541. }
  1542. if ss == "" && ParamMap != nil {
  1543. ss = getParamValue(v, value, ParamMap)
  1544. }
  1545. s_params = append(s_params, ss)
  1546. }
  1547. }
  1548. }
  1549. }
  1550. }
  1551. if sql == "" {
  1552. sqltype = ""
  1553. }
  1554. if sqltype == "s1" {
  1555. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1556. if v, ok := tempValParam.(map[string]interface{}); ok {
  1557. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1558. }
  1559. if err != nil {
  1560. return nil, err
  1561. }
  1562. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1563. if err != nil {
  1564. return nil, err
  1565. }
  1566. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1567. } else if sqltype == "sm" {
  1568. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1569. if v, ok := tempValParam.(map[string]interface{}); ok {
  1570. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1571. } else {
  1572. }
  1573. if err != nil {
  1574. return nil, err
  1575. }
  1576. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1577. if err != nil {
  1578. return nil, err
  1579. }
  1580. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1581. } else if sqltype == "v" {
  1582. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1583. if v, ok := tempValParam.(map[string]interface{}); ok {
  1584. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1585. } else {
  1586. }
  1587. if err != nil {
  1588. return nil, err
  1589. }
  1590. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1591. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1592. }
  1593. } else if sqltype == "e" {
  1594. tempVal_arrary := make([]map[string]interface{}, 0)
  1595. tempVal_map := make(map[string]interface{})
  1596. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1597. if err == nil {
  1598. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1599. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1600. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1601. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1602. return tempVal_arrary, err
  1603. }
  1604. return nil, err
  1605. } else {
  1606. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1607. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1608. if err != nil {
  1609. return nil, err
  1610. }
  1611. return nil, err
  1612. }
  1613. }
  1614. return nil, nil
  1615. }
  1616. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1617. var err error
  1618. subarray, ok := fasion["children"]
  1619. if ok {
  1620. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1621. tempVal_arrary := make([]map[string]interface{}, 0)
  1622. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1623. tempVal_ := make(map[string]interface{})
  1624. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1625. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1626. } else {
  1627. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1628. }
  1629. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1630. if err != nil {
  1631. return err
  1632. }
  1633. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1634. }
  1635. v.(map[string]interface{})["children"] = tempVal_arrary
  1636. }
  1637. }
  1638. return nil
  1639. }
  1640. // @Summary 删除图片
  1641. // @Tags RemovePicByName
  1642. // @Accept json
  1643. // @Produce json
  1644. // @Param sqlname query string true "sqlname"
  1645. // @Param offset query int true "offset"
  1646. // @Param pagecount query int true "pagecount"
  1647. // @Param returntype query string true "returntype"
  1648. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1649. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1650. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1651. // @Router /data/PostDataByName [POST]
  1652. func RemovePicByName(c *gin.Context) {
  1653. logging.Info("RemovePicByName ", c.Keys)
  1654. appG := app.Gin{C: c}
  1655. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1656. fsion := gofasion.NewFasion(string(dataByte))
  1657. sqlnamestr := fsion.Get("name").ValueStr()
  1658. picname := fsion.Get("picname").ValueStr()
  1659. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1660. params := fsion.Get("params").Array()
  1661. s_params := make([]interface{}, 0)
  1662. for _, v_params := range params {
  1663. s_params = append(s_params, v_params.ValueStr())
  1664. }
  1665. if sql != "" {
  1666. queryData, err := execDataBySql(sql, s_params)
  1667. if picname != "" {
  1668. // Destination
  1669. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1670. err := os.Remove(distPath) //删除文件test.txt
  1671. if err != nil {
  1672. //如果删除失败则输出 file remove Error!
  1673. fmt.Println("file remove Error!")
  1674. //输出错误详细信息
  1675. fmt.Printf("%s", err)
  1676. } else {
  1677. //如果删除成功则输出 file remove OK!
  1678. fmt.Print("file remove OK!")
  1679. }
  1680. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1681. err = os.Remove(distPath) //删除文件test.txt
  1682. if err != nil {
  1683. //如果删除失败则输出 file remove Error!
  1684. fmt.Println("file remove Error!")
  1685. //输出错误详细信息
  1686. fmt.Printf("%s", err)
  1687. } else {
  1688. //如果删除成功则输出 file remove OK!
  1689. fmt.Print("file remove OK!")
  1690. }
  1691. }
  1692. if err != nil {
  1693. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1694. } else {
  1695. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1696. }
  1697. } else {
  1698. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1699. }
  1700. }
  1701. // @Summary 删除文件
  1702. // @Tags RemoveFileByName
  1703. // @Accept json
  1704. // @Produce json
  1705. // @Param sqlname query string true "sqlname"
  1706. // @Param offset query int true "offset"
  1707. // @Param pagecount query int true "pagecount"
  1708. // @Param returntype query string true "returntype"
  1709. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1710. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1711. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1712. // @Router /data/PostDataByName [POST]
  1713. func RemoveFileByName(c *gin.Context) {
  1714. appG := app.Gin{C: c}
  1715. id := c.Param("id")
  1716. logging.Info("DownloadFile ", c.Keys, id)
  1717. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1718. if eqdoc == nil {
  1719. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1720. return
  1721. }
  1722. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1723. err = os.Remove(distPath) //删除文件test.txt
  1724. if err != nil {
  1725. //如果删除失败则输出 file remove Error!
  1726. fmt.Println("file remove Error!")
  1727. //输出错误详细信息
  1728. fmt.Printf("%s", err)
  1729. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1730. return
  1731. }
  1732. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1733. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1734. }
  1735. // @Summary 根据APISQL表中SQL执行得到数据集
  1736. // @Tags PostDataByName
  1737. // @Accept json
  1738. // @Produce json
  1739. // @Param sqlname query string true "sqlname"
  1740. // @Param offset query int true "offset"
  1741. // @Param pagecount query int true "pagecount"
  1742. // @Param returntype query string true "returntype"
  1743. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1744. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1745. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1746. // @Router /data/PostDataByName [POST]
  1747. func UpdateDataRelation(c *gin.Context) {
  1748. appG := app.Gin{C: c}
  1749. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1750. fsion := gofasion.NewFasion(string(dataByte))
  1751. tablename := fsion.Get("name").ValueStr()
  1752. dataname := fsion.Get("dataname").ValueStr()
  1753. datavalue := fsion.Get("datavalue").ValueStr()
  1754. valuename := fsion.Get("valuename").ValueStr()
  1755. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1756. values := fsion.Get("values").Array()
  1757. tx := restful.Engine.NewSession()
  1758. err := tx.Begin()
  1759. defer func() {
  1760. switch {
  1761. case err != nil:
  1762. if tx != nil {
  1763. tx.Rollback()
  1764. }
  1765. default:
  1766. if tx != nil {
  1767. err = tx.Commit()
  1768. }
  1769. }
  1770. if tx != nil {
  1771. tx.Close()
  1772. }
  1773. }()
  1774. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1775. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1776. d_params := make([]interface{}, 4)
  1777. d_params[0] = datavalue
  1778. s_params := ""
  1779. for _, v_values := range values {
  1780. d_params[1] = v_values.ValueStr()
  1781. if s_params == "" {
  1782. s_params = v_values.ValueStr()
  1783. } else {
  1784. s_params = s_params + "," + v_values.ValueStr()
  1785. }
  1786. d_params[2] = d_params[1]
  1787. d_params[3] = d_params[0]
  1788. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1789. if err != nil {
  1790. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1791. break
  1792. }
  1793. }
  1794. if s_params != "" {
  1795. deleteSqlstr := "delete from " + tablename + " " +
  1796. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1797. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1798. if err != nil {
  1799. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1800. } else if err == nil {
  1801. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1802. }
  1803. } else {
  1804. deleteSqlstr := "delete from " + tablename + " " +
  1805. " where " + dataname + " = " + datavalue
  1806. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1807. if err != nil {
  1808. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1809. } else if err == nil {
  1810. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1811. }
  1812. }
  1813. }
  1814. // @Summary 根据APISQL表中SQL执行得到数据集
  1815. // @Tags PostDatasByName
  1816. // @Accept json
  1817. // @Produce json
  1818. // @Param sqlname query string true "sqlname"
  1819. // @Param offset query int true "offset"
  1820. // @Param pagecount query int true "pagecount"
  1821. // @Param returntype query string true "returntype"
  1822. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1823. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1824. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1825. // @Router /data/PostDatasByName [POST]
  1826. func PostDataByNames(c *gin.Context) {
  1827. appG := app.Gin{C: c}
  1828. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1829. fsion := gofasion.NewFasion(string(dataByte))
  1830. sqlParams := fsion.Get("array").Array()
  1831. queryData := make(map[string]interface{})
  1832. for _, v := range sqlParams {
  1833. fsion2 := gofasion.NewFasion(v.Json())
  1834. ss := fsion2.Get("name")
  1835. aa := fsion2.Get("params")
  1836. fmt.Println(ss, aa)
  1837. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1838. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1839. if sql == "" {
  1840. errorm := make(map[string]interface{})
  1841. errorm["code"] = e.ERROR
  1842. errorm["message"] = "sql没有找到"
  1843. errorm["param"] = ""
  1844. queryData[fsion2.Get("name").ValueStr()] = errorm
  1845. continue
  1846. } else if sql != "" {
  1847. s_params := make([]interface{}, 0)
  1848. if fsion2.HasKey("parammaps") {
  1849. parammaps := fsion2.Get("parammaps")
  1850. paramslist := strings.Split(p, ",")
  1851. if len(paramslist) > 0 && p != "" {
  1852. for _, value := range paramslist {
  1853. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1854. if tempv, exists := c.Get("jwt_username"); exists {
  1855. s_params = append(s_params, tempv.(string))
  1856. } else {
  1857. s_params = append(s_params, "")
  1858. }
  1859. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1860. ids, err := setting.SnowIds.NextId()
  1861. if err != nil {
  1862. ids = time.Now().UnixNano()
  1863. logging.Info("create SnowIds err", err)
  1864. }
  1865. s_params = append(s_params, ids)
  1866. } else {
  1867. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1868. }
  1869. }
  1870. }
  1871. } else if fsion2.HasKey("params") {
  1872. params := fsion2.Get("params").Array()
  1873. //ids,err := setting.SnowIds.NextId()
  1874. //if err !=nil{
  1875. // ids = time.Now().UnixNano()
  1876. // logging.Info("create SnowIds err",err)
  1877. //}
  1878. //s_params = append(s_params, ids)
  1879. for _, v_params := range params {
  1880. s_params = append(s_params, v_params.ValueStr())
  1881. }
  1882. }
  1883. _, err := execDataBySql(sql, s_params)
  1884. if err != nil {
  1885. logging.Error("PostDataByName err: ", err)
  1886. errorm := make(map[string]interface{})
  1887. errorm["code"] = e.ERROR
  1888. errorm["message"] = err.Error()
  1889. errorm["param"] = s_params
  1890. queryData[fsion2.Get("name").ValueStr()] = errorm
  1891. continue
  1892. } else {
  1893. errorm := make(map[string]interface{})
  1894. errorm["code"] = e.SUCCESS
  1895. errorm["message"] = "success"
  1896. queryData[fsion2.Get("name").ValueStr()] = errorm
  1897. continue
  1898. }
  1899. } else {
  1900. errorm := make(map[string]interface{})
  1901. errorm["code"] = e.ERROR
  1902. errorm["message"] = "NO SQL"
  1903. errorm["param"] = ""
  1904. queryData[fsion2.Get("name").ValueStr()] = errorm
  1905. }
  1906. }
  1907. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1908. }
  1909. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1910. if offset > 0 {
  1911. offset = offset - 1
  1912. }
  1913. //if pagecount == 0 {
  1914. // pagecount = setting.AppSetting.PageSize
  1915. //}else if pagecount>setting.AppSetting.PageSize{
  1916. // pagecount = setting.AppSetting.PageSize
  1917. //}
  1918. if returntype == "list" {
  1919. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1920. return queryData, err
  1921. } else if returntype == "listlist" {
  1922. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1923. return queryData, err
  1924. } else {
  1925. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1926. return queryData, err
  1927. }
  1928. }
  1929. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1930. if offset > 0 {
  1931. offset = offset - 1
  1932. }
  1933. //if pagecount == 0 {
  1934. // pagecount = setting.AppSetting.PageSize
  1935. //}else if pagecount>setting.AppSetting.PageSize{
  1936. // pagecount = setting.AppSetting.PageSize
  1937. //}
  1938. if returntype == "list" {
  1939. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1940. return queryData, err
  1941. } else if returntype == "listlist" {
  1942. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1943. return queryData, err
  1944. } else {
  1945. fmt.Println(params)
  1946. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1947. return queryData, err
  1948. }
  1949. }
  1950. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1951. paramslist := strings.Split(Params, ",")
  1952. s_params := make([]interface{}, 0)
  1953. if isList {
  1954. for _, v_params := range thisParams["params"].([]interface{}) {
  1955. s_params = append(s_params, v_params)
  1956. }
  1957. } else {
  1958. paramslist := strings.Split(Params, ",")
  1959. if len(paramslist) > 0 && Params != "" {
  1960. for _, value := range paramslist {
  1961. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1962. }
  1963. }
  1964. }
  1965. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  1966. for _, queryData_ := range queryData {
  1967. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  1968. if isList {
  1969. if queryData_[idname] != nil {
  1970. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  1971. }
  1972. } else {
  1973. if queryData_[idname] != nil {
  1974. thisParams[idname] = queryData_[idname].(interface{})
  1975. }
  1976. if len(paramslist) > 0 && Params != "" {
  1977. s_params = make([]interface{}, 0)
  1978. for _, value := range paramslist {
  1979. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1980. }
  1981. }
  1982. }
  1983. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  1984. } else {
  1985. }
  1986. }
  1987. return queryData, err
  1988. }
  1989. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1990. queryData, err := restful.ExecQuery(sqlstr, params)
  1991. return queryData, err
  1992. }
  1993. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1994. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  1995. return queryData, err
  1996. }
  1997. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1998. queryData, err := restful.ExecQuery(sqlstr, params)
  1999. return queryData, err
  2000. }
  2001. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2002. // @Tags ImportExcel
  2003. // @Accept json
  2004. // @Produce json
  2005. // @Param file query string true "文件名"
  2006. // @Param name header string true "执行sql的名字"
  2007. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2008. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2009. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2010. // @Router /data/ImportExcel [POST]
  2011. func ImportExcel(c *gin.Context) {
  2012. appG := app.Gin{C: c}
  2013. inputdata := ""
  2014. c.Request.ParseForm()
  2015. params := c.Request.Form
  2016. file, _, err := c.Request.FormFile("file")
  2017. if err != nil {
  2018. appG.Response(http.StatusOK, e.ERROR, err)
  2019. return
  2020. }
  2021. sqlnamestrs := params.Get("name")
  2022. sheetname := params.Get("sheetname")
  2023. pastureid := params.Get("pastureid")
  2024. //importParams := params.Get("importParams")
  2025. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2026. // 必输项参数 (字符串格式 "field1,field2,field3")
  2027. requiredParams := params.Get("requiredParams")
  2028. // 日期参数
  2029. dateParams := params.Get("dateParams")
  2030. // 数字参数
  2031. numParams := params.Get("numParams")
  2032. //将字符串分割开
  2033. dateParamslist := strings.Split(dateParams, ",")
  2034. requiredParamslist := strings.Split(requiredParams, ",")
  2035. numParamslist := strings.Split(numParams, ",")
  2036. queryData := make([]interface{}, 0)
  2037. sqlslist := strings.Split(sqlnamestrs, ",")
  2038. xlsx1, err := excelize.OpenReader(file)
  2039. if err != nil {
  2040. fmt.Println(err)
  2041. return
  2042. }
  2043. ok := 0
  2044. error := 0
  2045. isdone := true
  2046. rows := xlsx1.GetRows(sheetname)
  2047. // 限制10000条,多余的截取掉
  2048. if len(rows) > 10000 {
  2049. rows = rows[:10000]
  2050. }
  2051. for i, row := range rows {
  2052. if i > 0 {
  2053. entry := make(map[string]interface{})
  2054. outentry := make(map[string]interface{})
  2055. for j, colCell := range rows[0] {
  2056. for k, colCell1 := range row {
  2057. if j == k {
  2058. outentry[colCell] = colCell1
  2059. entry[colCell] = colCell1
  2060. }
  2061. }
  2062. }
  2063. inputdata = ""
  2064. a := ""
  2065. fmt.Println(outentry, entry)
  2066. //校验日期格式
  2067. for _, v := range dateParamslist {
  2068. if v == "" {
  2069. continue
  2070. }
  2071. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2072. dtime, err := TransfTime(d.(string))
  2073. if err != nil {
  2074. a = strings.Trim(v, " ")
  2075. break
  2076. }
  2077. outentry[strings.Trim(v, " ")] = dtime
  2078. }
  2079. }
  2080. if a != "" {
  2081. outentry["error_msg"] = a + " 格式错误"
  2082. error++
  2083. queryData = append(queryData, outentry)
  2084. continue
  2085. }
  2086. a = ""
  2087. //校验必填格式
  2088. for _, v := range requiredParamslist {
  2089. if v == "" {
  2090. continue
  2091. }
  2092. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2093. a = strings.Trim(v, " ")
  2094. break
  2095. }
  2096. }
  2097. if a != "" {
  2098. outentry["error_msg"] = a + " 未填或格式错误"
  2099. error++
  2100. queryData = append(queryData, outentry)
  2101. continue
  2102. }
  2103. a = ""
  2104. //校验数字格式
  2105. for _, v := range numParamslist {
  2106. if v == "" {
  2107. continue
  2108. }
  2109. d, ok := outentry[strings.Trim(v, " ")]
  2110. if !ok || d == "" {
  2111. outentry[strings.Trim(v, " ")] = 0
  2112. } else {
  2113. var fl float64
  2114. switch d.(type) {
  2115. case string:
  2116. fl, err = strconv.ParseFloat(d.(string), 64)
  2117. }
  2118. if err != nil || fl < 0 {
  2119. a = strings.Trim(v, " ")
  2120. break
  2121. }
  2122. }
  2123. }
  2124. if a != "" {
  2125. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2126. error++
  2127. queryData = append(queryData, outentry)
  2128. continue
  2129. }
  2130. tx := restful.Engine.NewSession()
  2131. err := tx.Begin()
  2132. for _, sqlnamestr := range sqlslist {
  2133. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2134. paramslist := strings.Split(paramslists, ",")
  2135. if len(paramslist) > 0 {
  2136. s_params := make([]interface{}, 0)
  2137. for _, value := range paramslist {
  2138. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2139. if tempv, exists := c.Get("jwt_username"); exists {
  2140. s_params = append(s_params, tempv.(string))
  2141. } else {
  2142. s_params = append(s_params, "")
  2143. }
  2144. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2145. s_params = append(s_params, pastureid)
  2146. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2147. ids, err := setting.SnowIds.NextId()
  2148. if err != nil {
  2149. ids = time.Now().UnixNano()
  2150. logging.Info("create SnowIds err", err)
  2151. }
  2152. s_params = append(s_params, ids)
  2153. } else {
  2154. if outentry[strings.Trim(value, " ")] == nil {
  2155. s_params = append(s_params, "")
  2156. } else {
  2157. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2158. }
  2159. }
  2160. }
  2161. outentry["input"] = inputdata
  2162. fmt.Println(sql, s_params)
  2163. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2164. if err != nil {
  2165. if tx != nil {
  2166. tx.Rollback()
  2167. }
  2168. if tx != nil {
  2169. tx.Close()
  2170. }
  2171. msg := geterrmsg(err.Error())
  2172. outentry["error_msg"] = msg
  2173. error++
  2174. queryData = append(queryData, outentry)
  2175. isdone = true
  2176. break
  2177. } else {
  2178. if len(returnmsgmap1) > 0 {
  2179. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2180. if tx != nil {
  2181. tx.Rollback()
  2182. }
  2183. if tx != nil {
  2184. tx.Close()
  2185. }
  2186. msg := geterrmsg(va.(string))
  2187. outentry["error_msg"] = msg
  2188. error++
  2189. queryData = append(queryData, outentry)
  2190. isdone = true
  2191. break
  2192. }
  2193. }
  2194. isdone = false
  2195. }
  2196. }
  2197. }
  2198. switch {
  2199. case err != nil:
  2200. if tx != nil {
  2201. tx.Rollback()
  2202. }
  2203. default:
  2204. if tx != nil {
  2205. err = tx.Commit()
  2206. }
  2207. }
  2208. if tx != nil {
  2209. tx.Close()
  2210. }
  2211. }
  2212. if !isdone {
  2213. ok++
  2214. isdone = true
  2215. }
  2216. }
  2217. data := make(map[string]interface{})
  2218. data["result"] = queryData
  2219. data["success"] = ok
  2220. data["err_count"] = error
  2221. appG.Response(http.StatusOK, e.SUCCESS, data)
  2222. }
  2223. func TransfTime(timestr string) (string, error) {
  2224. if timestr == "" {
  2225. return time.Now().Format("2006-01-02"), nil
  2226. }
  2227. days, err := strconv.Atoi(timestr)
  2228. if err != nil {
  2229. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2230. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2231. }
  2232. _, err := time.Parse("2006-01-02", timestr)
  2233. if err != nil {
  2234. t, err := time.Parse("2006/01/02", timestr)
  2235. if err != nil {
  2236. t, err := time.Parse("2006.01.02", timestr)
  2237. if err != nil {
  2238. return "", err
  2239. } else {
  2240. return t.Format("2006-01-02"), nil
  2241. }
  2242. } else {
  2243. return t.Format("2006-01-02"), nil
  2244. }
  2245. } else {
  2246. return timestr, nil
  2247. }
  2248. }
  2249. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2250. times = times.AddDate(0, 0, days)
  2251. return times.Format("2006-01-02"), nil
  2252. }
  2253. func Createchart(c *gin.Context) {
  2254. appG := app.Gin{C: c}
  2255. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2256. fsion := gofasion.NewFasion(string(dataByte))
  2257. chart_name := fsion.Get("chart_name").ValueStr()
  2258. desc := fsion.Get("desc").ValueStr()
  2259. pastureid := fsion.Get("pastureid").ValueStr()
  2260. source_id := fsion.Get("source_id").ValueStr()
  2261. emp := fsion.Get("emp").ValueStr()
  2262. content := fsion.Get("content").Json()
  2263. var mapResult map[string]interface{}
  2264. err1 := json.Unmarshal([]byte(content), &mapResult)
  2265. if err1 != nil {
  2266. fmt.Println("JsonToMapDemo err: ", err1)
  2267. }
  2268. tx := restful.Engine.NewSession()
  2269. err := tx.Begin()
  2270. defer func() {
  2271. switch {
  2272. case err != nil:
  2273. logging.Error("tx.Begin 事务启动失败__error:", err)
  2274. if tx != nil {
  2275. tx.Rollback()
  2276. }
  2277. default:
  2278. if tx != nil {
  2279. err = tx.Commit()
  2280. }
  2281. }
  2282. if tx != nil {
  2283. tx.Close()
  2284. }
  2285. }()
  2286. ids, err := setting.SnowIds.NextId()
  2287. if err != nil {
  2288. ids = time.Now().UnixNano()
  2289. logging.Info("create SnowIds err", err)
  2290. }
  2291. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2292. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2293. if err != nil {
  2294. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2295. } else {
  2296. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2297. }
  2298. }
  2299. func Updatedashboard(c *gin.Context) {
  2300. appG := app.Gin{C: c}
  2301. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2302. fsion := gofasion.NewFasion(string(dataByte))
  2303. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2304. pastureid := fsion.Get("pastureid").ValueStr()
  2305. content := fsion.Get("content").Json()
  2306. var mapResult map[string]interface{}
  2307. err1 := json.Unmarshal([]byte(content), &mapResult)
  2308. if err1 != nil {
  2309. fmt.Println("JsonToMapDemo err: ", err1)
  2310. }
  2311. layout := mapResult["layout"]
  2312. tx := restful.Engine.NewSession()
  2313. err := tx.Begin()
  2314. defer func() {
  2315. switch {
  2316. case err != nil:
  2317. logging.Error("tx.Begin 事务启动失败__error:", err)
  2318. if tx != nil {
  2319. tx.Rollback()
  2320. }
  2321. default:
  2322. if tx != nil {
  2323. err = tx.Commit()
  2324. }
  2325. }
  2326. if tx != nil {
  2327. tx.Close()
  2328. }
  2329. }()
  2330. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2331. if err != nil {
  2332. println("2", err.Error())
  2333. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2334. } else {
  2335. if exec != nil {
  2336. if exec[0]["content"] == nil {
  2337. mapR := make(map[string]interface{})
  2338. mapR["layout"] = layout
  2339. mjson, _ := json.Marshal(mapR)
  2340. mString := string(mjson)
  2341. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2342. if err3 != nil {
  2343. println("3", err3.Error())
  2344. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2345. } else {
  2346. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2347. }
  2348. } else {
  2349. var mapR map[string]interface{}
  2350. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2351. if err1 != nil {
  2352. fmt.Println("JsonToMapDemo err: ", err2)
  2353. }
  2354. mapR["layout"] = layout
  2355. mjson, _ := json.Marshal(mapR)
  2356. mString := string(mjson)
  2357. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2358. if err3 != nil {
  2359. println("3", err3.Error())
  2360. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2361. } else {
  2362. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2363. }
  2364. }
  2365. } else {
  2366. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2367. }
  2368. }
  2369. }
  2370. func ExecSQL(c *gin.Context) {
  2371. appG := app.Gin{C: c}
  2372. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2373. fsion := gofasion.NewFasion(string(dataByte))
  2374. content := fsion.Get("content").Json()
  2375. pastureid := fsion.Get("pastureid").ValueStr()
  2376. var mapResult map[string]interface{}
  2377. err1 := json.Unmarshal([]byte(content), &mapResult)
  2378. if err1 != nil {
  2379. fmt.Println("JsonToMapDemo err: ", err1)
  2380. }
  2381. sqlstr := "select "
  2382. groupstr := " GROUP BY "
  2383. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2384. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2385. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2386. }
  2387. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2388. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2389. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2390. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2391. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2392. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2393. sqlstr = sqlstr + tem + ","
  2394. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2395. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2396. sqlstr = sqlstr + tem + ","
  2397. } else {
  2398. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2399. sqlstr = sqlstr + tem + ","
  2400. }
  2401. }
  2402. if _, ok := mapResult["selectedCalcul2"]; ok {
  2403. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2404. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2405. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2406. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2407. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2408. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2409. sqlstr = sqlstr + tem + ","
  2410. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2411. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2412. sqlstr = sqlstr + tem + ","
  2413. } else {
  2414. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2415. sqlstr = sqlstr + tem + ","
  2416. }
  2417. }
  2418. }
  2419. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2420. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2421. sqlstr = sqlstr + " where pastureid=" + pastureid
  2422. if len(mapResult["filters"].([]interface{})) > 0 {
  2423. sqlstr = sqlstr + " and "
  2424. }
  2425. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2426. for _, value := range mapResult["filters"].([]interface{}) {
  2427. switch value.(map[string]interface{})["filterOperator"].(string) {
  2428. case ">", "=", "<", ">=", "<=", "!=", "like":
  2429. 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 "
  2430. case "IN":
  2431. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2432. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2433. sqlstr = sqlstr + value1.(string) + ","
  2434. }
  2435. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2436. sqlstr = sqlstr + ")" + " AND "
  2437. case "BETWEEN":
  2438. 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 "
  2439. }
  2440. }
  2441. if len(mapResult["filters"].([]interface{})) > 0 {
  2442. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2443. }
  2444. //
  2445. groupstr = groupstr[0 : len(groupstr)-1]
  2446. sqlstr = sqlstr + groupstr + " "
  2447. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2448. sqlstr = sqlstr + " order by "
  2449. }
  2450. //
  2451. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2452. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2453. sqlstr = sqlstr + value.(string) + " "
  2454. } else {
  2455. sqlstr = sqlstr + value.(string) + ","
  2456. }
  2457. }
  2458. //
  2459. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2460. tx := restful.Engine.NewSession()
  2461. err := tx.Begin()
  2462. defer func() {
  2463. switch {
  2464. case err != nil:
  2465. logging.Error("tx.Begin 事务启动失败__error:", err)
  2466. if tx != nil {
  2467. tx.Rollback()
  2468. }
  2469. default:
  2470. if tx != nil {
  2471. err = tx.Commit()
  2472. }
  2473. }
  2474. if tx != nil {
  2475. tx.Close()
  2476. }
  2477. }()
  2478. exec, err := tx.SQL(sqlstr).Query().List()
  2479. if err != nil {
  2480. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2481. } else {
  2482. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2483. }
  2484. }
  2485. func Dashboards(c *gin.Context) {
  2486. appG := app.Gin{C: c}
  2487. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2488. fsion := gofasion.NewFasion(string(dataByte))
  2489. sqlnamestr := fsion.Get("name").ValueStr()
  2490. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2491. offset := fsion.Get("offset").ValueDefaultInt(0)
  2492. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2493. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2494. month := fsion.Get("month").ValueDefaultStr("map")
  2495. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2496. tx := restful.Engine.NewSession()
  2497. err := tx.Begin()
  2498. defer func() {
  2499. switch {
  2500. case err != nil:
  2501. if tx != nil {
  2502. tx.Rollback()
  2503. }
  2504. default:
  2505. if tx != nil {
  2506. err = tx.Commit()
  2507. }
  2508. }
  2509. if tx != nil {
  2510. tx.Close()
  2511. }
  2512. }()
  2513. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2514. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2515. if sql != "" {
  2516. s_params := make([]interface{}, 0)
  2517. if fsion.HasKey("parammaps") {
  2518. parammaps := fsion.Get("parammaps")
  2519. paramslist := strings.Split(p, ",")
  2520. if len(paramslist) > 0 && p != "" {
  2521. for _, value := range paramslist {
  2522. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2523. if tempv, exists := c.Get("jwt_username"); exists {
  2524. s_params = append(s_params, tempv.(string))
  2525. } else {
  2526. s_params = append(s_params, "")
  2527. }
  2528. } else {
  2529. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2530. }
  2531. }
  2532. }
  2533. }
  2534. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2535. if err != nil {
  2536. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2537. } else {
  2538. //paramslist1 := strings.Split(p1, ",")
  2539. dids := make([]interface{}, 0)
  2540. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2541. var mapResult map[string]interface{}
  2542. dids = append(dids, value["dashboard_id"])
  2543. if value["content"] != nil {
  2544. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2545. if err1 != nil {
  2546. println("JsonToMapDemo1 err: ", err1)
  2547. }
  2548. temap := make(map[string]interface{})
  2549. tem := mapResult["layout"].([]interface{})
  2550. if v, ok := value["chartids"]; ok {
  2551. chartids := strings.Split(v.(string), ",")
  2552. for _, va := range chartids {
  2553. a := false
  2554. for _, v2 := range tem {
  2555. if v2.(map[string]interface{})["id"].(string) == va {
  2556. a = true
  2557. //println("va1======",va)
  2558. }
  2559. }
  2560. if !a {
  2561. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2562. va + "\",\"id\":\"" + va +
  2563. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2564. var mapTem map[string]interface{}
  2565. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2566. if err1 != nil {
  2567. println("JsonToMapDemo err: ", err1)
  2568. }
  2569. tem = append(tem, mapTem)
  2570. }
  2571. }
  2572. temap["layout"] = tem
  2573. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2574. }
  2575. } else {
  2576. temap := make(map[string]interface{})
  2577. tem := make([]interface{}, 0)
  2578. if v, ok := value["chartids"]; ok {
  2579. chartids := strings.Split(v.(string), ",")
  2580. for _, va := range chartids {
  2581. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2582. va + "\",\"id\":\"" + va +
  2583. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2584. var mapTem map[string]interface{}
  2585. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2586. if err1 != nil {
  2587. println("JsonToMapDemo err: ", err1)
  2588. }
  2589. tem = append(tem, mapTem)
  2590. }
  2591. temap["layout"] = tem
  2592. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2593. }
  2594. }
  2595. }
  2596. queryData.(map[string]interface{})["order"] = dids
  2597. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2598. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2599. }
  2600. } else {
  2601. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2602. }
  2603. }
  2604. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2605. fsion := gofasion.NewFasion(parammaps)
  2606. sqlnamestr := fsion.Get("name").ValueStr()
  2607. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2608. offset := fsion.Get("offset").ValueDefaultInt(0)
  2609. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2610. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2611. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2612. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2613. body := []byte("")
  2614. if sql != "" {
  2615. s_params := make([]interface{}, 0)
  2616. if fsion.HasKey("parammaps") {
  2617. parammaps := fsion.Get("parammaps")
  2618. paramslist := strings.Split(p, ",")
  2619. if len(paramslist) > 0 && p != "" {
  2620. for _, value := range paramslist {
  2621. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2622. }
  2623. }
  2624. }
  2625. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2626. if err != nil {
  2627. } else {
  2628. paramslist1 := strings.Split(p1, ",")
  2629. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2630. s_params1 := make([]interface{}, 0)
  2631. if len(paramslist1) > 0 && p1 != "" {
  2632. for _, v := range paramslist1 {
  2633. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2634. }
  2635. }
  2636. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2637. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2638. body, _ = json.Marshal(queryData)
  2639. }
  2640. }
  2641. }
  2642. bs := bytes.NewBuffer(body)
  2643. client := &http.Client{}
  2644. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2645. req, err := http.NewRequest(RequestMethod,
  2646. url,
  2647. bs,
  2648. )
  2649. if err != nil {
  2650. }
  2651. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2652. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2653. if err != nil {
  2654. // handle error
  2655. }
  2656. resp, err := client.Do(req)
  2657. if err != nil {
  2658. return ""
  2659. }
  2660. defer resp.Body.Close()
  2661. result_body, err := ioutil.ReadAll(resp.Body)
  2662. if err != nil {
  2663. return ""
  2664. }
  2665. fmt.Println(string(result_body))
  2666. return ""
  2667. }
  2668. func GetSummary(c *gin.Context) {
  2669. appG := app.Gin{C: c}
  2670. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2671. fsion := gofasion.NewFasion(string(dataByte))
  2672. offset := fsion.Get("offset").ValueDefaultInt(0)
  2673. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2674. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2675. parammaps := fsion.Get("parammaps")
  2676. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2677. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2678. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2679. tx := restful.Engine.NewSession()
  2680. defer tx.Close()
  2681. sqlnamestr := ""
  2682. if genre == "0" {
  2683. if status == "0" {
  2684. sqlnamestr = "getAccuracyJSY"
  2685. } else if status == "1" {
  2686. sqlnamestr = "getAccuracyHFT"
  2687. } else if status == "2" {
  2688. sqlnamestr = "getAccuracyHNS"
  2689. } else if status == "3" {
  2690. sqlnamestr = "getAccuracyHSC"
  2691. } else if status == "4" {
  2692. sqlnamestr = "getAccuracyHCC"
  2693. } else if status == "5" {
  2694. sqlnamestr = "getAccuracyMC"
  2695. } else if status == "6" {
  2696. sqlnamestr = "getAccuracyFeedHL"
  2697. } else if status == "7" {
  2698. sqlnamestr = "getAccuracyRT"
  2699. }
  2700. } else {
  2701. if status == "0" {
  2702. sqlnamestr = "getAccuracySCCJSY"
  2703. } else if status == "1" {
  2704. sqlnamestr = "getAccuracySFT"
  2705. } else if status == "2" {
  2706. sqlnamestr = "getAccuracySNS"
  2707. } else if status == "3" {
  2708. sqlnamestr = "getAccuracySSC"
  2709. } else if status == "4" {
  2710. sqlnamestr = "getAccuracySCC"
  2711. } else if status == "5" {
  2712. sqlnamestr = "getAccuracySLCL"
  2713. } else if status == "7" {
  2714. sqlnamestr = "getAccuracySCCRT"
  2715. }
  2716. }
  2717. if isDate == "1" {
  2718. sqlnamestr += "Date"
  2719. }
  2720. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2721. // fmt.Println(sqlnamestr, sql)
  2722. if sql != "" {
  2723. s_params := make([]interface{}, 0)
  2724. // if fsion.HasKey("parammaps") {
  2725. fmt.Println(s_params, "222", p)
  2726. paramslist := strings.Split(p, ",")
  2727. if len(paramslist) > 0 && p != "" {
  2728. for _, value := range paramslist {
  2729. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2730. if tempv, exists := c.Get("jwt_username"); exists {
  2731. s_params = append(s_params, tempv.(string))
  2732. } else {
  2733. s_params = append(s_params, "")
  2734. }
  2735. } else {
  2736. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2737. }
  2738. }
  2739. }
  2740. if returntype == "xlsx" {
  2741. var xlsxfile *xlsx.File
  2742. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2743. //c.File("c:/dd.xlsx")
  2744. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2745. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2746. c.Header("Content-Transfer-Encoding", "binary")
  2747. _ = xlsxfile.Write(c.Writer)
  2748. } else {
  2749. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2750. if err != nil {
  2751. logging.Error("GetDataByName err: ", err)
  2752. msg := geterrmsg(err.Error())
  2753. appG.Response(http.StatusOK, e.ERROR, msg)
  2754. } else {
  2755. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2756. }
  2757. }
  2758. } else {
  2759. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2760. }
  2761. }
  2762. // type lpplanStruct struct {
  2763. // Id int64 `xorm:"id"`
  2764. // Tmrname string `xorm:"tmrname"`
  2765. // Tmrid int64 `xorm:"tmrid"`
  2766. // Sort int64 `xorm:"sort"`
  2767. // Sel int64 `xorm:"sel"`
  2768. // Times int64 `xorm:"times"`
  2769. // Ftname string `xorm:"ftname"`
  2770. // Ftid int64 `xorm:"ftid"`
  2771. // Maxweight float64 `xorm:"maxweight"`
  2772. // Sumweight float64 `xorm:"sumweight"`
  2773. // Sumcowcount int64 `xorm:"sumcowcount"`
  2774. // Pastureid string `xorm:"pastureid"`
  2775. // Display string `xorm:"display"`
  2776. // Issplit int64 `xorm:"issplit"`
  2777. // BeginTime string `xorm:"begintime"`
  2778. // }
  2779. func UpdateFTdetail(c *gin.Context) {
  2780. appG := app.Gin{C: c}
  2781. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2782. tempval_ := make(map[string]interface{})
  2783. tempCommon := make(map[string]interface{})
  2784. tempval := make([]map[string]interface{}, 0)
  2785. fTChange := make(map[string]interface{}, 0)
  2786. fpdOldDataList := make([]map[string]interface{}, 0)
  2787. fpdDataList := make([]map[string]interface{}, 0)
  2788. fsion := gofasion.NewFasion(string(dataByte))
  2789. // parammaps := fsion.Get("parammaps")
  2790. createdate := time.Now().Format("2006-01-02 15:04:05")
  2791. err := json.Unmarshal(dataByte, &tempval_)
  2792. if err != nil {
  2793. appG.Response(http.StatusOK, e.ERROR, false)
  2794. return
  2795. }
  2796. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2797. tx := restful.Engine.NewSession()
  2798. if v, ok := tempval_["data"].([]interface{}); ok {
  2799. for _, Tvalue := range v {
  2800. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2801. if v1["name"] == "updateFPbyFTChange" {
  2802. fTChange = v1
  2803. continue
  2804. }
  2805. tempval = append(tempval, v1)
  2806. }
  2807. }
  2808. }
  2809. parammaps := fTChange["parammaps"].(map[string]interface{})
  2810. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2811. // if err != nil {
  2812. // logs.Error(err)
  2813. // appG.Response(http.StatusOK, e.ERROR, false)
  2814. // return
  2815. // }
  2816. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2817. // if err != nil {
  2818. // logs.Error(err)
  2819. // appG.Response(http.StatusOK, e.ERROR, false)
  2820. // return
  2821. // }
  2822. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2823. // if err != nil {
  2824. // logs.Error(err)
  2825. // appG.Response(http.StatusOK, e.ERROR, false)
  2826. // return
  2827. // }
  2828. err = tx.Begin()
  2829. if err != nil {
  2830. logging.Error("tx.Begin 事务启动失败__error:", err)
  2831. }
  2832. defer func() {
  2833. if err != nil {
  2834. if tx != nil {
  2835. tx.Rollback()
  2836. }
  2837. }
  2838. if tx != nil {
  2839. tx.Close()
  2840. }
  2841. }()
  2842. if err != nil {
  2843. } else {
  2844. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2845. tempCommon = v
  2846. }
  2847. 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 ,
  2848. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2849. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2850. UNION
  2851. 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 ,
  2852. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2853. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2854. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2855. if err == nil {
  2856. if tempv, exists := c.Get("jwt_username"); exists {
  2857. tempCommon["jwt_username"] = tempv.(string)
  2858. }
  2859. for _, paramvalue := range tempval {
  2860. if _, ok := paramvalue["resultname"]; !ok {
  2861. paramvalue["resultname"] = paramvalue["name"]
  2862. }
  2863. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2864. if err != nil {
  2865. logging.Error("ExecDataParam error:", err)
  2866. break
  2867. }
  2868. }
  2869. if err != nil {
  2870. msg := geterrmsg(err.Error())
  2871. appG.Response(http.StatusOK, e.ERROR, msg)
  2872. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2873. }
  2874. }
  2875. }
  2876. tx.Commit()
  2877. // go func() {
  2878. if fTChange != nil {
  2879. parammaps := fTChange["parammaps"].(map[string]interface{})
  2880. if parammaps["type"].(float64) == 1 {
  2881. _, err = tx.SQL(`UPDATE feedp fp
  2882. set
  2883. ccountratio = ccount *(ratio /100 ),
  2884. fp.ftweight= IFNULL(IF(
  2885. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2886. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2887. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2888. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2889. ),0),fp.feedweight = IFNULL(IF(
  2890. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2891. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2892. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2893. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2894. ),0) +ifnull(fp.supplyweight,0)
  2895. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2896. _, err = tx.SQL(`UPDATE fpdetail fpd
  2897. INNER JOIN feedp fp
  2898. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2899. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2900. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2901. } else {
  2902. _, err = tx.SQL(`UPDATE feedp fp
  2903. SET ccountratio = ccount *(ratio /100 ),
  2904. fp.supplyweight= IFNULL(IF(
  2905. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2906. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2907. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2908. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2909. ),0),fp.feedweight = IFNULL(IF(
  2910. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2911. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2912. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2913. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2914. ),0) +ifnull(fp.supplyweight,0)
  2915. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2916. _, err = tx.SQL(`UPDATE fpdetail fpd
  2917. INNER JOIN feedp fp
  2918. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2919. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2920. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2921. }
  2922. 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 ,
  2923. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2924. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2925. UNION
  2926. 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 ,
  2927. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2928. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2929. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2930. lpplanList := make([]*lpplanStruct, 0)
  2931. err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2932. if err != nil {
  2933. logs.Error(err, 1)
  2934. return
  2935. }
  2936. lppidlist := []string{}
  2937. for _, lpp := range lpplanList {
  2938. lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2939. }
  2940. if len(lppidlist) <= 0 {
  2941. appG.Response(http.StatusOK, e.SUCCESS, true)
  2942. return
  2943. }
  2944. lpplandtl1AllList := make([]*lpplandtl1, 0)
  2945. err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  2946. order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  2947. if err != nil {
  2948. // tx.Rollback()
  2949. logs.Error(err, 2, parammaps["pastureid"])
  2950. return
  2951. }
  2952. // for _, lpp := range lpplandtl1AllList {
  2953. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  2954. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  2955. // if err != nil {
  2956. // logs.Error(err)
  2957. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  2958. // return
  2959. // }
  2960. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  2961. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  2962. // if err != nil {
  2963. // logs.Error(err)
  2964. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  2965. // return
  2966. // }
  2967. // }
  2968. var wg sync.WaitGroup
  2969. for _, old := range fpdOldDataList {
  2970. for _, fpd := range fpdDataList {
  2971. wg.Add(1)
  2972. go func(old, fpd map[string]interface{}) {
  2973. updateLppandList := make([]*lpplandtl1, 0)
  2974. defer wg.Done()
  2975. if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  2976. fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  2977. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  2978. oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  2979. // if weight > oldweight {
  2980. // return
  2981. // }
  2982. var w float64
  2983. var status int
  2984. if weight < oldweight {
  2985. if weight >= 0 {
  2986. return
  2987. }
  2988. w = weight
  2989. status = 0
  2990. } else {
  2991. if oldweight > 0 {
  2992. return
  2993. }
  2994. w = weight
  2995. status = 1
  2996. }
  2997. // fweight = w
  2998. for _, lpp := range lpplanList {
  2999. var fweight float64
  3000. var lweight float64
  3001. lpplandtl1List := make([]*lpplandtl1, 0)
  3002. fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3003. for _, lppland := range lpplandtl1AllList {
  3004. if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3005. lpplandtl1List = append(lpplandtl1List, lppland)
  3006. }
  3007. }
  3008. if len(lpplandtl1List) == 0 {
  3009. continue
  3010. }
  3011. for _, lppland := range lpplandtl1List {
  3012. lweight += lppland.Lweight
  3013. }
  3014. if status == 0 {
  3015. if lweight <= 0 {
  3016. continue
  3017. }
  3018. } else {
  3019. if lpp.Maxweight <= lweight {
  3020. continue
  3021. }
  3022. }
  3023. for _, lppland := range lpplandtl1List {
  3024. if fpdid == lppland.Fpdid {
  3025. if status == 1 {
  3026. // if w <= lppland.Lweight {
  3027. if lpp.Maxweight <= lweight {
  3028. continue
  3029. }
  3030. if w+lweight <= lpp.Maxweight {
  3031. lppland.Lweight += w
  3032. lweight += w
  3033. fweight += w
  3034. w = 0
  3035. } else {
  3036. w = w - (lpp.Maxweight - lweight)
  3037. n := (lpp.Maxweight - lweight)
  3038. lppland.Lweight = lppland.Lweight + n
  3039. lweight += n
  3040. fweight += n
  3041. }
  3042. } else {
  3043. if lppland.Lweight == 0 {
  3044. continue
  3045. }
  3046. if w+lppland.Lweight >= 0 {
  3047. lppland.Lweight = lppland.Lweight + w
  3048. lweight = lweight + w
  3049. fweight = fweight + w
  3050. w = 0
  3051. } else {
  3052. w = w + lppland.Lweight
  3053. lweight = lweight - lppland.Lweight
  3054. fweight = fweight - lppland.Lweight
  3055. lppland.Lweight = 0
  3056. }
  3057. }
  3058. updateLppandList = append(updateLppandList, lppland)
  3059. break
  3060. }
  3061. }
  3062. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3063. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3064. WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3065. if err != nil {
  3066. // tx.Rollback()
  3067. logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3068. return
  3069. }
  3070. for _, lppland := range updateLppandList {
  3071. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3072. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3073. if err != nil {
  3074. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3075. // tx.Rollback()
  3076. logs.Error(err, 3)
  3077. return
  3078. }
  3079. // defer wg.Done()
  3080. }
  3081. updateLppandList = []*lpplandtl1{}
  3082. if w == 0 {
  3083. break
  3084. }
  3085. }
  3086. }
  3087. }(old, fpd)
  3088. }
  3089. }
  3090. wg.Wait()
  3091. }
  3092. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3093. if err != nil {
  3094. logs.Error(err)
  3095. appG.Response(http.StatusOK, e.ERROR, false)
  3096. return
  3097. }
  3098. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3099. if err != nil {
  3100. logs.Error(err)
  3101. appG.Response(http.StatusOK, e.ERROR, false)
  3102. return
  3103. }
  3104. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3105. if err != nil {
  3106. logs.Error(err)
  3107. appG.Response(http.StatusOK, e.ERROR, false)
  3108. return
  3109. }
  3110. now := createdate
  3111. // for _, oldFpd := range oldFpdDataList {
  3112. for _, newFpd := range newFpdDataList {
  3113. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3114. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3115. // go func() {
  3116. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3117. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3118. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3119. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3120. if err != nil {
  3121. logs.Error(err)
  3122. appG.Response(http.StatusOK, e.ERROR, false)
  3123. return
  3124. }
  3125. // }()
  3126. }
  3127. // break
  3128. // }
  3129. // }
  3130. // }
  3131. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3132. for _, newLpplandtl1 := range newLpplandtl1List {
  3133. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3134. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3135. // go func() {
  3136. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3137. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3138. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3139. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3140. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3141. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3142. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3143. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3144. if err != nil {
  3145. logs.Error(err)
  3146. appG.Response(http.StatusOK, e.ERROR, false)
  3147. return
  3148. }
  3149. // }()
  3150. // }
  3151. // break
  3152. // }
  3153. // }
  3154. }
  3155. // for _, oldFeedp := range oldFeedpList {
  3156. for _, newFeedp := range newFeedpList {
  3157. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3158. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3159. // go func() {
  3160. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3161. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3162. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3163. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3164. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3165. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3166. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3167. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3168. if err != nil {
  3169. logs.Error(err)
  3170. appG.Response(http.StatusOK, e.ERROR, false)
  3171. return
  3172. }
  3173. }
  3174. // ,,parammaps["ftid"])
  3175. // surplus, surplusId, id, pastureId string
  3176. // FtdetailSurplusFt(parammaps["ftid"].)
  3177. ftList1, err := tx.SQL(` SELECT
  3178. f.id,
  3179. f.surplus surplusId,
  3180. f.pastureid,
  3181. s.surplus
  3182. FROM
  3183. feedtemplet f
  3184. JOIN surplus s ON s.id = f.surplus
  3185. WHERE
  3186. f.id = ?`, parammaps["ftid"]).QueryString()
  3187. for _, ft := range ftList1 {
  3188. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3189. }
  3190. appG.Response(http.StatusOK, e.SUCCESS, true)
  3191. }
  3192. type lpplandtlInfo struct {
  3193. Id int64 `xorm:"id"`
  3194. Pastureid int64 `xorm:"pastureid"`
  3195. Lppid int64 `xorm:"lppid"`
  3196. Barid int64 `xorm:"barid"`
  3197. Barname string `xorm:"barname"`
  3198. Fpdid int64 `xorm:"fpdid"`
  3199. Fttype int64 `xorm:"fttype"`
  3200. Lweight float64 `xorm:"lweight"`
  3201. Sort int64 `xorm:"sort"`
  3202. Tmrid int64 `xorm:"tmrid"`
  3203. Tmrname string `xorm:"tmrname"`
  3204. Cowcount int64 `xorm:"cowcount"`
  3205. Ccountradio float64 `xorm:"ccountradio"`
  3206. Background string `xorm:"background"`
  3207. Lweighthis float64 `xorm:"lweighthis"`
  3208. Maxweight float64 `xorm:"maxweight"`
  3209. }
  3210. func UpdateFpdetailBar(c *gin.Context) {
  3211. appG := app.Gin{C: c}
  3212. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3213. fsion := gofasion.NewFasion(string(dataByte))
  3214. pastureid := fsion.Get("pastureid").ValueStr()
  3215. id := fsion.Get("id").ValueStr()
  3216. tx := restful.Engine.NewSession()
  3217. tx.Begin()
  3218. 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 `,
  3219. pastureid, id).Query().List()
  3220. if err != nil {
  3221. logs.Error(err)
  3222. }
  3223. for _, fpd := range fpdList {
  3224. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3225. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3226. pastureid, fpd["id"]).Query().List()
  3227. if err != nil {
  3228. tx.Rollback()
  3229. logs.Error(err)
  3230. appG.Response(http.StatusOK, e.ERROR, false)
  3231. return
  3232. }
  3233. var lweight float64
  3234. for _, lppland := range lpplandList {
  3235. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3236. lweight += lweight1
  3237. }
  3238. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3239. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3240. if fpdweight >= ptuse && lweight == ptuse {
  3241. continue
  3242. } else {
  3243. if lweight <= fpdweight {
  3244. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3245. if err != nil {
  3246. tx.Rollback()
  3247. logs.Error(err)
  3248. appG.Response(http.StatusOK, e.ERROR, false)
  3249. return
  3250. }
  3251. } else {
  3252. weight := fpdweight - lweight
  3253. for _, lppland := range lpplandList {
  3254. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3255. if weight >= lpplandlweight {
  3256. weight = weight - lpplandlweight
  3257. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3258. if err != nil {
  3259. tx.Rollback()
  3260. logs.Error(err)
  3261. appG.Response(http.StatusOK, e.ERROR, false)
  3262. return
  3263. }
  3264. } else {
  3265. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3266. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3267. // if err != nil {
  3268. // tx.Rollback()
  3269. // logs.Error(err)
  3270. // appG.Response(http.StatusOK, e.ERROR, false)
  3271. // return
  3272. // }
  3273. weight = 0
  3274. break
  3275. }
  3276. }
  3277. }
  3278. }
  3279. }
  3280. fsionData := fsion.Get("data").Array()
  3281. for _, list := range fsionData {
  3282. ftmap := make(map[string]interface{})
  3283. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3284. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3285. ftmap["times"] = list.Get("times").ValueInt64()
  3286. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3287. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3288. // fmt.Println(ftmap)
  3289. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3290. and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3291. if err != nil {
  3292. tx.Rollback()
  3293. logs.Error(err)
  3294. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3295. return
  3296. }
  3297. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3298. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3299. if err != nil {
  3300. tx.Rollback()
  3301. logs.Error(err)
  3302. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3303. return
  3304. }
  3305. fpdDataList, err := tx.SQL(`
  3306. 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 ,
  3307. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3308. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3309. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3310. if err != nil {
  3311. tx.Rollback()
  3312. logs.Error(err)
  3313. }
  3314. for _, fpd := range fpdDataList {
  3315. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3316. fttype := -1
  3317. if fpd["fttype"].(string) == "1" {
  3318. fttype = 1
  3319. }
  3320. var fweight float64
  3321. var lweight float64
  3322. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3323. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  3324. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3325. join tmr t on t.id = lpp.tmrid
  3326. where lppland.fpdid =?
  3327. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3328. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3329. if err != nil {
  3330. tx.Rollback()
  3331. logs.Error(err)
  3332. }
  3333. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3334. var w float64
  3335. var status int
  3336. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3337. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3338. if weight >= 0 {
  3339. continue
  3340. }
  3341. w = weight
  3342. status = 0
  3343. } else {
  3344. // continue
  3345. if weight <= 0 {
  3346. continue
  3347. }
  3348. w = weight
  3349. status = 1
  3350. }
  3351. // for _, lppland := range lpplandtl1List {
  3352. // lweight += lppland.Lweight
  3353. // }
  3354. for _, lppland := range lpplandtl1List {
  3355. lpplandInfo := new(lpplandtlInfo)
  3356. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3357. lweight = lpplandInfo.Lweight
  3358. if status == 1 {
  3359. // if w <= lppland.Lweight {
  3360. if lppland.Maxweight <= lweight {
  3361. continue
  3362. }
  3363. if w+lweight <= lppland.Maxweight {
  3364. lppland.Lweight += w
  3365. lweight += w
  3366. fweight += w
  3367. w = 0
  3368. } else {
  3369. w = w - (lppland.Maxweight - lweight)
  3370. n := (lppland.Maxweight - lweight)
  3371. lppland.Lweight = lppland.Lweight + n
  3372. lweight += n
  3373. fweight += n
  3374. }
  3375. } else {
  3376. if lppland.Lweight == 0 {
  3377. continue
  3378. }
  3379. if w+lppland.Lweight >= 0 {
  3380. lppland.Lweight = lppland.Lweight + w
  3381. lweight = lweight + w
  3382. fweight = fweight + w
  3383. w = 0
  3384. } else {
  3385. w = w + lppland.Lweight
  3386. lweight = lweight - lppland.Lweight
  3387. fweight = fweight - lppland.Lweight
  3388. lppland.Lweight = 0
  3389. }
  3390. }
  3391. if lppland.Lweight > 0 {
  3392. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3393. if err != nil {
  3394. tx.Rollback()
  3395. logs.Error(err)
  3396. return
  3397. }
  3398. } else {
  3399. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3400. if err != nil {
  3401. tx.Rollback()
  3402. logs.Error(err)
  3403. return
  3404. }
  3405. }
  3406. if w == 0 {
  3407. break
  3408. }
  3409. // break
  3410. }
  3411. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3412. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3413. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3414. if err != nil {
  3415. tx.Rollback()
  3416. logs.Error(err)
  3417. }
  3418. if w == 0 {
  3419. break
  3420. }
  3421. }
  3422. }
  3423. }
  3424. tx.Commit()
  3425. now := time.Now()
  3426. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3427. if err != nil {
  3428. logs.Error(err)
  3429. appG.Response(http.StatusOK, e.ERROR, false)
  3430. return
  3431. }
  3432. for _, newLpplandtl1 := range newLpplandtl1List {
  3433. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3434. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3435. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3436. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3437. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3438. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3439. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3440. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3441. if err != nil {
  3442. logs.Error(err)
  3443. appG.Response(http.StatusOK, e.ERROR, false)
  3444. return
  3445. }
  3446. }
  3447. appG.Response(http.StatusOK, e.SUCCESS, true)
  3448. }
  3449. func GetProcessAnalysis(c *gin.Context) {
  3450. appG := app.Gin{C: c}
  3451. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3452. fsion := gofasion.NewFasion(string(dataByte))
  3453. sqlnamestr := fsion.Get("name").ValueStr()
  3454. offset := fsion.Get("offset").ValueDefaultInt(0)
  3455. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3456. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3457. parammaps := fsion.Get("parammaps")
  3458. tx := restful.Engine.NewSession()
  3459. err := tx.Begin()
  3460. defer func() {
  3461. switch {
  3462. case err != nil:
  3463. logging.Error("tx.Begin 事务启动失败__error:", err)
  3464. if tx != nil {
  3465. tx.Rollback()
  3466. }
  3467. default:
  3468. if tx != nil {
  3469. err = tx.Commit()
  3470. }
  3471. }
  3472. if tx != nil {
  3473. tx.Close()
  3474. }
  3475. }()
  3476. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3477. s_params := make([]interface{}, 0)
  3478. paramslist := strings.Split(p, ",")
  3479. if len(paramslist) > 0 && p != "" {
  3480. for _, value := range paramslist {
  3481. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3482. if tempv, exists := c.Get("jwt_username"); exists {
  3483. s_params = append(s_params, tempv.(string))
  3484. } else {
  3485. s_params = append(s_params, "")
  3486. }
  3487. } else {
  3488. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3489. }
  3490. }
  3491. }
  3492. tmrtnameStr := ""
  3493. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3494. if len(tmrtnameStr) == 0 {
  3495. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3496. } else {
  3497. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3498. }
  3499. }
  3500. if len(tmrtnameStr) > 0 {
  3501. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3502. }
  3503. sql += " ORDER BY d.intime"
  3504. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3505. if err != nil {
  3506. logging.Error("GetDataByName err: ", err)
  3507. msg := geterrmsg(err.Error())
  3508. appG.Response(http.StatusOK, e.ERROR, msg)
  3509. } else {
  3510. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3511. }
  3512. }
  3513. func UpdateFeedtempletStatus(c *gin.Context) {
  3514. appG := app.Gin{C: c}
  3515. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3516. fsion := gofasion.NewFasion(string(dataByte))
  3517. parammaps := fsion.Get("parammaps")
  3518. tx := restful.Engine.NewSession()
  3519. tx.Begin()
  3520. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3521. if err != nil {
  3522. tx.Rollback()
  3523. logs.Error(err)
  3524. appG.Response(http.StatusOK, e.ERROR, err)
  3525. return
  3526. }
  3527. tx.Commit()
  3528. appG.Response(http.StatusOK, e.SUCCESS, true)
  3529. }
  3530. func AddFtdry(c *gin.Context) {
  3531. appG := app.Gin{C: c}
  3532. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3533. fsion := gofasion.NewFasion(string(dataByte))
  3534. sqlnamestr := fsion.Get("name").ValueStr()
  3535. s_params := make([]interface{}, 0)
  3536. tx := restful.Engine.NewSession()
  3537. err := tx.Begin()
  3538. defer func() {
  3539. switch {
  3540. case err != nil:
  3541. if tx != nil {
  3542. tx.Rollback()
  3543. }
  3544. default:
  3545. if tx != nil {
  3546. err = tx.Commit()
  3547. }
  3548. }
  3549. if tx != nil {
  3550. tx.Close()
  3551. }
  3552. }()
  3553. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3554. if sql != "" {
  3555. parammaps := fsion.Get("parammaps")
  3556. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3557. paramslist := strings.Split(p, ",")
  3558. if len(paramslist) > 0 && p != "" {
  3559. for _, value := range paramslist {
  3560. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3561. if tempv, exists := c.Get("jwt_username"); exists {
  3562. s_params = append(s_params, tempv.(string))
  3563. } else {
  3564. s_params = append(s_params, "")
  3565. }
  3566. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3567. ids, err := setting.SnowIds.NextId()
  3568. if err != nil {
  3569. ids = time.Now().UnixNano()
  3570. logging.Info("create SnowIds err", err)
  3571. }
  3572. s_params = append(s_params, ids)
  3573. } else {
  3574. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3575. }
  3576. }
  3577. }
  3578. var actweight float64
  3579. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3580. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3581. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3582. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3583. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3584. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3585. 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()
  3586. if err != nil {
  3587. logging.Error("AddFtdry err: ", err)
  3588. msg := geterrmsg(err.Error())
  3589. appG.Response(http.StatusOK, e.ERROR, msg)
  3590. }
  3591. if len(actweightList) > 0 {
  3592. for _, item := range actweightList {
  3593. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3594. if err != nil {
  3595. logging.Error("AddFtdry err: ", err)
  3596. msg := geterrmsg(err.Error())
  3597. appG.Response(http.StatusOK, e.ERROR, msg)
  3598. }
  3599. actweight = fl
  3600. }
  3601. } else {
  3602. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3603. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3604. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3605. if err != nil {
  3606. logging.Error("AddFtdry err: ", err)
  3607. msg := geterrmsg(err.Error())
  3608. appG.Response(http.StatusOK, e.ERROR, msg)
  3609. }
  3610. for _, item := range dryList {
  3611. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3612. if err != nil {
  3613. logging.Error("AddFtdry err: ", err)
  3614. msg := geterrmsg(err.Error())
  3615. appG.Response(http.StatusOK, e.ERROR, msg)
  3616. }
  3617. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3618. }
  3619. }
  3620. if sqlnamestr == "insertFtdry" {
  3621. s_params = append(s_params, actweight)
  3622. } else if sqlnamestr == "updateFtdry" {
  3623. sql = fmt.Sprintf(sql, actweight)
  3624. }
  3625. queryData, err := execDataBySqlT(sql, s_params, tx)
  3626. if err != nil {
  3627. logging.Error("AddFtdry err: ", err)
  3628. msg := geterrmsg(err.Error())
  3629. appG.Response(http.StatusOK, e.ERROR, msg)
  3630. } else {
  3631. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3632. }
  3633. } else {
  3634. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3635. }
  3636. }
  3637. func CheckDates(c *gin.Context) {
  3638. tx := restful.Engine.NewSession()
  3639. defer tx.Close()
  3640. appG := app.Gin{C: c}
  3641. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3642. tempval_ := make(map[string]interface{})
  3643. tempCommon := make(map[string]interface{})
  3644. tempval := make([]map[string]interface{}, 0)
  3645. err := json.Unmarshal(dataByte, &tempval_)
  3646. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3647. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3648. if err != nil {
  3649. } else {
  3650. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3651. tempCommon = v
  3652. }
  3653. if v, ok := tempval_["data"].([]interface{}); ok {
  3654. for _, Tvalue := range v {
  3655. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3656. tempval = append(tempval, v1)
  3657. }
  3658. }
  3659. }
  3660. if err == nil {
  3661. if tempv, exists := c.Get("jwt_username"); exists {
  3662. tempCommon["jwt_username"] = tempv.(string)
  3663. }
  3664. for _, paramvalue := range tempval {
  3665. if _, ok := paramvalue["resultname"]; !ok {
  3666. paramvalue["resultname"] = paramvalue["name"]
  3667. }
  3668. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3669. if err != nil {
  3670. logging.Error("ExecDataParam error:", err)
  3671. }
  3672. }
  3673. if err == nil {
  3674. vmsg := ""
  3675. for _, item := range tempval {
  3676. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3677. for _, childrenList := range list.([]interface{}) {
  3678. for k, children := range childrenList.(map[string]interface{}) {
  3679. if k != "children" {
  3680. continue
  3681. }
  3682. for _, v := range children.([]map[string]interface{}) {
  3683. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3684. if k1 == "list" {
  3685. for _, v2 := range v1.([]map[string]interface{}) {
  3686. if v2["vmsg"].(string) != "1" {
  3687. if len(vmsg) == 0 {
  3688. vmsg = v2["vmsg"].(string)
  3689. } else {
  3690. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3691. }
  3692. }
  3693. }
  3694. }
  3695. }
  3696. }
  3697. }
  3698. }
  3699. }
  3700. }
  3701. if len(vmsg) > 0 {
  3702. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3703. } else {
  3704. appG.Response(http.StatusOK, e.SUCCESS, true)
  3705. }
  3706. } else {
  3707. msg := geterrmsg(err.Error())
  3708. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3709. }
  3710. }
  3711. }
  3712. if err != nil {
  3713. msg := geterrmsg(err.Error())
  3714. appG.Response(http.StatusOK, e.ERROR, msg)
  3715. }
  3716. }
  3717. 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) {
  3718. sqlname := fasion["name"].(string)
  3719. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3720. if v, ok := fasion["type"]; ok {
  3721. sqltype = v.(string)
  3722. }
  3723. sql := ""
  3724. p := ""
  3725. s_params := make([]interface{}, 0)
  3726. if sqltype != "" {
  3727. sql, p = restful.GetSqlByName(sqlname, tx)
  3728. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3729. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3730. paramslist := strings.Split(p, ",")
  3731. if len(paramslist) > 0 && p != "" {
  3732. for _, value := range paramslist {
  3733. ss := ""
  3734. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3735. ids, err := setting.SnowIds.NextId()
  3736. if err != nil {
  3737. ids = time.Now().UnixNano()
  3738. logging.Info("create SnowIds err", err)
  3739. }
  3740. s_params = append(s_params, ids)
  3741. } else {
  3742. if ss == "" && CommonParamMap != nil {
  3743. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3744. ss = valuestring
  3745. tempstrb := strings.IndexAny(valuestring, "@")
  3746. tempstre := strings.IndexAny(valuestring, ".")
  3747. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3748. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3749. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3750. }
  3751. } else {
  3752. ss = ""
  3753. }
  3754. }
  3755. }
  3756. if ss == "" && ParentParamMap != nil {
  3757. ss = getParamValue_(v, value, ParentParamMap)
  3758. }
  3759. if ss == "" && sameParamMap != nil {
  3760. ss = getParamValue(v, value, sameParamMap)
  3761. }
  3762. if ss == "" && ParamMap != nil {
  3763. ss = getParamValue(v, value, ParamMap)
  3764. }
  3765. s_params = append(s_params, ss)
  3766. }
  3767. }
  3768. }
  3769. }
  3770. }
  3771. if sql == "" {
  3772. sqltype = ""
  3773. }
  3774. if sql != "" {
  3775. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3776. if err != nil {
  3777. return nil, err
  3778. }
  3779. // fmt.Println(tempValParam)
  3780. return tempValParam.(map[string]interface{}), nil
  3781. } else {
  3782. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3783. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3784. if err != nil {
  3785. return nil, err
  3786. }
  3787. return nil, err
  3788. }
  3789. }
  3790. return nil, nil
  3791. }
  3792. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3793. var err error
  3794. subarray, ok := fasion["children"]
  3795. if ok {
  3796. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3797. tempVal_arrary := make([]map[string]interface{}, 0)
  3798. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3799. tempVal_ := make(map[string]interface{})
  3800. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3801. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3802. } else {
  3803. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3804. }
  3805. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3806. if err != nil {
  3807. return err
  3808. }
  3809. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3810. }
  3811. v.(map[string]interface{})["children"] = tempVal_arrary
  3812. }
  3813. }
  3814. return nil
  3815. }
  3816. func FpdImportExcel(c *gin.Context) {
  3817. appG := app.Gin{C: c}
  3818. inputdata := ""
  3819. c.Request.ParseForm()
  3820. params := c.Request.Form
  3821. file, _, err := c.Request.FormFile("file")
  3822. if err != nil {
  3823. appG.Response(http.StatusOK, e.ERROR, err)
  3824. return
  3825. }
  3826. sqlnamestrs := params.Get("name")
  3827. sheetname := params.Get("sheetname")
  3828. pastureid := params.Get("pastureid")
  3829. // importParams := params.Get("importParams")
  3830. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3831. // 必输项参数 (字符串格式 "field1,field2,field3")
  3832. requiredParams := params.Get("requiredParams")
  3833. // 日期参数
  3834. dateParams := params.Get("dateParams")
  3835. // 数字参数
  3836. numParams := params.Get("numParams")
  3837. //将字符串分割开
  3838. dateParamslist := strings.Split(dateParams, ",")
  3839. requiredParamslist := strings.Split(requiredParams, ",")
  3840. numParamslist := strings.Split(numParams, ",")
  3841. queryData := make([]interface{}, 0)
  3842. sqlslist := strings.Split(sqlnamestrs, ",")
  3843. xlsx1, err := excelize.OpenReader(file)
  3844. if err != nil {
  3845. fmt.Println(err)
  3846. return
  3847. }
  3848. ok := 0
  3849. error := 0
  3850. isdone := true
  3851. tx := restful.Engine.NewSession()
  3852. defer tx.Close()
  3853. languageStatus := GetLanguageStatus()
  3854. if languageStatus == "0" {
  3855. 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
  3856. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3857. if err != nil {
  3858. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3859. return
  3860. }
  3861. rows := xlsx1.GetRows(sheetname)
  3862. // 限制10000条,多余的截取掉
  3863. if len(rows) > 10000 {
  3864. rows = rows[:10000]
  3865. }
  3866. dataList := make(map[string][]*upFpdetail, 0)
  3867. for i, row := range rows {
  3868. if i > 0 {
  3869. entry := make(map[string]interface{})
  3870. outentry := make(map[string]interface{})
  3871. for j, colCell := range rows[0] {
  3872. for k, colCell1 := range row {
  3873. if j == k {
  3874. outentry[colCell] = colCell1
  3875. entry[colCell] = colCell1
  3876. }
  3877. }
  3878. }
  3879. inputdata = ""
  3880. a := ""
  3881. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3882. //校验日期格式
  3883. for _, v := range dateParamslist {
  3884. if v == "" {
  3885. continue
  3886. }
  3887. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3888. dtime, err := TransfTime(d.(string))
  3889. if err != nil {
  3890. a = strings.Trim(v, " ")
  3891. break
  3892. }
  3893. outentry[strings.Trim(v, " ")] = dtime
  3894. }
  3895. }
  3896. if a != "" {
  3897. outentry["error_msg"] = a + " 格式错误"
  3898. error++
  3899. queryData = append(queryData, outentry)
  3900. continue
  3901. }
  3902. a = ""
  3903. //校验必填格式
  3904. for _, v := range requiredParamslist {
  3905. if v == "" {
  3906. continue
  3907. }
  3908. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3909. a = strings.Trim(v, " ")
  3910. break
  3911. }
  3912. }
  3913. if a != "" {
  3914. outentry["error_msg"] = a + " 未填或格式错误"
  3915. error++
  3916. queryData = append(queryData, outentry)
  3917. continue
  3918. }
  3919. a = ""
  3920. //校验数字格式
  3921. for _, v := range numParamslist {
  3922. if v == "" {
  3923. continue
  3924. }
  3925. d, ok := outentry[strings.Trim(v, " ")]
  3926. if !ok || d == "" {
  3927. outentry[strings.Trim(v, " ")] = 0
  3928. } else {
  3929. var fl float64
  3930. switch d.(type) {
  3931. case string:
  3932. fl, err = strconv.ParseFloat(d.(string), 64)
  3933. }
  3934. if err != nil || fl < 0 {
  3935. a = strings.Trim(v, " ")
  3936. break
  3937. }
  3938. }
  3939. }
  3940. if a != "" {
  3941. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3942. error++
  3943. queryData = append(queryData, outentry)
  3944. continue
  3945. }
  3946. errExist := false
  3947. for _, sqlnamestr := range sqlslist {
  3948. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3949. paramslist := strings.Split(paramslists, ",")
  3950. if len(paramslist) > 0 {
  3951. s_params := make([]interface{}, 0)
  3952. for _, value := range paramslist {
  3953. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3954. if tempv, exists := c.Get("jwt_username"); exists {
  3955. s_params = append(s_params, tempv.(string))
  3956. } else {
  3957. s_params = append(s_params, "")
  3958. }
  3959. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3960. s_params = append(s_params, pastureid)
  3961. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3962. ids, err := setting.SnowIds.NextId()
  3963. if err != nil {
  3964. ids = time.Now().UnixNano()
  3965. logging.Info("create SnowIds err", err)
  3966. }
  3967. s_params = append(s_params, ids)
  3968. } else {
  3969. if outentry[strings.Trim(value, " ")] == nil {
  3970. s_params = append(s_params, "")
  3971. } else {
  3972. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3973. }
  3974. }
  3975. }
  3976. outentry["input"] = inputdata
  3977. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3978. if err != nil {
  3979. errExist = true
  3980. // if tx != nil {
  3981. // tx.Rollback()
  3982. // }
  3983. // if tx != nil {
  3984. // tx.Close()
  3985. // }
  3986. msg := geterrmsg(err.Error())
  3987. outentry["error_msg"] = msg
  3988. error++
  3989. queryData = append(queryData, outentry)
  3990. isdone = true
  3991. break
  3992. } else {
  3993. if len(returnmsgmap1) > 0 {
  3994. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3995. // if tx != nil {
  3996. // tx.Rollback()
  3997. // }
  3998. // if tx != nil {
  3999. // tx.Close()
  4000. // }
  4001. msg := geterrmsg(va.(string))
  4002. outentry["error_msg"] = msg
  4003. error++
  4004. queryData = append(queryData, outentry)
  4005. isdone = true
  4006. break
  4007. }
  4008. }
  4009. isdone = false
  4010. }
  4011. }
  4012. }
  4013. if !errExist {
  4014. dataexcel := make(map[string]interface{}, 0)
  4015. if _, ok := outentry["栏舍名称"]; ok {
  4016. dataexcel["barname"] = outentry["栏舍名称"]
  4017. }
  4018. if _, ok := outentry["实际牛头数"]; ok {
  4019. dataexcel["ccount"] = outentry["实际牛头数"]
  4020. }
  4021. if _, ok := outentry["系数(%)"]; ok {
  4022. dataexcel["ratio"] = outentry["系数(%)"]
  4023. }
  4024. if _, ok := outentry["配方模板"]; ok {
  4025. dataexcel["ftname"] = outentry["配方模板"]
  4026. }
  4027. if _, ok := outentry["补料配方"]; ok {
  4028. dataexcel["ptsfname"] = outentry["补料配方"]
  4029. }
  4030. if _, ok := outentry["第一班比例(%)"]; ok {
  4031. dataexcel["1"] = outentry["第一班比例(%)"]
  4032. }
  4033. if _, ok := outentry["第二班比例(%)"]; ok {
  4034. dataexcel["2"] = outentry["第二班比例(%)"]
  4035. }
  4036. if _, ok := outentry["第三班比例(%)"]; ok {
  4037. dataexcel["3"] = outentry["第三班比例(%)"]
  4038. }
  4039. if _, ok := outentry["第四班比例(%)"]; ok {
  4040. dataexcel["4"] = outentry["第四班比例(%)"]
  4041. }
  4042. if _, ok := outentry["第五班比例(%)"]; ok {
  4043. dataexcel["5"] = outentry["第五班比例(%)"]
  4044. }
  4045. if _, ok := outentry["第六班比例(%)"]; ok {
  4046. dataexcel["6"] = outentry["第六班比例(%)"]
  4047. }
  4048. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4049. if err != nil {
  4050. logs.Error(err)
  4051. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4052. return
  4053. }
  4054. if !existbar {
  4055. continue
  4056. }
  4057. _, 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()
  4058. if err != nil {
  4059. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4060. return
  4061. }
  4062. _, 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()
  4063. if err != nil {
  4064. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4065. return
  4066. }
  4067. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4068. if err != nil {
  4069. logs.Error(err)
  4070. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4071. return
  4072. }
  4073. if !existft {
  4074. continue
  4075. }
  4076. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4077. if err != nil {
  4078. logs.Error(err)
  4079. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4080. return
  4081. }
  4082. if !ftexist {
  4083. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4084. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4085. if err != nil {
  4086. logs.Error(err)
  4087. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4088. return
  4089. }
  4090. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4091. if err != nil {
  4092. logs.Error(err)
  4093. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4094. return
  4095. }
  4096. }
  4097. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4098. if err != nil {
  4099. logs.Error(err)
  4100. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4101. return
  4102. }
  4103. if !exist {
  4104. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4105. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4106. if err != nil {
  4107. logs.Error(err)
  4108. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4109. return
  4110. }
  4111. }
  4112. var feedpargs []interface{}
  4113. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4114. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4115. if _, ok := dataexcel["ftname"]; ok {
  4116. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4117. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4118. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4119. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4120. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4121. } else {
  4122. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4123. }
  4124. if _, ok := dataexcel["ptsfname"]; ok {
  4125. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4126. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4127. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4128. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4129. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4130. } else {
  4131. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4132. }
  4133. upFeedpSql += " where barname = ? and pastureid = ? "
  4134. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4135. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4136. if err != nil {
  4137. logs.Error(err)
  4138. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4139. return
  4140. }
  4141. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4142. if err != nil {
  4143. logs.Error(err)
  4144. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4145. return
  4146. }
  4147. if !exist1 {
  4148. _, 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) `,
  4149. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4150. if err != nil {
  4151. logs.Error(err)
  4152. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4153. return
  4154. }
  4155. }
  4156. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4157. if err != nil {
  4158. logs.Error(err)
  4159. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4160. return
  4161. }
  4162. if !exist2 {
  4163. _, 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) `,
  4164. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4165. if err != nil {
  4166. logs.Error(err)
  4167. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4168. return
  4169. }
  4170. }
  4171. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4172. if err != nil {
  4173. logs.Error(err)
  4174. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4175. return
  4176. }
  4177. if !exist3 {
  4178. _, 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) `,
  4179. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4180. if err != nil {
  4181. logs.Error(err)
  4182. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4183. return
  4184. }
  4185. }
  4186. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4187. if err != nil {
  4188. logs.Error(err)
  4189. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4190. return
  4191. }
  4192. if !exist4 {
  4193. _, 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) `,
  4194. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4195. if err != nil {
  4196. logs.Error(err)
  4197. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4198. return
  4199. }
  4200. }
  4201. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4202. if err != nil {
  4203. logs.Error(err)
  4204. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4205. return
  4206. }
  4207. if !exist5 {
  4208. _, 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) `,
  4209. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4210. if err != nil {
  4211. logs.Error(err)
  4212. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4213. return
  4214. }
  4215. }
  4216. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4217. if err != nil {
  4218. logs.Error(err)
  4219. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4220. return
  4221. }
  4222. if !exist6 {
  4223. _, 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) `,
  4224. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4225. if err != nil {
  4226. logs.Error(err)
  4227. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4228. return
  4229. }
  4230. }
  4231. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4232. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4233. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4234. and pastureid = ? and times = ?`
  4235. var fpdargs1 []interface{}
  4236. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4237. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4238. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4239. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4240. if err != nil {
  4241. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4242. return
  4243. }
  4244. var fpdargs2 []interface{}
  4245. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4246. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4247. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4248. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4249. if err != nil {
  4250. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4251. return
  4252. }
  4253. var fpdargs3 []interface{}
  4254. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4255. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4256. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4257. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4258. if err != nil {
  4259. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4260. return
  4261. }
  4262. var fpdargs4 []interface{}
  4263. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4264. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4265. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4266. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4267. if err != nil {
  4268. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4269. return
  4270. }
  4271. var fpdargs5 []interface{}
  4272. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4273. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4274. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4275. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4276. if err != nil {
  4277. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4278. return
  4279. }
  4280. var fpdargs6 []interface{}
  4281. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4282. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4283. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4284. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4285. if err != nil {
  4286. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4287. return
  4288. }
  4289. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4290. 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()
  4291. if err != nil {
  4292. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4293. return
  4294. }
  4295. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4296. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4297. upFpdetailList := make([]*upFpdetail, 0)
  4298. for _, newfpd := range newList {
  4299. for _, oldfpd := range oldFpdList {
  4300. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4301. var oldweight, newweight float64
  4302. if oldfpd["weight"] != nil {
  4303. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4304. }
  4305. if newfpd["weight"] != nil {
  4306. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4307. }
  4308. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4309. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4310. Old: oldweight,
  4311. New: newweight,
  4312. Times: newfpd["times"].(int64),
  4313. Ptid: newfpd["ptid"].(int64),
  4314. Fweight: fweight,
  4315. Id: oldfpd["id"].(int64),
  4316. })
  4317. break
  4318. }
  4319. }
  4320. }
  4321. // fmt.Println(dataexcel["barname"])
  4322. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4323. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4324. }
  4325. }
  4326. if !isdone {
  4327. ok++
  4328. isdone = true
  4329. }
  4330. }
  4331. for barname, v := range dataList {
  4332. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  4333. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  4334. if err != nil {
  4335. logs.Error(err, "11111")
  4336. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4337. return
  4338. }
  4339. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4340. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  4341. if err != nil {
  4342. logs.Error(err, "22222")
  4343. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4344. return
  4345. }
  4346. updateFpdetailByBar(pastureid, barname, v)
  4347. }
  4348. } else {
  4349. 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
  4350. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4351. if err != nil {
  4352. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4353. return
  4354. }
  4355. rows := xlsx1.GetRows(sheetname)
  4356. // 限制10000条,多余的截取掉
  4357. if len(rows) > 10000 {
  4358. rows = rows[:10000]
  4359. }
  4360. dataList := make(map[string][]*upFpdetail, 0)
  4361. for i, row := range rows {
  4362. if i > 0 {
  4363. entry := make(map[string]interface{})
  4364. outentry := make(map[string]interface{})
  4365. for j, colCell := range rows[0] {
  4366. for k, colCell1 := range row {
  4367. if j == k {
  4368. outentry[colCell] = colCell1
  4369. entry[colCell] = colCell1
  4370. }
  4371. }
  4372. }
  4373. inputdata = ""
  4374. a := ""
  4375. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4376. //校验日期格式
  4377. for _, v := range dateParamslist {
  4378. if v == "" {
  4379. continue
  4380. }
  4381. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  4382. dtime, err := TransfTime(d.(string))
  4383. if err != nil {
  4384. a = strings.Trim(v, " ")
  4385. break
  4386. }
  4387. outentry[strings.Trim(v, " ")] = dtime
  4388. }
  4389. }
  4390. if a != "" {
  4391. outentry["error_msg"] = a + " format error"
  4392. error++
  4393. queryData = append(queryData, outentry)
  4394. continue
  4395. }
  4396. a = ""
  4397. //校验必填格式
  4398. for _, v := range requiredParamslist {
  4399. if v == "" {
  4400. continue
  4401. }
  4402. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  4403. a = strings.Trim(v, " ")
  4404. break
  4405. }
  4406. }
  4407. if a != "" {
  4408. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4409. error++
  4410. queryData = append(queryData, outentry)
  4411. continue
  4412. }
  4413. a = ""
  4414. //校验数字格式
  4415. for _, v := range numParamslist {
  4416. if v == "" {
  4417. continue
  4418. }
  4419. d, ok := outentry[strings.Trim(v, " ")]
  4420. if !ok || d == "" {
  4421. outentry[strings.Trim(v, " ")] = 0
  4422. } else {
  4423. var fl float64
  4424. switch d.(type) {
  4425. case string:
  4426. fl, err = strconv.ParseFloat(d.(string), 64)
  4427. }
  4428. if err != nil || fl < 0 {
  4429. a = strings.Trim(v, " ")
  4430. break
  4431. }
  4432. }
  4433. }
  4434. if a != "" {
  4435. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4436. error++
  4437. queryData = append(queryData, outentry)
  4438. continue
  4439. }
  4440. errExist := false
  4441. for _, sqlnamestr := range sqlslist {
  4442. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4443. paramslist := strings.Split(paramslists, ",")
  4444. if len(paramslist) > 0 {
  4445. s_params := make([]interface{}, 0)
  4446. for _, value := range paramslist {
  4447. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4448. if tempv, exists := c.Get("jwt_username"); exists {
  4449. s_params = append(s_params, tempv.(string))
  4450. } else {
  4451. s_params = append(s_params, "")
  4452. }
  4453. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4454. s_params = append(s_params, pastureid)
  4455. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4456. ids, err := setting.SnowIds.NextId()
  4457. if err != nil {
  4458. ids = time.Now().UnixNano()
  4459. logging.Info("create SnowIds err", err)
  4460. }
  4461. s_params = append(s_params, ids)
  4462. } else {
  4463. if outentry[strings.Trim(value, " ")] == nil {
  4464. s_params = append(s_params, "")
  4465. } else {
  4466. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4467. }
  4468. }
  4469. }
  4470. outentry["input"] = inputdata
  4471. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4472. if err != nil {
  4473. errExist = true
  4474. // if tx != nil {
  4475. // tx.Rollback()
  4476. // }
  4477. // if tx != nil {
  4478. // tx.Close()
  4479. // }
  4480. msg := geterrmsg(err.Error())
  4481. outentry["error_msg"] = msg
  4482. error++
  4483. queryData = append(queryData, outentry)
  4484. isdone = true
  4485. break
  4486. } else {
  4487. if len(returnmsgmap1) > 0 {
  4488. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4489. // if tx != nil {
  4490. // tx.Rollback()
  4491. // }
  4492. // if tx != nil {
  4493. // tx.Close()
  4494. // }
  4495. msg := geterrmsg(va.(string))
  4496. outentry["error_msg"] = msg
  4497. error++
  4498. queryData = append(queryData, outentry)
  4499. isdone = true
  4500. break
  4501. }
  4502. }
  4503. isdone = false
  4504. }
  4505. }
  4506. }
  4507. if !errExist {
  4508. dataexcel := make(map[string]interface{}, 0)
  4509. if _, ok := outentry["Pen Name"]; ok {
  4510. dataexcel["barname"] = outentry["Pen Name"]
  4511. }
  4512. if _, ok := outentry["Actual Headcount"]; ok {
  4513. dataexcel["ccount"] = outentry["Actual Headcount"]
  4514. }
  4515. if _, ok := outentry["Coefficient(%)"]; ok {
  4516. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4517. }
  4518. if _, ok := outentry["Formula Template"]; ok {
  4519. dataexcel["ftname"] = outentry["Formula Template"]
  4520. }
  4521. if _, ok := outentry["Supplement Formula"]; ok {
  4522. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4523. }
  4524. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4525. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4526. }
  4527. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4528. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4529. }
  4530. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4531. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4532. }
  4533. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4534. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4535. }
  4536. if _, ok := outentry["Fifth shift Ratio(%)"]; ok {
  4537. dataexcel["5"] = outentry["Fifth shift Ratio(%)"]
  4538. }
  4539. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4540. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4541. }
  4542. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4543. if err != nil {
  4544. logs.Error(err)
  4545. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4546. return
  4547. }
  4548. if !existbar {
  4549. continue
  4550. }
  4551. _, 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()
  4552. if err != nil {
  4553. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4554. return
  4555. }
  4556. _, 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()
  4557. if err != nil {
  4558. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4559. return
  4560. }
  4561. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4562. if err != nil {
  4563. logs.Error(err)
  4564. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  4565. return
  4566. }
  4567. if !existft {
  4568. continue
  4569. }
  4570. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4571. if err != nil {
  4572. logs.Error(err)
  4573. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4574. return
  4575. }
  4576. if !ftexist {
  4577. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4578. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4579. if err != nil {
  4580. logs.Error(err)
  4581. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4582. return
  4583. }
  4584. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4585. if err != nil {
  4586. logs.Error(err)
  4587. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4588. return
  4589. }
  4590. }
  4591. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4592. if err != nil {
  4593. logs.Error(err)
  4594. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4595. return
  4596. }
  4597. if !exist {
  4598. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4599. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4600. if err != nil {
  4601. logs.Error(err)
  4602. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4603. return
  4604. }
  4605. }
  4606. var feedpargs []interface{}
  4607. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4608. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4609. if _, ok := dataexcel["ftname"]; ok {
  4610. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4611. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4612. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4613. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4614. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4615. } else {
  4616. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4617. }
  4618. if _, ok := dataexcel["ptsfname"]; ok {
  4619. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4620. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4621. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4622. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4623. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4624. } else {
  4625. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4626. }
  4627. upFeedpSql += " where barname = ? and pastureid = ? "
  4628. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4629. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4630. if err != nil {
  4631. logs.Error(err)
  4632. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4633. return
  4634. }
  4635. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4636. if err != nil {
  4637. logs.Error(err)
  4638. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4639. return
  4640. }
  4641. if !exist1 {
  4642. _, 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) `,
  4643. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4644. if err != nil {
  4645. logs.Error(err)
  4646. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4647. return
  4648. }
  4649. }
  4650. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4651. if err != nil {
  4652. logs.Error(err)
  4653. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4654. return
  4655. }
  4656. if !exist2 {
  4657. _, 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) `,
  4658. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4659. if err != nil {
  4660. logs.Error(err)
  4661. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4662. return
  4663. }
  4664. }
  4665. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4666. if err != nil {
  4667. logs.Error(err)
  4668. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4669. return
  4670. }
  4671. if !exist3 {
  4672. _, 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) `,
  4673. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4674. if err != nil {
  4675. logs.Error(err)
  4676. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4677. return
  4678. }
  4679. }
  4680. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4681. if err != nil {
  4682. logs.Error(err)
  4683. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4684. return
  4685. }
  4686. if !exist4 {
  4687. _, 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) `,
  4688. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4689. if err != nil {
  4690. logs.Error(err)
  4691. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4692. return
  4693. }
  4694. }
  4695. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4696. if err != nil {
  4697. logs.Error(err)
  4698. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4699. return
  4700. }
  4701. if !exist5 {
  4702. _, 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) `,
  4703. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4704. if err != nil {
  4705. logs.Error(err)
  4706. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4707. return
  4708. }
  4709. }
  4710. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4711. if err != nil {
  4712. logs.Error(err)
  4713. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4714. return
  4715. }
  4716. if !exist6 {
  4717. _, 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) `,
  4718. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4719. if err != nil {
  4720. logs.Error(err)
  4721. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4722. return
  4723. }
  4724. }
  4725. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4726. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4727. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4728. and pastureid = ? and times = ?`
  4729. var fpdargs1 []interface{}
  4730. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4731. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4732. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4733. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4734. if err != nil {
  4735. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4736. return
  4737. }
  4738. var fpdargs2 []interface{}
  4739. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4740. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4741. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4742. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4743. if err != nil {
  4744. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4745. return
  4746. }
  4747. var fpdargs3 []interface{}
  4748. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4749. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4750. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4751. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4752. if err != nil {
  4753. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4754. return
  4755. }
  4756. var fpdargs4 []interface{}
  4757. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4758. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4759. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4760. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4761. if err != nil {
  4762. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4763. return
  4764. }
  4765. var fpdargs5 []interface{}
  4766. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4767. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4768. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4769. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4770. if err != nil {
  4771. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4772. return
  4773. }
  4774. var fpdargs6 []interface{}
  4775. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4776. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4777. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4778. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4779. if err != nil {
  4780. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4781. return
  4782. }
  4783. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4784. 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()
  4785. if err != nil {
  4786. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4787. return
  4788. }
  4789. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4790. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4791. upFpdetailList := make([]*upFpdetail, 0)
  4792. for _, newfpd := range newList {
  4793. for _, oldfpd := range oldFpdList {
  4794. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4795. var oldweight, newweight float64
  4796. if oldfpd["weight"] != nil {
  4797. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4798. }
  4799. if newfpd["weight"] != nil {
  4800. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4801. }
  4802. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4803. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4804. Old: oldweight,
  4805. New: newweight,
  4806. Times: newfpd["times"].(int64),
  4807. Ptid: newfpd["ptid"].(int64),
  4808. Fweight: fweight,
  4809. Id: oldfpd["id"].(int64),
  4810. })
  4811. break
  4812. }
  4813. }
  4814. }
  4815. // fmt.Println(dataexcel["barname"])
  4816. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4817. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4818. }
  4819. }
  4820. if !isdone {
  4821. ok++
  4822. isdone = true
  4823. }
  4824. }
  4825. for barname, v := range dataList {
  4826. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  4827. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  4828. if err != nil {
  4829. logs.Error(err)
  4830. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4831. return
  4832. }
  4833. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4834. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  4835. if err != nil {
  4836. logs.Error(err)
  4837. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4838. return
  4839. }
  4840. updateFpdetailByBar(pastureid, barname, v)
  4841. }
  4842. }
  4843. data := make(map[string]interface{})
  4844. data["result"] = queryData
  4845. data["success"] = ok
  4846. data["err_count"] = error
  4847. appG.Response(http.StatusOK, e.SUCCESS, data)
  4848. }
  4849. type upFpdetail struct {
  4850. Old float64
  4851. New float64
  4852. Times int64
  4853. Ptid int64
  4854. Fweight float64
  4855. Id int64
  4856. // Ptsid string
  4857. }
  4858. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  4859. tx := restful.Engine.NewSession()
  4860. defer tx.Close()
  4861. tx.Begin()
  4862. 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 `,
  4863. pastureid, barname).Query().List()
  4864. if err != nil {
  4865. logs.Error(err)
  4866. }
  4867. for _, fpd := range fpdList {
  4868. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  4869. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  4870. pastureid, fpd["id"], fpd["times"]).Query().List()
  4871. if err != nil {
  4872. tx.Rollback()
  4873. logs.Error(err)
  4874. return err
  4875. }
  4876. var lweight float64
  4877. for _, lppland := range lpplandList {
  4878. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4879. lweight += lweight1
  4880. }
  4881. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4882. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4883. if fpdweight >= ptuse && lweight == ptuse {
  4884. continue
  4885. } else {
  4886. if lweight <= fpdweight {
  4887. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  4888. if err != nil {
  4889. tx.Rollback()
  4890. logs.Error(err)
  4891. return err
  4892. }
  4893. } else {
  4894. weight := lweight - fpdweight
  4895. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  4896. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  4897. if err != nil {
  4898. tx.Rollback()
  4899. logs.Error(err)
  4900. return err
  4901. }
  4902. for _, lppland := range lpplandList {
  4903. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4904. if weight >= lpplandlweight {
  4905. weight = weight - lpplandlweight
  4906. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  4907. if err != nil {
  4908. tx.Rollback()
  4909. logs.Error(err)
  4910. return err
  4911. }
  4912. } else {
  4913. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4914. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  4915. if err != nil {
  4916. tx.Rollback()
  4917. logs.Error(err)
  4918. return err
  4919. }
  4920. weight = 0
  4921. break
  4922. }
  4923. }
  4924. }
  4925. }
  4926. }
  4927. for _, list := range dataList {
  4928. ftmap := make(map[string]interface{})
  4929. ftmap["old"] = list.Old
  4930. ftmap["new"] = list.New
  4931. ftmap["times"] = list.Times
  4932. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  4933. ftmap["ptsid"] = ""
  4934. // fmt.Println(ftmap)
  4935. // 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 ,
  4936. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  4937. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  4938. // UNION
  4939. fpdDataList, err := tx.SQL(`
  4940. 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 ,
  4941. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  4942. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  4943. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  4944. if err != nil {
  4945. tx.Rollback()
  4946. logs.Error(err)
  4947. }
  4948. for _, fpd := range fpdDataList {
  4949. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  4950. // fttype := -1
  4951. // if fpd["fttype"].(string) == "1" {
  4952. fttype := 1
  4953. // }
  4954. var fweight float64
  4955. var lweight float64
  4956. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4957. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  4958. join lpplandtl1 lppland on lpp.id = lppland.lppid
  4959. join tmr t on t.id = lpp.tmrid
  4960. where lppland.fpdid =?
  4961. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4962. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  4963. if err != nil {
  4964. tx.Rollback()
  4965. logs.Error(err)
  4966. }
  4967. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  4968. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  4969. // 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
  4970. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4971. var w float64
  4972. var status int
  4973. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  4974. if weight >= 0 {
  4975. continue
  4976. }
  4977. w = weight
  4978. status = 0
  4979. } else {
  4980. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  4981. // continue
  4982. // }
  4983. w = weight
  4984. status = 1
  4985. }
  4986. // for _, lppland := range lpplandtl1List {
  4987. // lweight += lppland.Lweight
  4988. // }
  4989. for _, lppland := range lpplandtl1List {
  4990. lpplandInfo := new(lpplandtlInfo)
  4991. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  4992. lweight = lpplandInfo.Lweight
  4993. if status == 1 {
  4994. // if w <= lppland.Lweight {
  4995. if lppland.Maxweight <= lweight {
  4996. continue
  4997. }
  4998. if w+lweight <= lppland.Maxweight {
  4999. lppland.Lweight += w
  5000. lweight += w
  5001. fweight += w
  5002. w = 0
  5003. } else {
  5004. w = w - (lppland.Maxweight - lweight)
  5005. n := (lppland.Maxweight - lweight)
  5006. lppland.Lweight = lppland.Lweight + n
  5007. lweight += n
  5008. fweight += n
  5009. }
  5010. } else {
  5011. if lppland.Lweight == 0 {
  5012. continue
  5013. }
  5014. if w+lppland.Lweight >= 0 {
  5015. lppland.Lweight = lppland.Lweight + w
  5016. lweight = lweight + w
  5017. fweight = fweight + w
  5018. w = 0
  5019. } else {
  5020. w = w + lppland.Lweight
  5021. lweight = lweight - lppland.Lweight
  5022. fweight = fweight - lppland.Lweight
  5023. lppland.Lweight = 0
  5024. }
  5025. }
  5026. if lppland.Lweight > 0 {
  5027. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5028. if err != nil {
  5029. tx.Rollback()
  5030. logs.Error(err)
  5031. return err
  5032. }
  5033. } else {
  5034. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5035. if err != nil {
  5036. tx.Rollback()
  5037. logs.Error(err)
  5038. return err
  5039. }
  5040. }
  5041. if w == 0 {
  5042. break
  5043. }
  5044. }
  5045. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5046. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5047. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5048. if err != nil {
  5049. tx.Rollback()
  5050. logs.Error(err)
  5051. }
  5052. if w == 0 {
  5053. break
  5054. }
  5055. }
  5056. }
  5057. }
  5058. // for _, data := range dataList {
  5059. // fttype := -1
  5060. // if data.Ptid != -1 {
  5061. // fttype = 1
  5062. // }
  5063. // var fweight float64
  5064. // var lweight float64
  5065. // lpplandtl1List := make([]*lpplandtlInfo, 0)
  5066. // err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  5067. // join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  5068. // and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5069. // data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  5070. // if err != nil {
  5071. // tx.Rollback()
  5072. // logs.Error(err)
  5073. // return err
  5074. // }
  5075. // weight := data.Fweight
  5076. // // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5077. // var w float64
  5078. // var status int
  5079. // if data.New < data.Old {
  5080. // if weight >= 0 {
  5081. // continue
  5082. // }
  5083. // w = weight
  5084. // status = 0
  5085. // } else {
  5086. // // if weight-(data.New-data.Old) > 0 {
  5087. // // continue
  5088. // // }
  5089. // w = data.New - data.Old
  5090. // status = 1
  5091. // }
  5092. // for _, lppland := range lpplandtl1List {
  5093. // var lppdata lpplandtlInfo
  5094. // tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  5095. // lppland.Lppid, pastureid).GetFirst(&lppdata)
  5096. // if err != nil {
  5097. // tx.Rollback()
  5098. // logs.Error(err)
  5099. // return err
  5100. // }
  5101. // lweight = lppdata.Lweight
  5102. // if status == 1 {
  5103. // // if w <= lppland.Lweight {
  5104. // if lppland.Maxweight <= lweight {
  5105. // continue
  5106. // }
  5107. // if w+lweight <= lppland.Maxweight {
  5108. // lppland.Lweight += w
  5109. // lweight += w
  5110. // fweight += w
  5111. // w = 0
  5112. // } else {
  5113. // w = w - (lppland.Maxweight - lweight)
  5114. // n := (lppland.Maxweight - lweight)
  5115. // lppland.Lweight = lppland.Lweight + n
  5116. // lweight += n
  5117. // fweight += n
  5118. // }
  5119. // } else {
  5120. // if lppland.Lweight == 0 {
  5121. // continue
  5122. // }
  5123. // if w+lppland.Lweight >= 0 {
  5124. // lppland.Lweight = lppland.Lweight + w
  5125. // lweight = lweight + w
  5126. // fweight = fweight + w
  5127. // w = 0
  5128. // } else {
  5129. // w = w + lppland.Lweight
  5130. // lweight = lweight - lppland.Lweight
  5131. // fweight = fweight - lppland.Lweight
  5132. // lppland.Lweight = 0
  5133. // }
  5134. // }
  5135. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5136. // if err != nil {
  5137. // tx.Rollback()
  5138. // logs.Error(err)
  5139. // return err
  5140. // }
  5141. // break
  5142. // }
  5143. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5144. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5145. // WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  5146. // if err != nil {
  5147. // tx.Rollback()
  5148. // logs.Error(err)
  5149. // return err
  5150. // }
  5151. // // if w == 0 {
  5152. // // break
  5153. // // }
  5154. // // }
  5155. // }
  5156. err = tx.Commit()
  5157. if err != nil {
  5158. logs.Error(err)
  5159. tx.Rollback()
  5160. return err
  5161. }
  5162. now := time.Now()
  5163. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5164. if err != nil {
  5165. logs.Error(err)
  5166. return nil
  5167. }
  5168. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5169. if err != nil {
  5170. logs.Error(err)
  5171. return nil
  5172. }
  5173. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5174. if err != nil {
  5175. logs.Error(err)
  5176. return nil
  5177. }
  5178. for _, newLpplandtl1 := range newLpplandtl1List {
  5179. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5180. background,cowcount,ccountradio,lweighthis,createdate)
  5181. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5182. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5183. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5184. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5185. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5186. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5187. if err != nil {
  5188. logs.Error(err)
  5189. // appG.Response(http.StatusOK, e.ERROR, false)
  5190. return err
  5191. }
  5192. }
  5193. for _, newFpd := range newFpdDataList {
  5194. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5195. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5196. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5197. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5198. if err != nil {
  5199. logs.Error(err)
  5200. // appG.Response(http.StatusOK, e.ERROR, false)
  5201. return err
  5202. }
  5203. }
  5204. for _, newFeedp := range newFeedpList {
  5205. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5206. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5207. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5208. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5209. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5210. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5211. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5212. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5213. if err != nil {
  5214. logs.Error(err)
  5215. // appG.Response(http.StatusOK, e.ERROR, false)
  5216. return err
  5217. }
  5218. }
  5219. return nil
  5220. }
  5221. func DeleteFTdetail(c *gin.Context) {
  5222. appG := app.Gin{C: c}
  5223. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5224. fsion := gofasion.NewFasion(string(dataByte))
  5225. parammaps := fsion.Get("parammaps")
  5226. pastureid := parammaps.Get("pastureid").ValueStr()
  5227. ftid := parammaps.Get("ftid").ValueStr()
  5228. tx := restful.Engine.NewSession()
  5229. defer tx.Close()
  5230. tx.Begin()
  5231. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5232. if err != nil {
  5233. tx.Rollback()
  5234. logs.Error(err)
  5235. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5236. return
  5237. }
  5238. if parammaps.Get("type").ValueStr() == "1" {
  5239. _, err := tx.SQL(`UPDATE feedp fp
  5240. set
  5241. fp.ftweight= IFNULL(IF(
  5242. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5243. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5244. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5245. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5246. ),0),fp.feedweight = IFNULL(IF(
  5247. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5248. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5249. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5250. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5251. ),0) +ifnull(fp.supplyweight,0)
  5252. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5253. if err != nil {
  5254. tx.Rollback()
  5255. logs.Error(err)
  5256. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5257. return
  5258. }
  5259. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5260. _, err = tx.SQL(`
  5261. UPDATE fpdetail fpd
  5262. INNER JOIN feedp fp
  5263. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5264. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5265. ptuse= 0
  5266. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5267. if err != nil {
  5268. tx.Rollback()
  5269. logs.Error(err)
  5270. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5271. return
  5272. }
  5273. } else {
  5274. _, err := tx.SQL(`UPDATE feedp fp
  5275. SET
  5276. fp.supplyweight= IFNULL(IF(
  5277. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5278. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5279. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5280. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5281. ),0),fp.feedweight = IFNULL(IF(
  5282. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5283. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5284. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5285. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5286. ),0) + ifnull(fp.supplyweight,0)
  5287. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5288. if err != nil {
  5289. tx.Rollback()
  5290. logs.Error(err)
  5291. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5292. return
  5293. }
  5294. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5295. _, err = tx.SQL(`
  5296. UPDATE fpdetail fpd
  5297. INNER JOIN feedp fp
  5298. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5299. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5300. ptsrate = 0
  5301. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5302. if err != nil {
  5303. tx.Rollback()
  5304. logs.Error(err)
  5305. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5306. return
  5307. }
  5308. }
  5309. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5310. if err != nil {
  5311. tx.Rollback()
  5312. logs.Error(err)
  5313. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5314. return
  5315. }
  5316. err = tx.Commit()
  5317. if err != nil {
  5318. tx.Rollback()
  5319. logs.Error(err)
  5320. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5321. return
  5322. }
  5323. appG.Response(http.StatusOK, e.SUCCESS, true)
  5324. }
  5325. func DeleteSpillageAll(c *gin.Context) {
  5326. appG := app.Gin{C: c}
  5327. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5328. fsion := gofasion.NewFasion(string(dataByte))
  5329. parammaps := fsion.Get("parammaps")
  5330. pastureid := parammaps.Get("pastureid").ValueStr()
  5331. times := parammaps.Get("times").ValueStr()
  5332. barid := parammaps.Get("barid").ValueStr()
  5333. tx := restful.Engine.NewSession()
  5334. defer tx.Close()
  5335. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5336. if err != nil {
  5337. logs.Error(err)
  5338. appG.Response(http.StatusOK, e.ERROR, false)
  5339. return
  5340. }
  5341. now := time.Now()
  5342. for _, item := range lpplandtl1List {
  5343. go func(item map[string]interface{}) {
  5344. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5345. background,cowcount,ccountradio,lweighthis,createdate)
  5346. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5347. item["pastureid"], item["lppid"], item["barid"],
  5348. item["barname"], item["fpdid"], item["fttype"],
  5349. item["lweight"], item["sort"], item["tmrid"],
  5350. item["tmrname"], item["background"], item["cowcount"],
  5351. item["ccountradio"], item["lweighthis"], now).Execute()
  5352. if err != nil {
  5353. logs.Error(err)
  5354. appG.Response(http.StatusOK, e.ERROR, false)
  5355. return
  5356. }
  5357. }(item)
  5358. }
  5359. tx.Begin()
  5360. _, 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()
  5361. if err != nil {
  5362. tx.Rollback()
  5363. logs.Error(err)
  5364. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5365. return
  5366. }
  5367. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5368. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5369. if err != nil {
  5370. tx.Rollback()
  5371. logs.Error(err)
  5372. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5373. return
  5374. }
  5375. err = tx.Commit()
  5376. if err != nil {
  5377. tx.Rollback()
  5378. logs.Error(err)
  5379. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5380. return
  5381. }
  5382. appG.Response(http.StatusOK, e.SUCCESS, true)
  5383. }
  5384. func GetTMRListEnableTypeAll(c *gin.Context) {
  5385. appG := app.Gin{C: c}
  5386. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5387. fsion := gofasion.NewFasion(string(dataByte))
  5388. parammaps := fsion.Get("parammaps")
  5389. pastureid := parammaps.Get("pastureid").ValueStr()
  5390. tx := restful.Engine.NewSession()
  5391. defer tx.Close()
  5392. dataList, err := tx.SQL(`SELECT
  5393. eqcode,
  5394. tname,
  5395. datacaptureno,
  5396. trim(tclassid) tclassid,
  5397. concat(tname,' / ',eqcode) tmrmix,
  5398. d.label tclassname,
  5399. maxstirfeed,
  5400. remark,
  5401. tmr.enable,
  5402. TRIM(tmr.id) id,
  5403. TRIM(tmr.pastureid)pastureid
  5404. FROM
  5405. tmr
  5406. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5407. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5408. ORDER BY id DESC`, pastureid).Query().List()
  5409. if err != nil {
  5410. logs.Error(err)
  5411. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5412. return
  5413. }
  5414. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5415. if err != nil {
  5416. logs.Error(err)
  5417. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5418. return
  5419. }
  5420. var carNum int64
  5421. for _, sysopt := range sysoptData {
  5422. if sysopt["inforvalue"] == nil {
  5423. carNum = 1
  5424. } else {
  5425. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5426. }
  5427. }
  5428. id := 200
  5429. n := 0
  5430. for i := carNum; i > 0; i-- {
  5431. id++
  5432. n++
  5433. data := make(map[string]interface{}, 0)
  5434. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5435. data["tname"] = fmt.Sprintf("任意车%d", n)
  5436. data["datacaptureno"] = -2
  5437. data["tclassid"] = -2
  5438. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5439. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5440. data["maxstirfeed"] = 100000
  5441. data["remark"] = fmt.Sprintf("任意车%d", n)
  5442. data["enable"] = 1
  5443. data["id"] = fmt.Sprintf("%d", id)
  5444. data["pastureid"] = pastureid
  5445. dataList = append(dataList, data)
  5446. }
  5447. // UNION ALL
  5448. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5449. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5450. }
  5451. func GetFeedpHistory(c *gin.Context) {
  5452. appG := app.Gin{C: c}
  5453. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5454. fsion := gofasion.NewFasion(string(dataByte))
  5455. // parammaps := fsion.Get("parammaps")
  5456. bar := fsion.Get("barname").ValueStr()
  5457. startDate := fsion.Get("startDate").ValueStr()
  5458. endDate := fsion.Get("endDate").ValueStr()
  5459. tx := restful.Engine.NewSession()
  5460. defer tx.Close()
  5461. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5462. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5463. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5464. if err != nil {
  5465. logs.Error(err)
  5466. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5467. return
  5468. }
  5469. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5470. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5471. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5472. if err != nil {
  5473. logs.Error(err)
  5474. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5475. return
  5476. }
  5477. for _, feedp := range feedpList {
  5478. // LastftList, err := tx.SQL(` select tname ,id
  5479. // from feedtemplethistory where id = ?
  5480. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5481. // if err != nil {
  5482. // logs.Error(err)
  5483. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5484. // return
  5485. // }
  5486. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5487. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5488. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5489. if err != nil {
  5490. logs.Error(err)
  5491. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5492. return
  5493. }
  5494. var ftname interface{}
  5495. ftnamestatus := 0
  5496. ftname = feedp["ftname"]
  5497. var lastftid int64
  5498. if len(nextfeedpList) > 0 {
  5499. for _, ft := range nextfeedpList {
  5500. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5501. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5502. lastftid = ft["ftid"].(int64)
  5503. ftnamestatus = 1
  5504. break
  5505. }
  5506. }
  5507. }
  5508. for i, fpd := range fpdList {
  5509. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5510. fpd["weightstatus"] = 0
  5511. fpd["tratiostatus"] = 0
  5512. fpd["ftnamestatus"] = ftnamestatus
  5513. for k, fpd2 := range fpdList {
  5514. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5515. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5516. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5517. fpd["weightstatus"] = 1
  5518. }
  5519. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5520. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5521. fpd["tratiostatus"] = 1
  5522. }
  5523. break
  5524. }
  5525. }
  5526. fpd["barid"] = feedp["barid"]
  5527. fpd["barname"] = feedp["barname"]
  5528. fpd["ccount"] = feedp["ccount"]
  5529. fpd["ratio"] = feedp["ratio"]
  5530. fpd["ccountratio"] = feedp["ccountratio"]
  5531. fpd["ftid"] = feedp["ftid"]
  5532. fpd["ftname"] = ftname
  5533. fpd["ccountstatus"] = 0
  5534. fpd["ccountratiostatus"] = 0
  5535. fpd["ratiostatus"] = 0
  5536. fpd["ftnamestatus"] = 0
  5537. fpd["lastftid"] = lastftid
  5538. for _, next := range nextfeedpList {
  5539. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5540. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5541. fpd["ccountstatus"] = 1
  5542. }
  5543. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5544. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5545. fpd["ccountratiostatus"] = 1
  5546. }
  5547. if next["ratio"].(string) != fpd["ratio"].(string) {
  5548. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5549. fpd["ratiostatus"] = 1
  5550. }
  5551. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5552. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5553. // fpd["ftnamestatus"] = 1
  5554. // }
  5555. }
  5556. }
  5557. }
  5558. }
  5559. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5560. }
  5561. // func GetLpplandtl1History(c *gin.Context) {
  5562. // appG := app.Gin{C: c}
  5563. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5564. // fsion := gofasion.NewFasion(string(dataByte))
  5565. // // parammaps := fsion.Get("parammaps")
  5566. // barid := fsion.Get("barid").ValueStr()
  5567. // startDate := fsion.Get("startDate").ValueStr()
  5568. // endDate := fsion.Get("endDate").ValueStr()
  5569. // tx := restful.Engine.NewSession()
  5570. // defer tx.Close()
  5571. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5572. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5573. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5574. // // if err != nil {
  5575. // // logs.Error(err)
  5576. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5577. // // return
  5578. // // }
  5579. // // for _, feedp := range feedpList {
  5580. // // fmt.Println(feedp)
  5581. // // for i, fpd := range fpdList {
  5582. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5583. // // for k, fpd2 := range fpdList {
  5584. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5585. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5586. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5587. // // }
  5588. // // break
  5589. // // }
  5590. // // }
  5591. // // fpd["barid"] = feedp["barid"]
  5592. // // fpd["barname"] = feedp["barname"]
  5593. // // fpd["ccount"] = feedp["ccount"]
  5594. // // fpd["ratio"] = feedp["ratio"]
  5595. // // fpd["ccountratio"] = feedp["ccountratio"]
  5596. // // fpd["ftid"] = feedp["ftid"]
  5597. // // fpd["ftname"] = feedp["ftname"]
  5598. // // }
  5599. // // }
  5600. // // }
  5601. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5602. // }
  5603. func GetRemind(c *gin.Context) {
  5604. appG := app.Gin{C: c}
  5605. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5606. fsion := gofasion.NewFasion(string(dataByte))
  5607. parammaps := fsion.Get("parammaps")
  5608. pastureid := parammaps.Get("pastureid").ValueStr()
  5609. tx := restful.Engine.NewSession()
  5610. defer tx.Close()
  5611. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5612. if err != nil {
  5613. logs.Error(err)
  5614. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5615. return
  5616. }
  5617. // pastureid = "3"
  5618. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5619. if err != nil {
  5620. logs.Error(err)
  5621. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5622. return
  5623. }
  5624. defer resp.Body.Close()
  5625. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5626. buf.ReadFrom(resp.Body)
  5627. fmt.Println(string(buf.Bytes()))
  5628. respMap := make(map[string]interface{}, 0)
  5629. err = json.Unmarshal(buf.Bytes(), &respMap)
  5630. if err != nil {
  5631. logs.Error(err)
  5632. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5633. return
  5634. }
  5635. for _, data := range dataList {
  5636. r := make(map[string]interface{}, 0)
  5637. r["sys_name"] = ""
  5638. r["service_id"] = ""
  5639. r["pasture_id"] = ""
  5640. r["type_name"] = ""
  5641. r["remind_type_id"] = ""
  5642. r["remind_type"] = ""
  5643. r["push_date"] = ""
  5644. r["push_time"] = ""
  5645. r["interval_time"] = ""
  5646. r["push_limit"] = ""
  5647. r["template_id"] = ""
  5648. r["roles_id"] = ""
  5649. r["users_id"] = ""
  5650. r["date_type"] = ""
  5651. r["cycle_type"] = ""
  5652. data["data"] = r
  5653. for _, resp := range respMap["data"].([]interface{}) {
  5654. resp1 := resp.(map[string]interface{})
  5655. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5656. if resp1["push_time"] == nil {
  5657. resp1["push_time"] = ""
  5658. }
  5659. data["data"] = resp1
  5660. break
  5661. }
  5662. }
  5663. }
  5664. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5665. }
  5666. type NoticeMsgtype struct {
  5667. SysName string `json:"sys_name"`
  5668. PastureId int64 `json:"pasture_id"`
  5669. ServiceId int64 `json:"service_id"`
  5670. TypeName string `json:"type_name"`
  5671. RemindType int64 `json:"remind_type"`
  5672. PushDate int64 `json:"push_date"`
  5673. PushTime string `json:"push_time"`
  5674. IntervalTime int64 `json:"interval_time"`
  5675. PushLimit int64 `json:"push_limit"`
  5676. TemplateId string `json:"template_id"`
  5677. UsersId string `json:"users_id"`
  5678. DateType int64 `json:"date_type"`
  5679. CycleType int64 `json:"cycle_type"`
  5680. DelayTime int64 `json:"delay_time"`
  5681. Status int64 `json:"status"`
  5682. }
  5683. func UpdateRemind(c *gin.Context) {
  5684. appG := app.Gin{C: c}
  5685. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5686. parammaps := gofasion.NewFasion(string(dataByte))
  5687. // parammaps := fsion.Get("parammaps")
  5688. // user := parammaps.Get("user").ValueStr()
  5689. id := parammaps.Get("id").ValueInt64()
  5690. noticeMsgtype := new(NoticeMsgtype)
  5691. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  5692. noticeMsgtype.ServiceId = id
  5693. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  5694. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  5695. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  5696. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  5697. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  5698. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  5699. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  5700. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  5701. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  5702. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  5703. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  5704. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  5705. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  5706. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  5707. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  5708. //TODO
  5709. noticeMsgtype.SysName = "tmrWatch"
  5710. userList := parammaps.Get("user").Array()
  5711. var userstr []string
  5712. for _, user := range userList {
  5713. userstr = append(userstr, user.ValueStr())
  5714. }
  5715. tx := restful.Engine.NewSession()
  5716. defer tx.Close()
  5717. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  5718. if err != nil {
  5719. logs.Error(err)
  5720. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5721. return
  5722. }
  5723. // var jsonStr = []byte(noticeMsgtype
  5724. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  5725. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  5726. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  5727. req.Header.Set("Content-Type", "application/json")
  5728. client := &http.Client{}
  5729. resp, err := client.Do(req)
  5730. if err != nil {
  5731. logs.Error(err)
  5732. }
  5733. defer resp.Body.Close()
  5734. body, _ := ioutil.ReadAll(resp.Body)
  5735. fmt.Println("response Body:", string(body))
  5736. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  5737. if err != nil {
  5738. logs.Error(err)
  5739. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5740. return
  5741. }
  5742. defer getresp.Body.Close()
  5743. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5744. buf.ReadFrom(getresp.Body)
  5745. // fmt.Println(string(buf.Bytes()))
  5746. respMap := make(map[string]interface{}, 0)
  5747. err = json.Unmarshal(buf.Bytes(), &respMap)
  5748. if err != nil {
  5749. logs.Error(err)
  5750. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5751. return
  5752. }
  5753. for _, resp := range respMap["data"].([]interface{}) {
  5754. resp1 := resp.(map[string]interface{})
  5755. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  5756. if err != nil {
  5757. logs.Error(err)
  5758. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5759. return
  5760. }
  5761. }
  5762. appG.Response(http.StatusOK, e.SUCCESS, true)
  5763. }
  5764. func GetSpillageallHistory(c *gin.Context) {
  5765. appG := app.Gin{C: c}
  5766. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5767. parammaps := gofasion.NewFasion(string(dataByte))
  5768. barname := parammaps.Get("barname").ValueStr()
  5769. pastureid := parammaps.Get("pastureid").ValueStr()
  5770. startdate := parammaps.Get("startDate").ValueStr()
  5771. enddate := parammaps.Get("endDate").ValueStr()
  5772. tx := restful.Engine.NewSession()
  5773. defer tx.Close()
  5774. 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
  5775. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  5776. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  5777. if err != nil {
  5778. logs.Error(err)
  5779. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5780. return
  5781. }
  5782. respMap := make([]map[string]interface{}, 0)
  5783. data := make(map[interface{}]interface{})
  5784. for _, history := range historyList {
  5785. data[history["createdate"]] = history["createdate"]
  5786. }
  5787. createList := []string{}
  5788. for _, v := range data {
  5789. createList = append(createList, v.(string))
  5790. }
  5791. // sort.Sort()
  5792. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  5793. sort.Slice(createList, func(i, j int) bool {
  5794. return createList[i] > createList[j]
  5795. })
  5796. for _, v := range createList {
  5797. a := make(map[string]interface{})
  5798. a["createdate"] = data[v]
  5799. // createList = append(createList, v.(string))
  5800. respMap = append(respMap, a)
  5801. }
  5802. number := 0
  5803. dataMap := make([]interface{}, 0)
  5804. for k, resp := range respMap {
  5805. createdate := resp["createdate"].(string)
  5806. var nextcreatedate string
  5807. if len(respMap) > k+1 {
  5808. nextcreatedate = respMap[k+1]["createdate"].(string)
  5809. }
  5810. // dataList := make(map[string][]interface{})
  5811. // list := make(map[string]interface{})
  5812. times := make(map[interface{}]int)
  5813. for _, history := range historyList {
  5814. // List := make(map[interface{}][]interface{})
  5815. i := 0
  5816. if history["createdate"].(string) == createdate {
  5817. times[history["times"]]++
  5818. data := make(map[string]interface{})
  5819. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  5820. // exist := false
  5821. if nextcreatedate != "" {
  5822. for _, history1 := range historyList {
  5823. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  5824. history1["times"].(int64) == history["times"].(int64) {
  5825. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  5826. break
  5827. // exist = true
  5828. }
  5829. }
  5830. }
  5831. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5832. i++
  5833. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  5834. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  5835. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  5836. // resp["times"] = history["times"]
  5837. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5838. data1 := make(map[string]interface{})
  5839. data1["times"] = history["times"]
  5840. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5841. data1["createdate"] = resp["createdate"]
  5842. // fmt.Println(dataList)
  5843. dataMap = append(dataMap, data1)
  5844. }
  5845. if i > number {
  5846. number = i
  5847. }
  5848. // respMap = append(respMap, dataList)
  5849. }
  5850. // for k, data := range dataList {
  5851. // resp[k] = data
  5852. // }
  5853. // resp["data"] = dataList
  5854. }
  5855. // resp := make(map[string]interface{})
  5856. // sort.Strings(createList)
  5857. //
  5858. // for _, create := range createList {
  5859. // for _, r := range respMap {
  5860. // if create == r["createdate"].(string) {
  5861. // resp[create] = r
  5862. // break
  5863. // }
  5864. // }
  5865. // }
  5866. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  5867. var trainsList []interface{}
  5868. for i := 0; i < number; i++ {
  5869. trains := make(map[string]interface{})
  5870. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  5871. trains["prop"] = fmt.Sprintf("a%d", i+1)
  5872. trainsList = append(trainsList, trains)
  5873. }
  5874. respdata := make(map[string]interface{})
  5875. respdata["data"] = dataMap
  5876. respdata["trains"] = trainsList
  5877. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  5878. }
  5879. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  5880. appG := app.Gin{C: c}
  5881. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5882. parammaps := gofasion.NewFasion(string(dataByte))
  5883. ftid := parammaps.Get("ftid").ValueInt64()
  5884. lastftid := parammaps.Get("lastftid").ValueInt64()
  5885. pastureid := parammaps.Get("pastureid").ValueInt64()
  5886. // createdate := parammaps.Get("createdate").ValueStr()
  5887. tx := restful.Engine.NewSession()
  5888. defer tx.Close()
  5889. data := make(map[string]interface{})
  5890. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5891. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  5892. if err != nil {
  5893. logs.Error(err)
  5894. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5895. return
  5896. }
  5897. feedtemplet := make(map[string]interface{})
  5898. for _, f := range feedtempletList {
  5899. feedtemplet = f
  5900. }
  5901. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  5902. if err != nil {
  5903. logs.Error(err)
  5904. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5905. return
  5906. }
  5907. feedtemplet["fit"] = fitList
  5908. data["current"] = feedtemplet
  5909. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5910. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  5911. if err != nil {
  5912. logs.Error(err)
  5913. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5914. return
  5915. }
  5916. lastfeedtemplet := make(map[string]interface{})
  5917. for _, f := range lastfeedtempletList {
  5918. lastfeedtemplet = f
  5919. }
  5920. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  5921. if err != nil {
  5922. logs.Error(err)
  5923. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5924. return
  5925. }
  5926. lastfeedtemplet["fit"] = lastfitList
  5927. data["last"] = lastfeedtemplet
  5928. appG.Response(http.StatusOK, e.SUCCESS, data)
  5929. }
  5930. func GetFeedtempletHistory(c *gin.Context) {
  5931. appG := app.Gin{C: c}
  5932. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5933. parammaps := gofasion.NewFasion(string(dataByte))
  5934. ftid := parammaps.Get("ftid").ValueStr()
  5935. pastureid := parammaps.Get("pastureid").ValueInt64()
  5936. start := parammaps.Get("startdate").ValueStr()
  5937. end := parammaps.Get("enddate").ValueStr()
  5938. tx := restful.Engine.NewSession()
  5939. defer tx.Close()
  5940. 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 ?
  5941. and id = ? and pastureid = ? order by createdate desc `,
  5942. start, end, ftid, pastureid).Query().List()
  5943. if err != nil {
  5944. logs.Error(err)
  5945. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5946. return
  5947. }
  5948. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  5949. ftid, pastureid).Query().List()
  5950. if err != nil {
  5951. logs.Error(err)
  5952. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5953. return
  5954. }
  5955. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  5956. for i, ft := range ftList {
  5957. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  5958. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  5959. (select empname from user where id = fit.userId) empname,
  5960. 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
  5961. where fit.fitid = ?
  5962. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  5963. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  5964. if err != nil {
  5965. logs.Error(err)
  5966. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5967. return
  5968. }
  5969. ft["createdate"] = ft["createdate1"]
  5970. // data["tname"] = ft["tname"]
  5971. // data["tcode"] = ft["tcode"]
  5972. // data["tcolor"] = ft["tcolor"]
  5973. // data["fttype"] = ft["fttype"]
  5974. // data["ccname"] = ft["ccname"]
  5975. // data["source"] = ft["source"]
  5976. // data["version"] = ft["version"]
  5977. // data["remark"] = ft["remark"]
  5978. for n, ft2 := range ftList {
  5979. if i < n {
  5980. if ft["tname"].(string) != ft2["tname"].(string) {
  5981. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  5982. }
  5983. if _, ok := ft["tcode"]; ok {
  5984. if _, ok := ft2["tcode"]; ok {
  5985. if ft["tcode"].(string) != ft2["tcode"].(string) {
  5986. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  5987. }
  5988. }
  5989. }
  5990. if _, ok := ft["tcolor"]; ok {
  5991. if _, ok := ft2["tcolor"]; ok {
  5992. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  5993. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  5994. }
  5995. }
  5996. }
  5997. if _, ok := ft["fttype"]; ok {
  5998. if _, ok := ft2["fttype"]; ok {
  5999. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6000. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6001. }
  6002. }
  6003. }
  6004. if _, ok := ft["ccname"]; ok {
  6005. if _, ok := ft2["ccname"]; ok {
  6006. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6007. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6008. }
  6009. }
  6010. }
  6011. if _, ok := ft["source"]; ok {
  6012. if _, ok := ft2["source"]; ok {
  6013. if ft["source"].(string) != ft2["source"].(string) {
  6014. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6015. }
  6016. }
  6017. }
  6018. if _, ok := ft["version"]; ok {
  6019. if _, ok := ft2["version"]; ok {
  6020. if ft["version"].(int64) != ft2["version"].(int64) {
  6021. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6022. }
  6023. }
  6024. }
  6025. if _, ok := ft["remark"]; ok {
  6026. if _, ok := ft2["remark"]; ok {
  6027. if ft["remark"].(string) != ft2["remark"].(string) {
  6028. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6029. }
  6030. }
  6031. }
  6032. break
  6033. }
  6034. }
  6035. dataList := make([]map[string]interface{}, 0)
  6036. if len(fithisList) > 0 {
  6037. for _, fit := range fithisList {
  6038. data := make(map[string]interface{})
  6039. data["feedgroup"] = fit["feedgroup"]
  6040. data["fname"] = fit["fname"]
  6041. data["empname"] = fit["empname"]
  6042. if fit["Eweight"] != nil {
  6043. if fit["Eweight"].(string) != fit["weight"].(string) {
  6044. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6045. } else {
  6046. data["fweight"] = fit["Eweight"]
  6047. }
  6048. data["fweightstatus"] = 1
  6049. } else {
  6050. data["fweight"] = fit["weight"]
  6051. data["fweightstatus"] = 0
  6052. }
  6053. data["autosecond"] = fit["autosecond"]
  6054. // data["tname"] = ft["tname"]
  6055. // data["tcode"] = ft["tcode"]
  6056. // data["tcolor"] = ft["tcolor"]
  6057. // data["fttype"] = ft["fttype"]
  6058. // data["ccname"] = ft["ccname"]
  6059. // data["source"] = ft["source"]
  6060. // data["version"] = ft["version"]
  6061. // data["remark"] = ft["remark"]
  6062. // data["createdate"] = ft["createdate1"]
  6063. // ft["fit"] = data
  6064. dataList = append(dataList, data)
  6065. }
  6066. } else {
  6067. for _, fit := range ftdetailList {
  6068. data := make(map[string]interface{})
  6069. data["feedgroup"] = fit["feedgroup"]
  6070. data["fname"] = fit["fname"]
  6071. // if fit["Eweight"] != nil {
  6072. // data["weight"] = fit["Eweight"]
  6073. // } else {
  6074. data["fweight"] = fit["fweight"]
  6075. // }
  6076. data["autosecond"] = fit["autosecond"]
  6077. // ft["fit"] = data
  6078. dataList = append(dataList, data)
  6079. }
  6080. }
  6081. ft["fit"] = dataList
  6082. }
  6083. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6084. }
  6085. func UpdateMaterialTMR(c *gin.Context) {
  6086. appG := app.Gin{C: c}
  6087. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6088. parammaps := gofasion.NewFasion(string(dataByte))
  6089. tmrid := parammaps.Get("tmrid").ValueStr()
  6090. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6091. lppid := parammaps.Get("lppid").ValueStr()
  6092. times := parammaps.Get("times").ValueStr()
  6093. pastureid := parammaps.Get("pastureid").ValueStr()
  6094. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6095. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6096. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6097. tx := restful.Engine.NewSession()
  6098. defer tx.Close()
  6099. tx.Begin()
  6100. if tmrid != "1000" {
  6101. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6102. if err != nil {
  6103. logs.Error(err)
  6104. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6105. return
  6106. }
  6107. var maxstirfeed float64
  6108. for _, tmr := range tmrList {
  6109. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6110. }
  6111. if status == 0 {
  6112. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6113. if err != nil {
  6114. tx.Rollback()
  6115. logs.Error(err)
  6116. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6117. return
  6118. }
  6119. var lweight float64
  6120. for _, item := range lpplandtl1List {
  6121. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6122. lweight += fl
  6123. }
  6124. if lweight > maxstirfeed {
  6125. lweight = lweight - maxstirfeed
  6126. } else {
  6127. lweight = 0
  6128. }
  6129. if lweight > 0 {
  6130. lweight1 := lweight / float64(len(lpplandtl1List))
  6131. number := 0
  6132. for _, item := range lpplandtl1List {
  6133. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6134. if lweight1 >= fl {
  6135. number++
  6136. }
  6137. }
  6138. lweight := lweight / float64((len(lpplandtl1List) - number))
  6139. for _, item := range lpplandtl1List {
  6140. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6141. if lweight1 >= fl {
  6142. continue
  6143. }
  6144. if tmrtype == "1" {
  6145. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6146. if err != nil {
  6147. tx.Rollback()
  6148. logs.Error(err)
  6149. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6150. return
  6151. }
  6152. } else if tmrtype == "2" {
  6153. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6154. if err != nil {
  6155. tx.Rollback()
  6156. logs.Error(err)
  6157. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6158. return
  6159. }
  6160. }
  6161. if item["fttype"].(int64) == 0 {
  6162. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6163. if err != nil {
  6164. tx.Rollback()
  6165. logs.Error(err)
  6166. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6167. return
  6168. }
  6169. } else {
  6170. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6171. if err != nil {
  6172. tx.Rollback()
  6173. logs.Error(err)
  6174. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6175. return
  6176. }
  6177. }
  6178. }
  6179. } else {
  6180. for _, item := range lpplandtl1List {
  6181. // 自走式
  6182. if tmrtype == "1" {
  6183. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6184. if err != nil {
  6185. logs.Error(err)
  6186. tx.Rollback()
  6187. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6188. return
  6189. }
  6190. } else if tmrtype == "2" {
  6191. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6192. if err != nil {
  6193. logs.Error(err)
  6194. tx.Rollback()
  6195. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6196. return
  6197. }
  6198. }
  6199. }
  6200. }
  6201. } else if status == 1 {
  6202. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6203. if err != nil {
  6204. logs.Error(err)
  6205. tx.Rollback()
  6206. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6207. return
  6208. }
  6209. var lweight float64
  6210. for _, item := range lpplandtl1List {
  6211. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6212. lweight += fl
  6213. }
  6214. if lweight > maxstirfeed {
  6215. lweight = lweight - maxstirfeed
  6216. } else {
  6217. lweight = 0
  6218. }
  6219. for _, item := range lpplandtl1List {
  6220. if lweight > 0 {
  6221. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6222. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6223. if fl >= lweight {
  6224. item["lweight"] = fl - lweight
  6225. lweight = 0
  6226. if tmrtype == "1" {
  6227. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6228. if err != nil {
  6229. logs.Error(err)
  6230. tx.Rollback()
  6231. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6232. return
  6233. }
  6234. } else if tmrtype == "2" {
  6235. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6236. if err != nil {
  6237. logs.Error(err)
  6238. tx.Rollback()
  6239. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6240. return
  6241. }
  6242. }
  6243. if item["fttype"].(int64) == 0 {
  6244. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6245. if err != nil {
  6246. logs.Error(err)
  6247. tx.Rollback()
  6248. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6249. return
  6250. }
  6251. } else {
  6252. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6253. if err != nil {
  6254. logs.Error(err)
  6255. tx.Rollback()
  6256. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6257. return
  6258. }
  6259. }
  6260. } else {
  6261. lweight = lweight - fl
  6262. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6263. if err != nil {
  6264. logs.Error(err)
  6265. tx.Rollback()
  6266. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6267. return
  6268. }
  6269. if item["fttype"].(int64) == 0 {
  6270. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6271. if err != nil {
  6272. logs.Error(err)
  6273. tx.Rollback()
  6274. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6275. return
  6276. }
  6277. } else {
  6278. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6279. if err != nil {
  6280. logs.Error(err)
  6281. tx.Rollback()
  6282. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6283. return
  6284. }
  6285. }
  6286. }
  6287. } else {
  6288. // 自走式
  6289. if tmrtype == "1" {
  6290. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6291. if err != nil {
  6292. logs.Error(err)
  6293. tx.Rollback()
  6294. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6295. return
  6296. }
  6297. } else if tmrtype == "2" {
  6298. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6299. if err != nil {
  6300. logs.Error(err)
  6301. tx.Rollback()
  6302. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6303. return
  6304. }
  6305. }
  6306. }
  6307. }
  6308. } else {
  6309. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6310. if err != nil {
  6311. logs.Error(err)
  6312. tx.Rollback()
  6313. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6314. return
  6315. }
  6316. for _, item := range lpplandtl1List {
  6317. if item["fttype"].(int64) == 0 {
  6318. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6319. if err != nil {
  6320. logs.Error(err)
  6321. tx.Rollback()
  6322. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6323. return
  6324. }
  6325. } else {
  6326. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6327. if err != nil {
  6328. logs.Error(err)
  6329. tx.Rollback()
  6330. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6331. return
  6332. }
  6333. }
  6334. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6335. if err != nil {
  6336. logs.Error(err)
  6337. tx.Rollback()
  6338. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6339. return
  6340. }
  6341. }
  6342. }
  6343. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6344. if err != nil {
  6345. logs.Error(err)
  6346. tx.Rollback()
  6347. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6348. return
  6349. }
  6350. } else {
  6351. if status == 2 {
  6352. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6353. if err != nil {
  6354. logs.Error(err)
  6355. tx.Rollback()
  6356. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6357. return
  6358. }
  6359. for _, item := range lpplandtl1List {
  6360. if item["fttype"].(int64) == 0 {
  6361. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6362. if err != nil {
  6363. logs.Error(err)
  6364. tx.Rollback()
  6365. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6366. return
  6367. }
  6368. } else {
  6369. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6370. if err != nil {
  6371. logs.Error(err)
  6372. tx.Rollback()
  6373. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6374. return
  6375. }
  6376. }
  6377. }
  6378. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6379. if err != nil {
  6380. logs.Error(err)
  6381. tx.Rollback()
  6382. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6383. return
  6384. }
  6385. } else {
  6386. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6387. if err != nil {
  6388. logs.Error(err)
  6389. tx.Rollback()
  6390. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6391. return
  6392. }
  6393. }
  6394. }
  6395. err := tx.Commit()
  6396. if err != nil {
  6397. logs.Error(err)
  6398. tx.Rollback()
  6399. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6400. return
  6401. }
  6402. appG.Response(http.StatusOK, e.SUCCESS, true)
  6403. }
  6404. func UpdateMaterialTMRDate(c *gin.Context) {
  6405. appG := app.Gin{C: c}
  6406. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6407. parammaps := gofasion.NewFasion(string(dataByte))
  6408. tmrid := parammaps.Get("tmrid").ValueStr()
  6409. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6410. lppid := parammaps.Get("lppid").ValueStr()
  6411. times := parammaps.Get("times").ValueStr()
  6412. pastureid := parammaps.Get("pastureid").ValueStr()
  6413. date := parammaps.Get("date").ValueStr()
  6414. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6415. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6416. tx := restful.Engine.NewSession()
  6417. defer tx.Close()
  6418. tx.Begin()
  6419. if tmrid != "1000" {
  6420. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6421. if err != nil {
  6422. logs.Error(err)
  6423. tx.Rollback()
  6424. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6425. return
  6426. }
  6427. var maxstirfeed float64
  6428. for _, tmr := range tmrList {
  6429. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6430. }
  6431. if status == 0 {
  6432. 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()
  6433. if err != nil {
  6434. logs.Error(err)
  6435. tx.Rollback()
  6436. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6437. return
  6438. }
  6439. var lweight float64
  6440. for _, item := range lpplandtl1List {
  6441. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6442. lweight += fl
  6443. }
  6444. if lweight > maxstirfeed {
  6445. lweight = lweight - maxstirfeed
  6446. } else {
  6447. lweight = 0
  6448. }
  6449. if lweight > 0 {
  6450. lweight1 := lweight / float64(len(lpplandtl1List))
  6451. number := 0
  6452. for _, item := range lpplandtl1List {
  6453. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6454. if lweight1 >= fl {
  6455. number++
  6456. }
  6457. }
  6458. lweight := lweight / float64((len(lpplandtl1List) - number))
  6459. for _, item := range lpplandtl1List {
  6460. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6461. if lweight1 >= fl {
  6462. continue
  6463. }
  6464. if tmrtype == "1" {
  6465. _, 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()
  6466. if err != nil {
  6467. logs.Error(err)
  6468. tx.Rollback()
  6469. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6470. return
  6471. }
  6472. } else if tmrtype == "2" {
  6473. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6474. if err != nil {
  6475. logs.Error(err)
  6476. tx.Rollback()
  6477. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6478. return
  6479. }
  6480. }
  6481. if item["fttype"].(int64) == 0 {
  6482. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6483. if err != nil {
  6484. logs.Error(err)
  6485. tx.Rollback()
  6486. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6487. return
  6488. }
  6489. } else {
  6490. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6491. if err != nil {
  6492. logs.Error(err)
  6493. tx.Rollback()
  6494. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6495. return
  6496. }
  6497. }
  6498. }
  6499. } else {
  6500. for _, item := range lpplandtl1List {
  6501. // 自走式
  6502. if tmrtype == "1" {
  6503. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6504. if err != nil {
  6505. logs.Error(err)
  6506. tx.Rollback()
  6507. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6508. return
  6509. }
  6510. } else if tmrtype == "2" {
  6511. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6512. if err != nil {
  6513. logs.Error(err)
  6514. tx.Rollback()
  6515. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6516. return
  6517. }
  6518. }
  6519. }
  6520. }
  6521. } else if status == 1 {
  6522. 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()
  6523. if err != nil {
  6524. logs.Error(err)
  6525. tx.Rollback()
  6526. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6527. return
  6528. }
  6529. var lweight float64
  6530. for _, item := range lpplandtl1List {
  6531. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6532. lweight += fl
  6533. }
  6534. if lweight > maxstirfeed {
  6535. lweight = lweight - maxstirfeed
  6536. } else {
  6537. lweight = 0
  6538. }
  6539. for _, item := range lpplandtl1List {
  6540. if lweight > 0 {
  6541. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6542. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6543. if fl >= lweight {
  6544. item["lweight"] = fl - lweight
  6545. lweight = 0
  6546. if tmrtype == "1" {
  6547. _, 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()
  6548. if err != nil {
  6549. logs.Error(err)
  6550. tx.Rollback()
  6551. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6552. return
  6553. }
  6554. } else if tmrtype == "2" {
  6555. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6556. if err != nil {
  6557. logs.Error(err)
  6558. tx.Rollback()
  6559. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6560. return
  6561. }
  6562. }
  6563. if item["fttype"].(int64) == 0 {
  6564. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6565. if err != nil {
  6566. logs.Error(err)
  6567. tx.Rollback()
  6568. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6569. return
  6570. }
  6571. } else {
  6572. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6573. if err != nil {
  6574. logs.Error(err)
  6575. tx.Rollback()
  6576. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6577. return
  6578. }
  6579. }
  6580. } else {
  6581. lweight = lweight - fl
  6582. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6583. if err != nil {
  6584. logs.Error(err)
  6585. tx.Rollback()
  6586. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6587. return
  6588. }
  6589. if item["fttype"].(int64) == 0 {
  6590. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6591. if err != nil {
  6592. logs.Error(err)
  6593. tx.Rollback()
  6594. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6595. return
  6596. }
  6597. } else {
  6598. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6599. if err != nil {
  6600. logs.Error(err)
  6601. tx.Rollback()
  6602. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6603. return
  6604. }
  6605. }
  6606. }
  6607. } else {
  6608. // 自走式
  6609. if tmrtype == "1" {
  6610. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6611. if err != nil {
  6612. logs.Error(err)
  6613. tx.Rollback()
  6614. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6615. return
  6616. }
  6617. } else if tmrtype == "2" {
  6618. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6619. if err != nil {
  6620. logs.Error(err)
  6621. tx.Rollback()
  6622. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6623. return
  6624. }
  6625. }
  6626. }
  6627. }
  6628. } else {
  6629. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6630. if err != nil {
  6631. logs.Error(err)
  6632. tx.Rollback()
  6633. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6634. return
  6635. }
  6636. for _, item := range lpplandtl1List {
  6637. if item["fttype"].(int64) == 0 {
  6638. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6639. if err != nil {
  6640. logs.Error(err)
  6641. tx.Rollback()
  6642. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6643. return
  6644. }
  6645. } else {
  6646. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6647. if err != nil {
  6648. logs.Error(err)
  6649. tx.Rollback()
  6650. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6651. return
  6652. }
  6653. }
  6654. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6655. if err != nil {
  6656. logs.Error(err)
  6657. tx.Rollback()
  6658. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6659. return
  6660. }
  6661. }
  6662. }
  6663. _, 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()
  6664. if err != nil {
  6665. logs.Error(err)
  6666. tx.Rollback()
  6667. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6668. return
  6669. }
  6670. } else {
  6671. if status == 2 {
  6672. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  6673. if err != nil {
  6674. logs.Error(err)
  6675. tx.Rollback()
  6676. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6677. return
  6678. }
  6679. for _, item := range lpplandtl1List {
  6680. if item["fttype"].(int64) == 0 {
  6681. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6682. if err != nil {
  6683. logs.Error(err)
  6684. tx.Rollback()
  6685. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6686. return
  6687. }
  6688. } else {
  6689. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6690. if err != nil {
  6691. logs.Error(err)
  6692. tx.Rollback()
  6693. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6694. return
  6695. }
  6696. }
  6697. }
  6698. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  6699. if err != nil {
  6700. logs.Error(err)
  6701. tx.Rollback()
  6702. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6703. return
  6704. }
  6705. } else {
  6706. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  6707. if err != nil {
  6708. logs.Error(err)
  6709. tx.Rollback()
  6710. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6711. return
  6712. }
  6713. }
  6714. }
  6715. err := tx.Commit()
  6716. if err != nil {
  6717. logs.Error(err)
  6718. tx.Rollback()
  6719. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6720. return
  6721. }
  6722. appG.Response(http.StatusOK, e.SUCCESS, true)
  6723. }
  6724. func Decimal(value float64) float64 {
  6725. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  6726. return value
  6727. }
  6728. func UpdateDailyData(c *gin.Context) {
  6729. appG := app.Gin{C: c}
  6730. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6731. parammaps := gofasion.NewFasion(string(dataByte))
  6732. pid := parammaps.Get("pid").ValueDefaultStr("0")
  6733. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  6734. sort := parammaps.Get("sort").ValueDefaultStr("0")
  6735. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  6736. date := parammaps.Get("date").ValueStr()
  6737. tx := restful.Engine.NewSession()
  6738. defer tx.Close()
  6739. count, err := tx.SQL(`select count(1) from downloadedplan where pid in(select pid from downloadedplan where id= ? ) and havebutton = 1 and mydate = ?`, pid, date).Count()
  6740. if err != nil {
  6741. logs.Error("UpdateDailyData-error-0:", err)
  6742. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  6743. return
  6744. }
  6745. if count > 0 {
  6746. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  6747. return
  6748. }
  6749. tx.Begin()
  6750. if location == 0 {
  6751. fid := parammaps.Get("fid").ValueStr()
  6752. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  6753. if err != nil {
  6754. logs.Error("UpdateDailyData-error-1:", err)
  6755. tx.Rollback()
  6756. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6757. return
  6758. }
  6759. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6760. if err != nil {
  6761. logs.Error("UpdateDailyData-error-1:", err)
  6762. tx.Rollback()
  6763. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6764. return
  6765. }
  6766. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  6767. if err != nil {
  6768. fmt.Println("Error:", err)
  6769. return
  6770. }
  6771. actualWeight := weight - num
  6772. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  6773. if err != nil {
  6774. logs.Error("UpdateDailyData-error-2:", err)
  6775. tx.Rollback()
  6776. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6777. return
  6778. }
  6779. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  6780. if err != nil {
  6781. logs.Error("UpdateDailyData-error-3:", err)
  6782. tx.Rollback()
  6783. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6784. return
  6785. }
  6786. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6787. if err != nil {
  6788. logs.Error("UpdateDailyData-error-4:", err)
  6789. tx.Rollback()
  6790. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6791. return
  6792. }
  6793. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6794. if err != nil {
  6795. logs.Error("UpdateDailyData-error-5:", err)
  6796. tx.Rollback()
  6797. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6798. return
  6799. }
  6800. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6801. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6802. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6803. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6804. if err != nil {
  6805. fmt.Println("Error:", err)
  6806. return
  6807. }
  6808. // actual := actualWeight / float64(len(downloadedplanList))
  6809. for _, item := range downloadedplanList {
  6810. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6811. if err != nil {
  6812. fmt.Println("Error:", err)
  6813. return
  6814. }
  6815. actual := itemLweight / lweight * actualWeight
  6816. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6817. if err != nil {
  6818. logs.Error("UpdateDailyData-error-6:", err)
  6819. tx.Rollback()
  6820. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6821. return
  6822. }
  6823. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6824. if err != nil {
  6825. logs.Error("UpdateDailyData-error-7:", err)
  6826. tx.Rollback()
  6827. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6828. return
  6829. }
  6830. _, 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()
  6831. if err != nil {
  6832. logs.Error("UpdateDailyData-error-8:", err)
  6833. tx.Rollback()
  6834. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6835. return
  6836. }
  6837. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6838. if err != nil {
  6839. logs.Error("UpdateDailyData-error-9:", err)
  6840. tx.Rollback()
  6841. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6842. return
  6843. }
  6844. }
  6845. } else {
  6846. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6847. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6848. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6849. // if err != nil {
  6850. // fmt.Println("Error:", err)
  6851. // return
  6852. // }
  6853. for _, item := range downloadedplanList {
  6854. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6855. if err != nil {
  6856. logs.Error("UpdateDailyData-error-6:", err)
  6857. tx.Rollback()
  6858. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6859. return
  6860. }
  6861. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6862. item["lweight"], actualWeight, item["id"]).Execute()
  6863. if err != nil {
  6864. logs.Error("UpdateDailyData-error-7:", err)
  6865. tx.Rollback()
  6866. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6867. return
  6868. }
  6869. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6870. where pid = ?`, item["id"]).Execute()
  6871. if err != nil {
  6872. logs.Error("UpdateDailyData-error-8:", err)
  6873. tx.Rollback()
  6874. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6875. return
  6876. }
  6877. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6878. if err != nil {
  6879. logs.Error("UpdateDailyData-error-9:", err)
  6880. tx.Rollback()
  6881. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6882. return
  6883. }
  6884. }
  6885. }
  6886. } else {
  6887. fbarid := parammaps.Get("fbarid").ValueStr()
  6888. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  6889. if err != nil {
  6890. logs.Error("UpdateDailyData-error-10:", err)
  6891. tx.Rollback()
  6892. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6893. return
  6894. }
  6895. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6896. if err != nil {
  6897. logs.Error("UpdateDailyData-error-1:", err)
  6898. tx.Rollback()
  6899. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6900. return
  6901. }
  6902. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  6903. if err != nil {
  6904. fmt.Println("Error:", err)
  6905. return
  6906. }
  6907. actualWeight := weight - num
  6908. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  6909. if err != nil {
  6910. logs.Error("UpdateDailyData-error-11:", err)
  6911. tx.Rollback()
  6912. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6913. return
  6914. }
  6915. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  6916. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6917. if err != nil {
  6918. logs.Error("UpdateDailyData-error-12:", err)
  6919. tx.Rollback()
  6920. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6921. return
  6922. }
  6923. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6924. where pid = ? `, pid).Execute()
  6925. if err != nil {
  6926. logs.Error("UpdateDailyData-error-13:", err)
  6927. tx.Rollback()
  6928. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6929. return
  6930. }
  6931. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6932. if err != nil {
  6933. logs.Error("UpdateDailyData-error-14:", err)
  6934. tx.Rollback()
  6935. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6936. return
  6937. }
  6938. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6939. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6940. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6941. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6942. if err != nil {
  6943. fmt.Println("Error:", err)
  6944. return
  6945. }
  6946. for _, item := range downloadedplanList {
  6947. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6948. if err != nil {
  6949. fmt.Println("Error:", err)
  6950. return
  6951. }
  6952. actual := itemLweight / lweight * actualWeight
  6953. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6954. if err != nil {
  6955. logs.Error("UpdateDailyData-error-6:", err)
  6956. tx.Rollback()
  6957. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6958. return
  6959. }
  6960. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6961. if err != nil {
  6962. logs.Error("UpdateDailyData-error-7:", err)
  6963. tx.Rollback()
  6964. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6965. return
  6966. }
  6967. _, 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()
  6968. if err != nil {
  6969. logs.Error("UpdateDailyData-error-8:", err)
  6970. tx.Rollback()
  6971. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6972. return
  6973. }
  6974. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6975. if err != nil {
  6976. logs.Error("UpdateDailyData-error-9:", err)
  6977. tx.Rollback()
  6978. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6979. return
  6980. }
  6981. }
  6982. } else {
  6983. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6984. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6985. for _, item := range downloadedplanList {
  6986. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6987. // if err != nil {
  6988. // fmt.Println("Error:", err)
  6989. // return
  6990. // }
  6991. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6992. if err != nil {
  6993. logs.Error("UpdateDailyData-error-6:", err)
  6994. tx.Rollback()
  6995. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6996. return
  6997. }
  6998. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6999. item["lweight"], actualWeight, item["id"]).Execute()
  7000. if err != nil {
  7001. logs.Error("UpdateDailyData-error-7:", err)
  7002. tx.Rollback()
  7003. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7004. return
  7005. }
  7006. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7007. where pid = ?`, item["id"]).Execute()
  7008. if err != nil {
  7009. logs.Error("UpdateDailyData-error-8:", err)
  7010. tx.Rollback()
  7011. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7012. return
  7013. }
  7014. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7015. if err != nil {
  7016. logs.Error("UpdateDailyData-error-9:", err)
  7017. tx.Rollback()
  7018. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7019. return
  7020. }
  7021. }
  7022. }
  7023. }
  7024. err = tx.Commit()
  7025. if err != nil {
  7026. logs.Error("UpdateDailyData-error-20:", err)
  7027. tx.Rollback()
  7028. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7029. return
  7030. }
  7031. appG.Response(http.StatusOK, e.SUCCESS, true)
  7032. }
  7033. func GetFormulaStatistics(c *gin.Context) {
  7034. appG := app.Gin{C: c}
  7035. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7036. parammaps := gofasion.NewFasion(string(dataByte))
  7037. startTime := parammaps.Get("startTime").ValueStr()
  7038. endTime := parammaps.Get("endTime").ValueStr()
  7039. pastureId := parammaps.Get("pastureId").ValueStr()
  7040. tx := restful.Engine.NewSession()
  7041. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7042. if err != nil {
  7043. logs.Error("GetFormulaStatistics-error-1:", err)
  7044. tx.Rollback()
  7045. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7046. return
  7047. }
  7048. var feedtemplet, dateList []string
  7049. for _, f := range feedtempletList {
  7050. feedtemplet = append(feedtemplet, f["tname"].(string))
  7051. }
  7052. layout := "2006-01-02"
  7053. // s := "2023-05-01"
  7054. // e := "2023-05-23"
  7055. start, err := time.Parse(layout, startTime)
  7056. if err != nil {
  7057. fmt.Println(err)
  7058. return
  7059. }
  7060. end, err := time.Parse(layout, endTime)
  7061. if err != nil {
  7062. fmt.Println(err)
  7063. return
  7064. }
  7065. end = end.AddDate(0, 0, 1)
  7066. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7067. dateList = append(dateList, d.Format("2006-01-02"))
  7068. }
  7069. downloadedplanList, err := tx.SQL(`select count(1) total,ft.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7070. 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= ?
  7071. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7072. if err != nil {
  7073. logs.Error("GetFormulaStatistics-error-2:", err)
  7074. tx.Rollback()
  7075. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7076. return
  7077. }
  7078. var data2 [][]interface{}
  7079. for _, f := range feedtemplet {
  7080. var data1 []interface{}
  7081. for _, date := range dateList {
  7082. exist := false
  7083. for _, item := range downloadedplanList {
  7084. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7085. data1 = append(data1, item["total"])
  7086. exist = true
  7087. break
  7088. }
  7089. }
  7090. if !exist {
  7091. data1 = append(data1, 0)
  7092. }
  7093. }
  7094. data2 = append(data2, data1)
  7095. }
  7096. //前端让加的
  7097. feedtemplet = append(feedtemplet, "")
  7098. {
  7099. var data1 []interface{}
  7100. for _, f := range dateList {
  7101. // f = f + "\n"
  7102. fmt.Println(f)
  7103. data1 = append(data1, 0)
  7104. }
  7105. data2 = append(data2, data1)
  7106. }
  7107. resp := make(map[string]interface{}, 0)
  7108. resp["xdata"] = dateList
  7109. resp["data1"] = feedtemplet
  7110. resp["data2"] = data2
  7111. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7112. }
  7113. func GetPlanData(c *gin.Context) {
  7114. appG := app.Gin{C: c}
  7115. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7116. fsion := gofasion.NewFasion(string(dataByte))
  7117. sqlnamestr := fsion.Get("name").ValueStr()
  7118. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7119. offset := fsion.Get("offset").ValueDefaultInt(0)
  7120. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7121. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7122. month := fsion.Get("month").ValueDefaultStr("map")
  7123. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7124. tx := restful.Engine.NewSession()
  7125. err := tx.Begin()
  7126. defer func() {
  7127. switch {
  7128. case err != nil:
  7129. if tx != nil {
  7130. tx.Rollback()
  7131. }
  7132. default:
  7133. if tx != nil {
  7134. err = tx.Commit()
  7135. }
  7136. }
  7137. if tx != nil {
  7138. tx.Close()
  7139. }
  7140. }()
  7141. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7142. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7143. if sql != "" {
  7144. s_params := make([]interface{}, 0)
  7145. if fsion.HasKey("parammaps") {
  7146. parammaps := fsion.Get("parammaps")
  7147. paramslist := strings.Split(p, ",")
  7148. if len(paramslist) > 0 && p != "" {
  7149. for _, value := range paramslist {
  7150. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7151. if tempv, exists := c.Get("jwt_username"); exists {
  7152. s_params = append(s_params, tempv.(string))
  7153. } else {
  7154. s_params = append(s_params, "")
  7155. }
  7156. } else {
  7157. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7158. }
  7159. }
  7160. }
  7161. }
  7162. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7163. if err != nil {
  7164. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7165. } else {
  7166. paramslist1 := strings.Split(p1, ",")
  7167. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7168. s_params1 := make([]interface{}, 0)
  7169. if len(paramslist1) > 0 && p1 != "" {
  7170. for _, v := range paramslist1 {
  7171. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7172. }
  7173. }
  7174. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7175. for _, item := range arr {
  7176. trgaddressList := []string{}
  7177. if _, ok := item["trgaddress"]; ok {
  7178. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7179. for _, str := range trgaddressList1 {
  7180. if str != "" {
  7181. trgaddressList = append(trgaddressList, str)
  7182. }
  7183. }
  7184. }
  7185. item["trgaddressList"] = trgaddressList
  7186. }
  7187. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7188. }
  7189. // var wg sync.WaitGroup
  7190. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7191. // wg.Add(1)
  7192. // go func(value map[string]interface{}) {
  7193. // defer wg.Done()
  7194. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7195. // }(value)
  7196. // }
  7197. // wg.Wait()
  7198. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7199. }
  7200. } else {
  7201. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7202. }
  7203. }
  7204. func PostPlanData(c *gin.Context) {
  7205. appG := app.Gin{C: c}
  7206. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7207. fsion := gofasion.NewFasion(string(dataByte))
  7208. logging.Info("PostRJSBData err: ", string(dataByte))
  7209. s_params := make([]interface{}, 0)
  7210. tx := restful.Engine.NewSession()
  7211. err := tx.Begin()
  7212. defer func() {
  7213. switch {
  7214. case err != nil:
  7215. if tx != nil {
  7216. tx.Rollback()
  7217. }
  7218. default:
  7219. if tx != nil {
  7220. err = tx.Commit()
  7221. }
  7222. }
  7223. if tx != nil {
  7224. tx.Close()
  7225. }
  7226. }()
  7227. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7228. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7229. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7230. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7231. if !fsion.HasKey("parammaps") {
  7232. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7233. return
  7234. }
  7235. parammaps := fsion.Get("parammaps")
  7236. // paramslist := strings.Split(p, ",")
  7237. // if len(paramslist) > 0 && p != "" {
  7238. // for _, value := range paramslist {
  7239. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7240. // }
  7241. // }
  7242. // _, err = tx.SQL(sql, s_params...).Execute()
  7243. // if err != nil {
  7244. // logging.Error("PostRJSBData err: ", err)
  7245. // msg := geterrmsg(err.Error())
  7246. // appG.Response(http.StatusOK, e.ERROR, msg)
  7247. // return
  7248. // }
  7249. s_params = make([]interface{}, 0)
  7250. paramslist := strings.Split(p1, ",")
  7251. if len(paramslist) > 0 && p1 != "" {
  7252. for _, value := range paramslist {
  7253. // if value == "ID" {
  7254. // id := parammaps.Get("ID").ValueStr()
  7255. // pastureid := parammaps.Get("pastureid").ValueStr()
  7256. // 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
  7257. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7258. // if err != nil {
  7259. // logging.Error("PostRJSBData err: ", err)
  7260. // msg := geterrmsg(err.Error())
  7261. // appG.Response(http.StatusOK, e.ERROR, msg)
  7262. // return
  7263. // }
  7264. // for _, item := range datalist {
  7265. // id = item["id"]
  7266. // }
  7267. // s_params = append(s_params, id)
  7268. // } else {
  7269. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7270. // }
  7271. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7272. }
  7273. }
  7274. _, err = tx.SQL(sql1, s_params...).Execute()
  7275. if err != nil {
  7276. logging.Error("PostRJSBData1 err: ", err)
  7277. msg := geterrmsg(err.Error())
  7278. appG.Response(http.StatusOK, e.ERROR, msg)
  7279. return
  7280. }
  7281. s_params = make([]interface{}, 0)
  7282. paramslist = strings.Split(p2, ",")
  7283. if len(paramslist) > 0 && p2 != "" {
  7284. for _, value := range paramslist {
  7285. if value == "ID" {
  7286. id := parammaps.Get("ID").ValueStr()
  7287. pastureid := parammaps.Get("pastureid").ValueStr()
  7288. 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
  7289. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7290. if err != nil {
  7291. logging.Error("PostRJSBData err: ", err)
  7292. msg := geterrmsg(err.Error())
  7293. appG.Response(http.StatusOK, e.ERROR, msg)
  7294. return
  7295. }
  7296. for _, item := range datalist {
  7297. id = item["id"]
  7298. }
  7299. s_params = append(s_params, id)
  7300. } else {
  7301. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7302. }
  7303. }
  7304. }
  7305. _, err = tx.SQL(sql2, s_params...).Execute()
  7306. if err != nil {
  7307. logging.Error("PostRJSBData2 err: ", err)
  7308. msg := geterrmsg(err.Error())
  7309. appG.Response(http.StatusOK, e.ERROR, msg)
  7310. return
  7311. }
  7312. s_params = make([]interface{}, 0)
  7313. paramslist = strings.Split(p3, ",")
  7314. if len(paramslist) > 0 && p3 != "" {
  7315. for _, value := range paramslist {
  7316. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7317. }
  7318. }
  7319. _, err = tx.SQL(sql3, s_params...).Execute()
  7320. if err != nil {
  7321. logging.Error("PostRJSBData3 err: ", err)
  7322. msg := geterrmsg(err.Error())
  7323. appG.Response(http.StatusOK, e.ERROR, msg)
  7324. return
  7325. }
  7326. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7327. }
  7328. func CheckFeedTrgaddress(c *gin.Context) {
  7329. appG := app.Gin{C: c}
  7330. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7331. fsion := gofasion.NewFasion(string(dataByte))
  7332. fclassid := fsion.Get("fclassid").ValueStr()
  7333. feedId := fsion.Get("feedId").ValueStr()
  7334. backup1 := fsion.Get("backup1").ValueStr()
  7335. backup1List := strings.Split(backup1, ",")
  7336. tx := restful.Engine.NewSession()
  7337. defer tx.Close()
  7338. // if backup1 != "" {
  7339. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7340. for _, feed := range feedList {
  7341. if feed["backup1"] == "" {
  7342. continue
  7343. }
  7344. feedbackupList := strings.Split(feed["backup1"], ",")
  7345. for _, feedbackup := range feedbackupList {
  7346. for _, backup := range backup1List {
  7347. if feedbackup == backup {
  7348. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7349. return
  7350. }
  7351. }
  7352. }
  7353. }
  7354. // }
  7355. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7356. }
  7357. func ThiGetDataByName(c *gin.Context) {
  7358. appG := app.Gin{C: c}
  7359. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7360. fsion := gofasion.NewFasion(string(dataByte))
  7361. sqlnamestr := fsion.Get("name").ValueStr()
  7362. offset := fsion.Get("offset").ValueDefaultInt(0)
  7363. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7364. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7365. tx := restful.Engine.NewSession()
  7366. err := tx.Begin()
  7367. defer func() {
  7368. switch {
  7369. case err != nil:
  7370. logging.Error("tx.Begin 事务启动失败__error:", err)
  7371. if tx != nil {
  7372. tx.Rollback()
  7373. }
  7374. default:
  7375. if tx != nil {
  7376. err = tx.Commit()
  7377. }
  7378. }
  7379. if tx != nil {
  7380. tx.Close()
  7381. }
  7382. }()
  7383. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7384. if sql != "" {
  7385. s_params := make([]interface{}, 0)
  7386. if fsion.HasKey("parammaps") {
  7387. parammaps := fsion.Get("parammaps")
  7388. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7389. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7390. }
  7391. paramslist := strings.Split(p, ",")
  7392. if len(paramslist) > 0 && p != "" {
  7393. for _, value := range paramslist {
  7394. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7395. if tempv, exists := c.Get("jwt_username"); exists {
  7396. s_params = append(s_params, tempv.(string))
  7397. } else {
  7398. s_params = append(s_params, "")
  7399. }
  7400. } else {
  7401. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7402. }
  7403. }
  7404. }
  7405. } else if fsion.HasKey("params") {
  7406. params := fsion.Get("params").Array()
  7407. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7408. for _, v_params := range params {
  7409. s_params = append(s_params, v_params.ValueStr())
  7410. }
  7411. }
  7412. if returntype == "xlsx" {
  7413. var xlsxfile *xlsx.File
  7414. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7415. //c.File("c:/dd.xlsx")
  7416. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7417. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7418. c.Header("Content-Transfer-Encoding", "binary")
  7419. _ = xlsxfile.Write(c.Writer)
  7420. } else {
  7421. if sqlnamestr == "getHomepageStr" {
  7422. parammaps := fsion.Get("parammaps")
  7423. pastureid := parammaps.Get("pastureid").ValueStr()
  7424. var montimeList []float64
  7425. var montime float64
  7426. var wg sync.WaitGroup
  7427. now := time.Now()
  7428. for i := 0; i < 30; i++ {
  7429. wg.Add(1)
  7430. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7431. go func(nowstr string) {
  7432. defer wg.Done()
  7433. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7434. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7435. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7436. montimeList = append(montimeList, m)
  7437. }(nowstr)
  7438. }
  7439. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7440. if err != nil {
  7441. logging.Error("GetDataByName err: ", err)
  7442. msg := geterrmsg(err.Error())
  7443. appG.Response(http.StatusOK, e.ERROR, msg)
  7444. }
  7445. wg.Wait()
  7446. for _, m := range montimeList {
  7447. montime += m
  7448. }
  7449. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7450. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7451. return
  7452. }
  7453. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7454. if err != nil {
  7455. logging.Error("GetDataByName err: ", err)
  7456. msg := geterrmsg(err.Error())
  7457. appG.Response(http.StatusOK, e.ERROR, msg)
  7458. } else {
  7459. if sqlnamestr == "getFeedTrgaddressList" {
  7460. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7461. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7462. trgaddressList := []string{}
  7463. for _, str := range trgaddressList1 {
  7464. if str != "" {
  7465. trgaddressList = append(trgaddressList, str)
  7466. }
  7467. }
  7468. item["trgaddressList"] = trgaddressList
  7469. }
  7470. }
  7471. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7472. }
  7473. }
  7474. } else {
  7475. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7476. }
  7477. }
  7478. // func ToggleCcount(c *gin.Context) {
  7479. // appG := app.Gin{C: c}
  7480. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7481. // fsion := gofasion.NewFasion(string(dataByte))
  7482. // // 0 实际 1 软件
  7483. // status := fsion.Get("status").ValueDefaultInt64(0)
  7484. // pastureId := fsion.Get("pastureId").ValueStr()
  7485. // tx := restful.Engine.NewSession()
  7486. // err := tx.Begin()
  7487. // defer func() {
  7488. // switch {
  7489. // case err != nil:
  7490. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7491. // if tx != nil {
  7492. // tx.Rollback()
  7493. // }
  7494. // default:
  7495. // if tx != nil {
  7496. // err = tx.Commit()
  7497. // }
  7498. // }
  7499. // if tx != nil {
  7500. // tx.Close()
  7501. // }
  7502. // }()
  7503. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7504. // if err != nil {
  7505. // logs.Error(err)
  7506. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7507. // return
  7508. // }
  7509. // for _, bar := range barList {
  7510. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7511. // if err != nil {
  7512. // logs.Error(err)
  7513. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7514. // return
  7515. // }
  7516. // if !exist {
  7517. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7518. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7519. // if err != nil {
  7520. // logs.Error(err)
  7521. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7522. // return
  7523. // }
  7524. // }
  7525. // }
  7526. // if status == 0 {
  7527. // tx.Exec(`update feedp set ccount = actualcount `)
  7528. // }else{
  7529. // tx.Exec(`update feedp set ccount = softccount `)
  7530. // }
  7531. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7532. // if err != nil {
  7533. // logs.Error(err)
  7534. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7535. // return
  7536. // }
  7537. // for _, feedpData :=range feedpList{
  7538. // var feedpargs []interface{}
  7539. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7540. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7541. // if _, ok := feedpData["ftname"]; ok {
  7542. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7543. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7544. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7545. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7546. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7547. // } else {
  7548. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7549. // }
  7550. // if _, ok := feedpData["ptsfname"]; ok {
  7551. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7552. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7553. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7554. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7555. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7556. // } else {
  7557. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7558. // }
  7559. // upFeedpSql += " where barname = ? and pastureid = ? "
  7560. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7561. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7562. // if err != nil {
  7563. // logs.Error(err)
  7564. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7565. // return
  7566. // }
  7567. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7568. // if err != nil {
  7569. // logs.Error(err)
  7570. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7571. // return
  7572. // }
  7573. // if !exist1 {
  7574. // _, 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) `,
  7575. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7576. // if err != nil {
  7577. // logs.Error(err)
  7578. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7579. // return
  7580. // }
  7581. // }
  7582. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7583. // if err != nil {
  7584. // logs.Error(err)
  7585. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7586. // return
  7587. // }
  7588. // if !exist2 {
  7589. // _, 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) `,
  7590. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7591. // if err != nil {
  7592. // logs.Error(err)
  7593. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7594. // return
  7595. // }
  7596. // }
  7597. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7598. // if err != nil {
  7599. // logs.Error(err)
  7600. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7601. // return
  7602. // }
  7603. // if !exist3 {
  7604. // _, 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) `,
  7605. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7606. // if err != nil {
  7607. // logs.Error(err)
  7608. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7609. // return
  7610. // }
  7611. // }
  7612. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7613. // if err != nil {
  7614. // logs.Error(err)
  7615. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7616. // return
  7617. // }
  7618. // if !exist4 {
  7619. // _, 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) `,
  7620. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7621. // if err != nil {
  7622. // logs.Error(err)
  7623. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7624. // return
  7625. // }
  7626. // }
  7627. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7628. // if err != nil {
  7629. // logs.Error(err)
  7630. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7631. // return
  7632. // }
  7633. // if !exist5 {
  7634. // _, 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) `,
  7635. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7636. // if err != nil {
  7637. // logs.Error(err)
  7638. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7639. // return
  7640. // }
  7641. // }
  7642. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7643. // if err != nil {
  7644. // logs.Error(err)
  7645. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7646. // return
  7647. // }
  7648. // if !exist6 {
  7649. // _, 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) `,
  7650. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7651. // if err != nil {
  7652. // logs.Error(err)
  7653. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7654. // return
  7655. // }
  7656. // }
  7657. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7658. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7659. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7660. // and pastureid = ? and times = ?`
  7661. // var fpdargs1 []interface{}
  7662. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7663. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7664. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7665. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7666. // if err != nil {
  7667. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7668. // return
  7669. // }
  7670. // var fpdargs2 []interface{}
  7671. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7672. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7673. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7674. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7675. // if err != nil {
  7676. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7677. // return
  7678. // }
  7679. // var fpdargs3 []interface{}
  7680. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7681. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7682. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7683. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7684. // if err != nil {
  7685. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7686. // return
  7687. // }
  7688. // var fpdargs4 []interface{}
  7689. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7690. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7691. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7692. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7693. // if err != nil {
  7694. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7695. // return
  7696. // }
  7697. // var fpdargs5 []interface{}
  7698. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7699. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7700. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7701. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7702. // if err != nil {
  7703. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7704. // return
  7705. // }
  7706. // var fpdargs6 []interface{}
  7707. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7708. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7709. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7710. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7711. // if err != nil {
  7712. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7713. // return
  7714. // }
  7715. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7716. // 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()
  7717. // if err != nil {
  7718. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7719. // return
  7720. // }
  7721. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7722. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7723. // upFpdetailList := make([]*upFpdetail, 0)
  7724. // for _, newfpd := range newList {
  7725. // for _, oldfpd := range oldFpdList {
  7726. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7727. // var oldweight, newweight float64
  7728. // if oldfpd["weight"] != nil {
  7729. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7730. // }
  7731. // if newfpd["weight"] != nil {
  7732. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7733. // }
  7734. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7735. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  7736. // Old: oldweight,
  7737. // New: newweight,
  7738. // Times: newfpd["times"].(int64),
  7739. // Ptid: newfpd["ptid"].(int64),
  7740. // Fweight: fweight,
  7741. // Id: oldfpd["id"].(int64),
  7742. // })
  7743. // break
  7744. // }
  7745. // }
  7746. // }
  7747. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  7748. // }
  7749. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  7750. // }
  7751. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  7752. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  7753. if err != nil {
  7754. return err
  7755. }
  7756. for _, item := range feedpList {
  7757. // if item["ftid"].(string) != data["ftid"].(string) {
  7758. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  7759. if err != nil {
  7760. return err
  7761. }
  7762. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  7763. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  7764. if err != nil {
  7765. return err
  7766. }
  7767. // }
  7768. }
  7769. return nil
  7770. }
  7771. func PostPlanDatas(c *gin.Context) {
  7772. appG := app.Gin{C: c}
  7773. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7774. fsions := gofasion.NewFasion(string(dataByte))
  7775. logging.Info("PostRJSBDatas err: ", string(dataByte))
  7776. tx := restful.Engine.NewSession()
  7777. err := tx.Begin()
  7778. defer func() {
  7779. switch {
  7780. case err != nil:
  7781. if tx != nil {
  7782. tx.Rollback()
  7783. }
  7784. default:
  7785. if tx != nil {
  7786. err = tx.Commit()
  7787. }
  7788. }
  7789. if tx != nil {
  7790. tx.Close()
  7791. }
  7792. }()
  7793. pastureId := fsions.Get("pastureid").ValueStr()
  7794. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7795. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  7796. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  7797. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  7798. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7799. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7800. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7801. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7802. for _, parammaps := range fsions.Get("arrList").Array() {
  7803. fmt.Println(parammaps.Json())
  7804. if parammaps.Json() == "null" {
  7805. continue
  7806. }
  7807. // if !fsion.HasKey("arrList") {
  7808. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7809. // return
  7810. // continue
  7811. // }
  7812. // parammaps := fsion.Get("arrList")
  7813. s_params := make([]interface{}, 0)
  7814. // paramslist := strings.Split(p, ",")
  7815. // if len(paramslist) > 0 && p != "" {
  7816. // for _, value := range paramslist {
  7817. // if value == "pastureid" {
  7818. // s_params = append(s_params, pastureId)
  7819. // } else {
  7820. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7821. // }
  7822. // }
  7823. // }
  7824. // _, err = tx.SQL(sql, s_params...).Execute()
  7825. // if err != nil {
  7826. // logging.Error("PostRJSBData err: ", err)
  7827. // msg := geterrmsg(err.Error())
  7828. // appG.Response(http.StatusOK, e.ERROR, msg)
  7829. // return
  7830. // }
  7831. s_params = make([]interface{}, 0)
  7832. paramslist := strings.Split(p1, ",")
  7833. if len(paramslist) > 0 && p1 != "" {
  7834. for _, value := range paramslist {
  7835. // if value == "ID" {
  7836. // id := parammaps.Get("ID").ValueStr()
  7837. // pastureid := parammaps.Get("pastureid").ValueStr()
  7838. // 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
  7839. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7840. // if err != nil {
  7841. // logging.Error("PostRJSBData err: ", err)
  7842. // msg := geterrmsg(err.Error())
  7843. // appG.Response(http.StatusOK, e.ERROR, msg)
  7844. // return
  7845. // }
  7846. // for _, item := range datalist {
  7847. // id = item["id"]
  7848. // }
  7849. // s_params = append(s_params, id)
  7850. // } else {
  7851. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7852. // }
  7853. if value == "pastureid" {
  7854. s_params = append(s_params, pastureId)
  7855. } else {
  7856. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7857. }
  7858. }
  7859. }
  7860. _, err = tx.SQL(sql1, s_params...).Execute()
  7861. if err != nil {
  7862. logging.Error("PostRJSBData1 err: ", err)
  7863. msg := geterrmsg(err.Error())
  7864. appG.Response(http.StatusOK, e.ERROR, msg)
  7865. return
  7866. }
  7867. s_params = make([]interface{}, 0)
  7868. paramslist = strings.Split(p2, ",")
  7869. if len(paramslist) > 0 && p2 != "" {
  7870. for _, value := range paramslist {
  7871. if value == "ID" {
  7872. id := parammaps.Get("ID").ValueStr()
  7873. pastureid := parammaps.Get("pastureid").ValueStr()
  7874. 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
  7875. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7876. if err != nil {
  7877. logging.Error("PostRJSBData err: ", err)
  7878. msg := geterrmsg(err.Error())
  7879. appG.Response(http.StatusOK, e.ERROR, msg)
  7880. return
  7881. }
  7882. for _, item := range datalist {
  7883. id = item["id"]
  7884. }
  7885. s_params = append(s_params, id)
  7886. } else if value == "pastureid" {
  7887. s_params = append(s_params, pastureId)
  7888. } else {
  7889. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7890. }
  7891. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7892. }
  7893. }
  7894. _, err = tx.SQL(sql2, s_params...).Execute()
  7895. if err != nil {
  7896. logging.Error("PostRJSBData2 err: ", err)
  7897. msg := geterrmsg(err.Error())
  7898. appG.Response(http.StatusOK, e.ERROR, msg)
  7899. return
  7900. }
  7901. s_params = make([]interface{}, 0)
  7902. paramslist = strings.Split(p3, ",")
  7903. if len(paramslist) > 0 && p3 != "" {
  7904. for _, value := range paramslist {
  7905. if value == "pastureid" {
  7906. s_params = append(s_params, pastureId)
  7907. } else {
  7908. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7909. }
  7910. }
  7911. }
  7912. _, err = tx.SQL(sql3, s_params...).Execute()
  7913. if err != nil {
  7914. logging.Error("PostRJSBData3 err: ", err)
  7915. msg := geterrmsg(err.Error())
  7916. appG.Response(http.StatusOK, e.ERROR, msg)
  7917. return
  7918. }
  7919. }
  7920. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7921. }
  7922. func FpdBatchEdit(c *gin.Context) {
  7923. appG := app.Gin{C: c}
  7924. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7925. fsions := gofasion.NewFasion(string(dataByte))
  7926. barList := fsions.Get("barList").Array()
  7927. pastureid := fsions.Get("pastureId").ValueStr()
  7928. tx := restful.Engine.NewSession()
  7929. defer tx.Close()
  7930. 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
  7931. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7932. if err != nil {
  7933. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7934. return
  7935. }
  7936. for _, barFsions := range barList {
  7937. dataexcel := make(map[string]interface{}, 0)
  7938. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  7939. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  7940. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  7941. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  7942. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  7943. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  7944. continue
  7945. }
  7946. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  7947. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  7948. if err != nil {
  7949. logs.Error(err)
  7950. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7951. return
  7952. }
  7953. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  7954. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  7955. if err != nil {
  7956. logs.Error(err)
  7957. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7958. return
  7959. }
  7960. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  7961. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  7962. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  7963. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  7964. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  7965. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  7966. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  7967. if err != nil {
  7968. logs.Error(err)
  7969. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7970. return
  7971. }
  7972. if !ftexist {
  7973. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  7974. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7975. if err != nil {
  7976. logs.Error(err)
  7977. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7978. return
  7979. }
  7980. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7981. if err != nil {
  7982. logs.Error(err)
  7983. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7984. return
  7985. }
  7986. }
  7987. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7988. if err != nil {
  7989. logs.Error(err)
  7990. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7991. return
  7992. }
  7993. if !exist {
  7994. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7995. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  7996. if err != nil {
  7997. logs.Error(err)
  7998. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7999. return
  8000. }
  8001. }
  8002. var feedpargs []interface{}
  8003. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8004. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8005. if _, ok := dataexcel["ftname"]; ok {
  8006. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8007. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8008. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8009. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8010. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8011. } else {
  8012. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8013. }
  8014. if _, ok := dataexcel["ptsfname"]; ok {
  8015. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8016. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8017. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8018. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8019. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8020. } else {
  8021. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8022. }
  8023. upFeedpSql += " where barname = ? and pastureid = ? "
  8024. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8025. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8026. if err != nil {
  8027. logs.Error(err)
  8028. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8029. return
  8030. }
  8031. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8032. if err != nil {
  8033. logs.Error(err)
  8034. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8035. return
  8036. }
  8037. if !exist1 {
  8038. _, 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) `,
  8039. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8040. if err != nil {
  8041. logs.Error(err)
  8042. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8043. return
  8044. }
  8045. }
  8046. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8047. if err != nil {
  8048. logs.Error(err)
  8049. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8050. return
  8051. }
  8052. if !exist2 {
  8053. _, 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) `,
  8054. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8055. if err != nil {
  8056. logs.Error(err)
  8057. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8058. return
  8059. }
  8060. }
  8061. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8062. if err != nil {
  8063. logs.Error(err)
  8064. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8065. return
  8066. }
  8067. if !exist3 {
  8068. _, 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) `,
  8069. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8070. if err != nil {
  8071. logs.Error(err)
  8072. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8073. return
  8074. }
  8075. }
  8076. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8077. if err != nil {
  8078. logs.Error(err)
  8079. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8080. return
  8081. }
  8082. if !exist4 {
  8083. _, 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) `,
  8084. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8085. if err != nil {
  8086. logs.Error(err)
  8087. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8088. return
  8089. }
  8090. }
  8091. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8092. if err != nil {
  8093. logs.Error(err)
  8094. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8095. return
  8096. }
  8097. if !exist5 {
  8098. _, 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) `,
  8099. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8100. if err != nil {
  8101. logs.Error(err)
  8102. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8103. return
  8104. }
  8105. }
  8106. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8107. if err != nil {
  8108. logs.Error(err)
  8109. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8110. return
  8111. }
  8112. if !exist6 {
  8113. _, 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) `,
  8114. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8115. if err != nil {
  8116. logs.Error(err)
  8117. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8118. return
  8119. }
  8120. }
  8121. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8122. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8123. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8124. and pastureid = ? and times = ?`
  8125. var fpdargs1 []interface{}
  8126. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8127. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8128. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8129. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8130. if err != nil {
  8131. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8132. return
  8133. }
  8134. var fpdargs2 []interface{}
  8135. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8136. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8137. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8138. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8139. if err != nil {
  8140. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8141. return
  8142. }
  8143. var fpdargs3 []interface{}
  8144. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8145. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8146. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8147. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8148. if err != nil {
  8149. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8150. return
  8151. }
  8152. var fpdargs4 []interface{}
  8153. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8154. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8155. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8156. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8157. if err != nil {
  8158. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8159. return
  8160. }
  8161. var fpdargs5 []interface{}
  8162. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8163. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8164. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8165. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8166. if err != nil {
  8167. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8168. return
  8169. }
  8170. var fpdargs6 []interface{}
  8171. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8172. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8173. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8174. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8175. if err != nil {
  8176. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8177. return
  8178. }
  8179. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8180. 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()
  8181. if err != nil {
  8182. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8183. return
  8184. }
  8185. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8186. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8187. upFpdetailList := make([]*upFpdetail, 0)
  8188. for _, newfpd := range newList {
  8189. for _, oldfpd := range oldFpdList {
  8190. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8191. var oldweight, newweight float64
  8192. if oldfpd["weight"] != nil {
  8193. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8194. }
  8195. if newfpd["weight"] != nil {
  8196. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8197. }
  8198. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8199. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8200. Old: oldweight,
  8201. New: newweight,
  8202. Times: newfpd["times"].(int64),
  8203. Ptid: newfpd["ptid"].(int64),
  8204. Fweight: fweight,
  8205. Id: oldfpd["id"].(int64),
  8206. })
  8207. break
  8208. }
  8209. }
  8210. }
  8211. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8212. }
  8213. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8214. }
  8215. func UdBarSync(c *gin.Context) {
  8216. appG := app.Gin{C: c}
  8217. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8218. fsions := gofasion.NewFasion(string(dataByte))
  8219. pastureid := fsions.Get("pastureId").ValueStr()
  8220. tx := restful.Engine.NewSession()
  8221. defer tx.Close()
  8222. pastureinfo := new(udPastureInfo)
  8223. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8224. if err != nil {
  8225. logs.Error(err)
  8226. return
  8227. }
  8228. gm.UdBarSync(pastureid, pastureinfo.Werks)
  8229. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8230. }
  8231. func UdFeedSync(c *gin.Context) {
  8232. appG := app.Gin{C: c}
  8233. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8234. fsions := gofasion.NewFasion(string(dataByte))
  8235. pastureid := fsions.Get("pastureId").ValueStr()
  8236. tx := restful.Engine.NewSession()
  8237. defer tx.Close()
  8238. pastureinfo := new(udPastureInfo)
  8239. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8240. if err != nil {
  8241. logs.Error(err)
  8242. return
  8243. }
  8244. gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8245. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8246. }
  8247. func UdFeedtempletPush(c *gin.Context) {
  8248. appG := app.Gin{C: c}
  8249. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8250. fsions := gofasion.NewFasion(string(dataByte))
  8251. pastureid := fsions.Get("pastureId").ValueStr()
  8252. date := fsions.Get("date").ValueStr()
  8253. tx := restful.Engine.NewSession()
  8254. defer tx.Close()
  8255. pastureinfo := new(udPastureInfo)
  8256. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8257. if err != nil {
  8258. logs.Error(err)
  8259. return
  8260. }
  8261. gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8262. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8263. }
  8264. func UdUtirPush(c *gin.Context) {
  8265. appG := app.Gin{C: c}
  8266. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8267. fsions := gofasion.NewFasion(string(dataByte))
  8268. pastureid := fsions.Get("pastureId").ValueStr()
  8269. date := fsions.Get("date").ValueStr()
  8270. tx := restful.Engine.NewSession()
  8271. defer tx.Close()
  8272. pastureinfo := new(udPastureInfo)
  8273. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8274. if err != nil {
  8275. logs.Error(err)
  8276. return
  8277. }
  8278. gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8279. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8280. }
  8281. func UdBarFeedRemainPush(c *gin.Context) {
  8282. appG := app.Gin{C: c}
  8283. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8284. fsions := gofasion.NewFasion(string(dataByte))
  8285. pastureid := fsions.Get("pastureId").ValueStr()
  8286. date := fsions.Get("date").ValueStr()
  8287. tx := restful.Engine.NewSession()
  8288. defer tx.Close()
  8289. pastureinfo := new(udPastureInfo)
  8290. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8291. if err != nil {
  8292. logs.Error(err)
  8293. return
  8294. }
  8295. gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8296. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8297. }
  8298. func UdMaterialIssuePush(c *gin.Context) {
  8299. appG := app.Gin{C: c}
  8300. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8301. fsions := gofasion.NewFasion(string(dataByte))
  8302. pastureid := fsions.Get("pastureId").ValueStr()
  8303. date := fsions.Get("date").ValueStr()
  8304. tx := restful.Engine.NewSession()
  8305. defer tx.Close()
  8306. pastureinfo := new(udPastureInfo)
  8307. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8308. if err != nil {
  8309. logs.Error(err)
  8310. return
  8311. }
  8312. gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8313. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8314. }
  8315. func DelFeedTemplet(c *gin.Context) {
  8316. appG := app.Gin{C: c}
  8317. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8318. fsions := gofasion.NewFasion(string(dataByte))
  8319. ftId := fsions.Get("ftId").ValueStr()
  8320. // userId := fsions.Get("userId").ValueStr()
  8321. tx := restful.Engine.NewSession()
  8322. defer tx.Close()
  8323. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8324. if err != nil {
  8325. logs.Error(err)
  8326. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8327. return
  8328. }
  8329. // barIdList, err := tx.SQL(`select barid from feedp where ftid = ? `, ftId).QueryString()
  8330. // if err != nil {
  8331. // logs.Error(err)
  8332. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8333. // return
  8334. // }
  8335. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8336. if err != nil {
  8337. logs.Error(err)
  8338. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8339. return
  8340. }
  8341. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8342. if err != nil {
  8343. logs.Error(err)
  8344. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8345. return
  8346. }
  8347. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8348. if count > 0 {
  8349. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8350. if err != nil {
  8351. logs.Error(err)
  8352. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8353. return
  8354. }
  8355. }
  8356. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8357. if err != nil {
  8358. logs.Error(err)
  8359. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8360. return
  8361. }
  8362. // var barIdStr []string
  8363. // for _, bar := range barIdList {
  8364. // barIdStr = append(barIdStr, bar["barid"])
  8365. // }
  8366. // if len(barIdStr) > 0 {
  8367. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8368. // if err != nil {
  8369. // logs.Error(err)
  8370. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8371. // return
  8372. // }
  8373. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8374. // if err != nil {
  8375. // logs.Error(err)
  8376. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8377. // return
  8378. // }
  8379. // now := time.Now()
  8380. // for _, newFpd := range newFpdDataList {
  8381. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8382. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8383. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8384. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8385. // if err != nil {
  8386. // logs.Error(err)
  8387. // appG.Response(http.StatusOK, e.ERROR, false)
  8388. // return
  8389. // }
  8390. // }
  8391. // for _, newFeedp := range newFeedpList {
  8392. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8393. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8394. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8395. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8396. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8397. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8398. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8399. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8400. // if err != nil {
  8401. // logs.Error(err)
  8402. // appG.Response(http.StatusOK, e.ERROR, false)
  8403. // return
  8404. // }
  8405. // }
  8406. // }
  8407. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8408. }
  8409. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8410. data := fasion["parammaps"].(map[string]interface{})
  8411. plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(0,1,2) ").Count()
  8412. fmt.Println(err)
  8413. plancount1, err := tx.SQL(`SELECT
  8414. count( 1 )
  8415. FROM
  8416. (
  8417. SELECT
  8418. d.id
  8419. FROM
  8420. downloadedplan d
  8421. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  8422. JOIN downloadplandtl1_exec d1e ON d1e.pid = d.id
  8423. JOIN downloadplandtl2 d2 ON d2.pid = d.id
  8424. WHERE
  8425. d.mydate = ?
  8426. AND d.havebutton = 0
  8427. AND lpplantype IN ( 0, 1, 2 )
  8428. AND ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id and dd2.fname = d2.fname) =
  8429. ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id and (select count(1) from downloadplandtl2 where pid = dd2.pid and fname = dd2.fname ) = 1 and dd2.fname = d2.fname )
  8430. GROUP BY
  8431. d.id
  8432. ) d
  8433. `,
  8434. data["startTime"]).Count()
  8435. fmt.Println(err)
  8436. if plancount != plancount1 && number < 10 {
  8437. number++
  8438. ExecDataParam(fasion, CommonParamMap, ParamMap, nil, nil, tx)
  8439. checkPlan(tx, fasion, CommonParamMap, ParamMap, number)
  8440. }
  8441. }
  8442. func EditPlanSort(c *gin.Context) {
  8443. appG := app.Gin{C: c}
  8444. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8445. fsions := gofasion.NewFasion(string(dataByte))
  8446. planIdStr := fsions.Get("planId").ValueStr()
  8447. mydate := fsions.Get("mydate").ValueStr()
  8448. sort := fsions.Get("sort").ValueStr()
  8449. tx := restful.Engine.NewSession()
  8450. defer tx.Close()
  8451. tx.Begin()
  8452. type downloadedplan struct {
  8453. Id int64 `xorm:"id"`
  8454. Sort int `xorm:"sort"`
  8455. Pid int64 `xorm:"pid"`
  8456. }
  8457. planInfo := new(downloadedplan)
  8458. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  8459. if err != nil {
  8460. logs.Error(err)
  8461. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8462. tx.Rollback()
  8463. return
  8464. }
  8465. sort1, _ := strconv.Atoi(sort)
  8466. if sort1 == planInfo.Sort {
  8467. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  8468. tx.Rollback()
  8469. return
  8470. }
  8471. count1, err := tx.SQL(` select count(1) from downloadedplan where pid = (select pid from downloadedplan where sort = ? and mydate = ? ) and mydate = ? `, sort, mydate, mydate).Count()
  8472. if err != nil {
  8473. logs.Error(err)
  8474. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8475. tx.Rollback()
  8476. return
  8477. }
  8478. if count1 == 0 {
  8479. tx.Rollback()
  8480. logs.Error(err)
  8481. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  8482. return
  8483. }
  8484. count, err := tx.SQL(` select count(1) from downloadedplan where pid = (select pid from downloadedplan where sort = ? and mydate = ? ) and havebutton = 1 and mydate = ? `, sort, mydate, mydate).Count()
  8485. if err != nil {
  8486. logs.Error(err)
  8487. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8488. tx.Rollback()
  8489. return
  8490. }
  8491. if count > 0 {
  8492. tx.Rollback()
  8493. logs.Error(err)
  8494. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  8495. return
  8496. }
  8497. if planInfo.Sort > sort1 {
  8498. minSortList, err := tx.SQL(`select min(d.sort) sort from downloadedplan d where d.mydate = ? and d.pid = (select pid from downloadedplan where sort = ? and mydate = ? ) `, mydate, sort, mydate).QueryString()
  8499. if err != nil {
  8500. logs.Error(err)
  8501. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8502. tx.Rollback()
  8503. return
  8504. }
  8505. var minSort, pidCount int
  8506. for _, sort := range minSortList {
  8507. minSort, _ = strconv.Atoi(sort["sort"])
  8508. }
  8509. planList := make([]*downloadedplan, 0)
  8510. err = tx.SQL(`select id,d.sort sort,d.pid from downloadedplan d where d.mydate = ? and sort >= ? order by sort`, mydate, minSort).Find(&planList)
  8511. if err != nil {
  8512. logs.Error(err)
  8513. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8514. tx.Rollback()
  8515. return
  8516. }
  8517. planPid := planInfo.Pid
  8518. planList1 := make([]*downloadedplan, 0)
  8519. planList2 := make([]*downloadedplan, 0)
  8520. for _, plan := range planList {
  8521. if plan.Pid == planPid {
  8522. pidCount++
  8523. planList1 = append(planList1, plan)
  8524. } else {
  8525. planList2 = append(planList2, plan)
  8526. }
  8527. }
  8528. planList1 = append(planList1, planList2...)
  8529. for i, plan := range planList1 {
  8530. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  8531. if err != nil {
  8532. logs.Error(err)
  8533. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8534. tx.Rollback()
  8535. return
  8536. }
  8537. }
  8538. } else {
  8539. maxSortList, err := tx.SQL(`select max(d.sort) sort from downloadedplan d where d.mydate = ? and d.pid = (select pid from downloadedplan where sort = ? and mydate = ? ) `, mydate, sort, mydate).QueryString()
  8540. if err != nil {
  8541. logs.Error(err)
  8542. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8543. tx.Rollback()
  8544. return
  8545. }
  8546. var maxSort int
  8547. for _, sort := range maxSortList {
  8548. maxSort, _ = strconv.Atoi(sort["sort"])
  8549. }
  8550. planList := make([]*downloadedplan, 0)
  8551. err = tx.SQL(`select id,d.sort sort,d.pid from downloadedplan d where d.mydate = ? and sort <= ? order by sort`, mydate, maxSort).Find(&planList)
  8552. if err != nil {
  8553. logs.Error(err)
  8554. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8555. tx.Rollback()
  8556. return
  8557. }
  8558. planPid := planInfo.Pid
  8559. planList1 := make([]*downloadedplan, 0)
  8560. planList2 := make([]*downloadedplan, 0)
  8561. for _, plan := range planList {
  8562. if plan.Pid == planPid {
  8563. // pidCount++
  8564. planList1 = append(planList1, plan)
  8565. } else {
  8566. planList2 = append(planList2, plan)
  8567. }
  8568. }
  8569. planList2 = append(planList2, planList1...)
  8570. for i, plan := range planList2 {
  8571. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  8572. if err != nil {
  8573. logs.Error(err)
  8574. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8575. tx.Rollback()
  8576. return
  8577. }
  8578. }
  8579. }
  8580. err = tx.Commit()
  8581. if err != nil {
  8582. logs.Error(err)
  8583. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8584. tx.Rollback()
  8585. return
  8586. }
  8587. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8588. }
  8589. func EditDownloadedplanArtificial(c *gin.Context) {
  8590. appG := app.Gin{C: c}
  8591. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8592. fsions := gofasion.NewFasion(string(dataByte))
  8593. planIdStr := fsions.Get("planId").ValueStr()
  8594. tx := restful.Engine.NewSession()
  8595. defer tx.Close()
  8596. tx.Begin()
  8597. planIdList := strings.Split(planIdStr, ",")
  8598. for _, planId := range planIdList {
  8599. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? and havebutton != 1`, planId)
  8600. if err != nil {
  8601. logs.Error(err)
  8602. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8603. tx.Rollback()
  8604. return
  8605. }
  8606. }
  8607. err := tx.Commit()
  8608. if err != nil {
  8609. logs.Error(err)
  8610. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8611. tx.Rollback()
  8612. return
  8613. }
  8614. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8615. }
  8616. type PlanRFID struct {
  8617. RFID string `json:"RFID"`
  8618. Lweight string `json:"lweight"`
  8619. Gear string `json:"gear"`
  8620. Speed string `json:"speed"`
  8621. }
  8622. func GetPlanRFID(c *gin.Context) {
  8623. appG := app.Gin{C: c}
  8624. RFIDStr := c.Query("RFID")
  8625. planRFIDList := make([]*PlanRFID, 0)
  8626. planRFIDList = append(planRFIDList, &PlanRFID{
  8627. RFID: RFIDStr,
  8628. Lweight: "1411.1",
  8629. Gear: "1",
  8630. Speed: "10",
  8631. })
  8632. planRFIDList = append(planRFIDList, &PlanRFID{
  8633. RFID: RFIDStr,
  8634. Lweight: "1322.1",
  8635. Gear: "1",
  8636. Speed: "10",
  8637. })
  8638. planRFIDList = append(planRFIDList, &PlanRFID{
  8639. RFID: RFIDStr,
  8640. Lweight: "1904.1",
  8641. Gear: "1",
  8642. Speed: "10",
  8643. })
  8644. planRFIDList = append(planRFIDList, &PlanRFID{
  8645. RFID: RFIDStr,
  8646. Lweight: "1870.1",
  8647. Gear: "1",
  8648. Speed: "10",
  8649. })
  8650. planRFIDList = append(planRFIDList, &PlanRFID{
  8651. RFID: RFIDStr,
  8652. Lweight: "2041.1",
  8653. Gear: "1",
  8654. Speed: "10",
  8655. })
  8656. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  8657. }
  8658. type tmrEquipmentMuster struct {
  8659. A string
  8660. N string
  8661. }
  8662. func GetTmrEquipmentMuster(c *gin.Context) {
  8663. appG := app.Gin{C: c}
  8664. id := c.Query("id")
  8665. tx := restful.Engine.NewSession()
  8666. defer tx.Close()
  8667. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  8668. if err != nil {
  8669. logs.Error(err)
  8670. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8671. return
  8672. }
  8673. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  8674. for _, data := range dataList {
  8675. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  8676. for _, g := range tmrEquipmentMusterList {
  8677. a, _ := strconv.ParseFloat(g.A, 64)
  8678. n, _ := strconv.ParseFloat(g.N, 64)
  8679. a1, n1 := ddmmtoddd(a, n)
  8680. g.A = fmt.Sprintf("%f", n1)
  8681. g.N = fmt.Sprintf("%f", a1)
  8682. }
  8683. }
  8684. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  8685. }
  8686. func ddmmtoddd(lng, lat float64) (float64, float64) {
  8687. lngDegree := fmt.Sprintf("%f", lng/100)
  8688. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  8689. lngDegreeInt := int(lngDegreefloat * 1000000)
  8690. dd := lngDegreeInt / 100 * 100 / 60
  8691. fmt.Println(dd)
  8692. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  8693. latDegree := fmt.Sprintf("%f", lat/100)
  8694. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  8695. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  8696. latDegreeInt := int(latDegreefloat * 1000000)
  8697. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  8698. a, _ := strconv.ParseFloat(lngStr, 64)
  8699. b, _ := strconv.ParseFloat(latStr, 64)
  8700. return coordtransform.WGS84toGCJ02(b, a)
  8701. }
  8702. func EditDownloadedplanExecWeight(c *gin.Context) {
  8703. appG := app.Gin{C: c}
  8704. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8705. fsions := gofasion.NewFasion(string(dataByte))
  8706. pid := fsions.Get("pid").ValueStr()
  8707. sort := fsions.Get("sort").ValueStr()
  8708. weight := fsions.Get("weight").ValueStr()
  8709. tx := restful.Engine.NewSession()
  8710. defer tx.Close()
  8711. tx.Begin()
  8712. _, err := tx.Exec(` update downloadplandtl1_exec set actualweight = ? where pid = ? and sort = ? `, weight, pid, sort)
  8713. if err != nil {
  8714. logs.Error(err)
  8715. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8716. tx.Rollback()
  8717. return
  8718. }
  8719. _, err = tx.Exec(` update downloadplandtl1 set actualweight = lweight / (select sum(lweight) from downloadplandtl1 where pid = ? and sort = ? ) * ? where pid = ? and sort = ? `, pid, sort, weight, pid, sort)
  8720. if err != nil {
  8721. logs.Error(err)
  8722. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8723. tx.Rollback()
  8724. return
  8725. }
  8726. err = tx.Commit()
  8727. if err != nil {
  8728. logs.Error(err)
  8729. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8730. tx.Rollback()
  8731. return
  8732. }
  8733. appG.Response(http.StatusOK, e.SUCCESS, true)
  8734. }
  8735. func EditDownloadplandtl2Weight(c *gin.Context) {
  8736. appG := app.Gin{C: c}
  8737. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8738. fsions := gofasion.NewFasion(string(dataByte))
  8739. pid := fsions.Get("pid").ValueStr()
  8740. sort := fsions.Get("sort").ValueStr()
  8741. weight := fsions.Get("weight").ValueStr()
  8742. tx := restful.Engine.NewSession()
  8743. defer tx.Close()
  8744. tx.Begin()
  8745. _, err := tx.Exec(` update downloadplandtl2 set actualweight = ? where pid = ? and sort = ? `, weight, pid, sort)
  8746. if err != nil {
  8747. logs.Error(err)
  8748. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8749. tx.Rollback()
  8750. return
  8751. }
  8752. err = tx.Commit()
  8753. if err != nil {
  8754. logs.Error(err)
  8755. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8756. tx.Rollback()
  8757. return
  8758. }
  8759. appG.Response(http.StatusOK, e.SUCCESS, true)
  8760. }
  8761. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  8762. params := fasion.Get("parammaps")
  8763. surplus := params.Get("surplus").ValueStr()
  8764. surplusId := params.Get("surplusId").ValueStr()
  8765. tx := restful.Engine.NewSession()
  8766. defer tx.Close()
  8767. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  8768. if surplusId != "0" {
  8769. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  8770. if err != nil {
  8771. log.Println("PostDataByName-error-1: ", err)
  8772. return errors.New("配方修改失败!")
  8773. }
  8774. type ftdetail struct {
  8775. Id string
  8776. Fname string
  8777. Sort int64
  8778. }
  8779. ftList := make([]*ftdetail, 0)
  8780. for _, data := range dataList {
  8781. ft := new(ftdetail)
  8782. ft.Fname = data["fname"]
  8783. ft.Id = data["id"]
  8784. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  8785. if err != nil {
  8786. log.Println("PostDataByName-error-2: ", err)
  8787. return err
  8788. }
  8789. ft.Sort = sort
  8790. ftList = append(ftList, ft)
  8791. }
  8792. if surplus == "日粮" {
  8793. for _, ft := range ftList {
  8794. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  8795. }
  8796. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  8797. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  8798. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  8799. fmt.Println(err)
  8800. } else {
  8801. var sort int64
  8802. for _, ft := range ftList {
  8803. if ft.Fname == surplus {
  8804. sort = ft.Sort
  8805. break
  8806. }
  8807. }
  8808. if sort == 0 {
  8809. for _, ft := range ftList {
  8810. ft.Sort = ft.Sort + 1
  8811. }
  8812. } else {
  8813. for _, ft := range ftList {
  8814. if ft.Sort >= sort {
  8815. ft.Sort = ft.Sort + 1
  8816. }
  8817. }
  8818. }
  8819. for _, ft := range ftList {
  8820. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  8821. }
  8822. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  8823. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  8824. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  8825. if err != nil {
  8826. log.Println("PostDataByName-error-1: ", err)
  8827. fmt.Println(err)
  8828. return errors.New("配方修改失败!")
  8829. }
  8830. }
  8831. }
  8832. return nil
  8833. }
  8834. func FeedSurplus(fasion *gofasion.Fasion) {
  8835. tx := restful.Engine.NewSession()
  8836. defer tx.Close()
  8837. params := fasion.Get("parammaps")
  8838. feedId := params.Get("id").ValueStr()
  8839. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  8840. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  8841. }
  8842. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  8843. // params := fasion.Get("parammaps")
  8844. // surplus := params.Get("surplus").ValueStr()
  8845. // surplusId := params.Get("surplusId").ValueStr()
  8846. tx := restful.Engine.NewSession()
  8847. defer tx.Close()
  8848. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  8849. if surplusId != "0" {
  8850. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  8851. if err != nil {
  8852. log.Println("PostDataByName-error-1: ", err)
  8853. return errors.New("配方修改失败!")
  8854. }
  8855. type ftdetail struct {
  8856. Id string
  8857. Fname string
  8858. Sort int64
  8859. }
  8860. ftList := make([]*ftdetail, 0)
  8861. for _, data := range dataList {
  8862. ft := new(ftdetail)
  8863. ft.Fname = data["fname"]
  8864. ft.Id = data["id"]
  8865. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  8866. if err != nil {
  8867. log.Println("PostDataByName-error-2: ", err)
  8868. return err
  8869. }
  8870. ft.Sort = sort
  8871. ftList = append(ftList, ft)
  8872. }
  8873. if surplus == "日粮" {
  8874. for _, ft := range ftList {
  8875. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  8876. }
  8877. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  8878. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  8879. pastureId, id, surplusId, surplusId, surplusId)
  8880. fmt.Println(err)
  8881. } else {
  8882. var sort int64
  8883. for _, ft := range ftList {
  8884. if ft.Fname == surplus {
  8885. sort = ft.Sort
  8886. break
  8887. }
  8888. }
  8889. if sort == 0 {
  8890. for _, ft := range ftList {
  8891. ft.Sort = ft.Sort + 1
  8892. }
  8893. } else {
  8894. for _, ft := range ftList {
  8895. if ft.Sort >= sort {
  8896. ft.Sort = ft.Sort + 1
  8897. }
  8898. }
  8899. }
  8900. for _, ft := range ftList {
  8901. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  8902. }
  8903. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  8904. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  8905. id, surplusId, surplusId, sort, surplusId, pastureId)
  8906. if err != nil {
  8907. log.Println("PostDataByName-error-1: ", err)
  8908. fmt.Println(err)
  8909. return errors.New("配方修改失败!")
  8910. }
  8911. }
  8912. }
  8913. return nil
  8914. }
  8915. func GetLanguageStatus() string {
  8916. tx := restful.Engine.NewSession()
  8917. defer tx.Close()
  8918. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  8919. if err != nil {
  8920. log.Println(err)
  8921. return "0"
  8922. }
  8923. return dataList[0]["inforvalue"]
  8924. }
  8925. func EditLanguage(c *gin.Context) {
  8926. appG := app.Gin{C: c}
  8927. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8928. fsions := gofasion.NewFasion(string(dataByte))
  8929. language := fsions.Get("language").ValueStr()
  8930. tx := restful.Engine.NewSession()
  8931. defer tx.Close()
  8932. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  8933. if err != nil {
  8934. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8935. return
  8936. }
  8937. if language == "0" {
  8938. _, err := tx.Exec(`delete from dictlist `)
  8939. if err != nil {
  8940. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8941. return
  8942. }
  8943. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  8944. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  8945. if err != nil {
  8946. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8947. return
  8948. }
  8949. } else {
  8950. _, err := tx.Exec(`delete from dictlist `)
  8951. if err != nil {
  8952. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8953. return
  8954. }
  8955. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  8956. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  8957. if err != nil {
  8958. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8959. return
  8960. }
  8961. }
  8962. appG.Response(http.StatusOK, e.SUCCESS, true)
  8963. }