ops.go 332 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811
  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. count, err := tx.SQL(` select count(1) from lpplandtl1 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 = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3291. if count == 1 {
  3292. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3293. and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3294. if err != nil {
  3295. tx.Rollback()
  3296. logs.Error(err)
  3297. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3298. return
  3299. }
  3300. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3301. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3302. if err != nil {
  3303. tx.Rollback()
  3304. logs.Error(err)
  3305. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3306. return
  3307. }
  3308. }
  3309. fpdDataList, err := tx.SQL(`
  3310. 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 ,
  3311. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3312. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3313. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3314. if err != nil {
  3315. tx.Rollback()
  3316. logs.Error(err)
  3317. }
  3318. for _, fpd := range fpdDataList {
  3319. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3320. fttype := -1
  3321. if fpd["fttype"].(string) == "1" {
  3322. fttype = 1
  3323. }
  3324. var fweight float64
  3325. var lweight float64
  3326. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3327. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  3328. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3329. join tmr t on t.id = lpp.tmrid
  3330. where lppland.fpdid =?
  3331. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3332. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3333. if err != nil {
  3334. tx.Rollback()
  3335. logs.Error(err)
  3336. }
  3337. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3338. var w float64
  3339. var status int
  3340. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3341. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3342. if weight >= 0 {
  3343. continue
  3344. }
  3345. w = weight
  3346. status = 0
  3347. } else {
  3348. // continue
  3349. if weight <= 0 {
  3350. continue
  3351. }
  3352. w = weight
  3353. status = 1
  3354. }
  3355. // for _, lppland := range lpplandtl1List {
  3356. // lweight += lppland.Lweight
  3357. // }
  3358. for _, lppland := range lpplandtl1List {
  3359. lpplandInfo := new(lpplandtlInfo)
  3360. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3361. lweight = lpplandInfo.Lweight
  3362. if status == 1 {
  3363. // if w <= lppland.Lweight {
  3364. if lppland.Maxweight <= lweight {
  3365. continue
  3366. }
  3367. if w+lweight <= lppland.Maxweight {
  3368. lppland.Lweight += w
  3369. lweight += w
  3370. fweight += w
  3371. w = 0
  3372. } else {
  3373. w = w - (lppland.Maxweight - lweight)
  3374. n := (lppland.Maxweight - lweight)
  3375. lppland.Lweight = lppland.Lweight + n
  3376. lweight += n
  3377. fweight += n
  3378. }
  3379. } else {
  3380. if lppland.Lweight == 0 {
  3381. continue
  3382. }
  3383. if w+lppland.Lweight >= 0 {
  3384. lppland.Lweight = lppland.Lweight + w
  3385. lweight = lweight + w
  3386. fweight = fweight + w
  3387. w = 0
  3388. } else {
  3389. w = w + lppland.Lweight
  3390. lweight = lweight - lppland.Lweight
  3391. fweight = fweight - lppland.Lweight
  3392. lppland.Lweight = 0
  3393. }
  3394. }
  3395. if lppland.Lweight > 0 {
  3396. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3397. if err != nil {
  3398. tx.Rollback()
  3399. logs.Error(err)
  3400. return
  3401. }
  3402. } else {
  3403. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3404. if err != nil {
  3405. tx.Rollback()
  3406. logs.Error(err)
  3407. return
  3408. }
  3409. }
  3410. if w == 0 {
  3411. break
  3412. }
  3413. // break
  3414. }
  3415. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3416. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3417. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3418. if err != nil {
  3419. tx.Rollback()
  3420. logs.Error(err)
  3421. }
  3422. if w == 0 {
  3423. break
  3424. }
  3425. }
  3426. }
  3427. }
  3428. tx.Commit()
  3429. now := time.Now()
  3430. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3431. if err != nil {
  3432. logs.Error(err)
  3433. appG.Response(http.StatusOK, e.ERROR, false)
  3434. return
  3435. }
  3436. for _, newLpplandtl1 := range newLpplandtl1List {
  3437. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3438. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3439. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3440. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3441. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3442. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3443. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3444. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3445. if err != nil {
  3446. logs.Error(err)
  3447. appG.Response(http.StatusOK, e.ERROR, false)
  3448. return
  3449. }
  3450. }
  3451. appG.Response(http.StatusOK, e.SUCCESS, true)
  3452. }
  3453. func GetProcessAnalysis(c *gin.Context) {
  3454. appG := app.Gin{C: c}
  3455. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3456. fsion := gofasion.NewFasion(string(dataByte))
  3457. sqlnamestr := fsion.Get("name").ValueStr()
  3458. offset := fsion.Get("offset").ValueDefaultInt(0)
  3459. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3460. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3461. parammaps := fsion.Get("parammaps")
  3462. tx := restful.Engine.NewSession()
  3463. err := tx.Begin()
  3464. defer func() {
  3465. switch {
  3466. case err != nil:
  3467. logging.Error("tx.Begin 事务启动失败__error:", err)
  3468. if tx != nil {
  3469. tx.Rollback()
  3470. }
  3471. default:
  3472. if tx != nil {
  3473. err = tx.Commit()
  3474. }
  3475. }
  3476. if tx != nil {
  3477. tx.Close()
  3478. }
  3479. }()
  3480. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3481. s_params := make([]interface{}, 0)
  3482. paramslist := strings.Split(p, ",")
  3483. if len(paramslist) > 0 && p != "" {
  3484. for _, value := range paramslist {
  3485. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3486. if tempv, exists := c.Get("jwt_username"); exists {
  3487. s_params = append(s_params, tempv.(string))
  3488. } else {
  3489. s_params = append(s_params, "")
  3490. }
  3491. } else {
  3492. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3493. }
  3494. }
  3495. }
  3496. tmrtnameStr := ""
  3497. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3498. if len(tmrtnameStr) == 0 {
  3499. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3500. } else {
  3501. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3502. }
  3503. }
  3504. if len(tmrtnameStr) > 0 {
  3505. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3506. }
  3507. sql += " ORDER BY d.intime"
  3508. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3509. if err != nil {
  3510. logging.Error("GetDataByName err: ", err)
  3511. msg := geterrmsg(err.Error())
  3512. appG.Response(http.StatusOK, e.ERROR, msg)
  3513. } else {
  3514. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3515. }
  3516. }
  3517. func UpdateFeedtempletStatus(c *gin.Context) {
  3518. appG := app.Gin{C: c}
  3519. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3520. fsion := gofasion.NewFasion(string(dataByte))
  3521. parammaps := fsion.Get("parammaps")
  3522. tx := restful.Engine.NewSession()
  3523. tx.Begin()
  3524. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3525. if err != nil {
  3526. tx.Rollback()
  3527. logs.Error(err)
  3528. appG.Response(http.StatusOK, e.ERROR, err)
  3529. return
  3530. }
  3531. tx.Commit()
  3532. appG.Response(http.StatusOK, e.SUCCESS, true)
  3533. }
  3534. func AddFtdry(c *gin.Context) {
  3535. appG := app.Gin{C: c}
  3536. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3537. fsion := gofasion.NewFasion(string(dataByte))
  3538. sqlnamestr := fsion.Get("name").ValueStr()
  3539. s_params := make([]interface{}, 0)
  3540. tx := restful.Engine.NewSession()
  3541. err := tx.Begin()
  3542. defer func() {
  3543. switch {
  3544. case err != nil:
  3545. if tx != nil {
  3546. tx.Rollback()
  3547. }
  3548. default:
  3549. if tx != nil {
  3550. err = tx.Commit()
  3551. }
  3552. }
  3553. if tx != nil {
  3554. tx.Close()
  3555. }
  3556. }()
  3557. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3558. if sql != "" {
  3559. parammaps := fsion.Get("parammaps")
  3560. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3561. paramslist := strings.Split(p, ",")
  3562. if len(paramslist) > 0 && p != "" {
  3563. for _, value := range paramslist {
  3564. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3565. if tempv, exists := c.Get("jwt_username"); exists {
  3566. s_params = append(s_params, tempv.(string))
  3567. } else {
  3568. s_params = append(s_params, "")
  3569. }
  3570. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3571. ids, err := setting.SnowIds.NextId()
  3572. if err != nil {
  3573. ids = time.Now().UnixNano()
  3574. logging.Info("create SnowIds err", err)
  3575. }
  3576. s_params = append(s_params, ids)
  3577. } else {
  3578. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3579. }
  3580. }
  3581. }
  3582. var actweight float64
  3583. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3584. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3585. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3586. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3587. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3588. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3589. 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()
  3590. if err != nil {
  3591. logging.Error("AddFtdry err: ", err)
  3592. msg := geterrmsg(err.Error())
  3593. appG.Response(http.StatusOK, e.ERROR, msg)
  3594. }
  3595. if len(actweightList) > 0 {
  3596. for _, item := range actweightList {
  3597. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3598. if err != nil {
  3599. logging.Error("AddFtdry err: ", err)
  3600. msg := geterrmsg(err.Error())
  3601. appG.Response(http.StatusOK, e.ERROR, msg)
  3602. }
  3603. actweight = fl
  3604. }
  3605. } else {
  3606. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3607. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3608. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3609. if err != nil {
  3610. logging.Error("AddFtdry err: ", err)
  3611. msg := geterrmsg(err.Error())
  3612. appG.Response(http.StatusOK, e.ERROR, msg)
  3613. }
  3614. for _, item := range dryList {
  3615. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3616. if err != nil {
  3617. logging.Error("AddFtdry err: ", err)
  3618. msg := geterrmsg(err.Error())
  3619. appG.Response(http.StatusOK, e.ERROR, msg)
  3620. }
  3621. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3622. }
  3623. }
  3624. if sqlnamestr == "insertFtdry" {
  3625. s_params = append(s_params, actweight)
  3626. } else if sqlnamestr == "updateFtdry" {
  3627. sql = fmt.Sprintf(sql, actweight)
  3628. }
  3629. queryData, err := execDataBySqlT(sql, s_params, tx)
  3630. if err != nil {
  3631. logging.Error("AddFtdry err: ", err)
  3632. msg := geterrmsg(err.Error())
  3633. appG.Response(http.StatusOK, e.ERROR, msg)
  3634. } else {
  3635. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3636. }
  3637. } else {
  3638. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3639. }
  3640. }
  3641. func CheckDates(c *gin.Context) {
  3642. tx := restful.Engine.NewSession()
  3643. defer tx.Close()
  3644. appG := app.Gin{C: c}
  3645. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3646. tempval_ := make(map[string]interface{})
  3647. tempCommon := make(map[string]interface{})
  3648. tempval := make([]map[string]interface{}, 0)
  3649. err := json.Unmarshal(dataByte, &tempval_)
  3650. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3651. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3652. if err != nil {
  3653. } else {
  3654. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3655. tempCommon = v
  3656. }
  3657. if v, ok := tempval_["data"].([]interface{}); ok {
  3658. for _, Tvalue := range v {
  3659. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3660. tempval = append(tempval, v1)
  3661. }
  3662. }
  3663. }
  3664. if err == nil {
  3665. if tempv, exists := c.Get("jwt_username"); exists {
  3666. tempCommon["jwt_username"] = tempv.(string)
  3667. }
  3668. for _, paramvalue := range tempval {
  3669. if _, ok := paramvalue["resultname"]; !ok {
  3670. paramvalue["resultname"] = paramvalue["name"]
  3671. }
  3672. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3673. if err != nil {
  3674. logging.Error("ExecDataParam error:", err)
  3675. }
  3676. }
  3677. if err == nil {
  3678. vmsg := ""
  3679. for _, item := range tempval {
  3680. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3681. for _, childrenList := range list.([]interface{}) {
  3682. for k, children := range childrenList.(map[string]interface{}) {
  3683. if k != "children" {
  3684. continue
  3685. }
  3686. for _, v := range children.([]map[string]interface{}) {
  3687. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3688. if k1 == "list" {
  3689. for _, v2 := range v1.([]map[string]interface{}) {
  3690. if v2["vmsg"].(string) != "1" {
  3691. if len(vmsg) == 0 {
  3692. vmsg = v2["vmsg"].(string)
  3693. } else {
  3694. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3695. }
  3696. }
  3697. }
  3698. }
  3699. }
  3700. }
  3701. }
  3702. }
  3703. }
  3704. }
  3705. if len(vmsg) > 0 {
  3706. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3707. } else {
  3708. appG.Response(http.StatusOK, e.SUCCESS, true)
  3709. }
  3710. } else {
  3711. msg := geterrmsg(err.Error())
  3712. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3713. }
  3714. }
  3715. }
  3716. if err != nil {
  3717. msg := geterrmsg(err.Error())
  3718. appG.Response(http.StatusOK, e.ERROR, msg)
  3719. }
  3720. }
  3721. 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) {
  3722. sqlname := fasion["name"].(string)
  3723. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3724. if v, ok := fasion["type"]; ok {
  3725. sqltype = v.(string)
  3726. }
  3727. sql := ""
  3728. p := ""
  3729. s_params := make([]interface{}, 0)
  3730. if sqltype != "" {
  3731. sql, p = restful.GetSqlByName(sqlname, tx)
  3732. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3733. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3734. paramslist := strings.Split(p, ",")
  3735. if len(paramslist) > 0 && p != "" {
  3736. for _, value := range paramslist {
  3737. ss := ""
  3738. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3739. ids, err := setting.SnowIds.NextId()
  3740. if err != nil {
  3741. ids = time.Now().UnixNano()
  3742. logging.Info("create SnowIds err", err)
  3743. }
  3744. s_params = append(s_params, ids)
  3745. } else {
  3746. if ss == "" && CommonParamMap != nil {
  3747. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3748. ss = valuestring
  3749. tempstrb := strings.IndexAny(valuestring, "@")
  3750. tempstre := strings.IndexAny(valuestring, ".")
  3751. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3752. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3753. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3754. }
  3755. } else {
  3756. ss = ""
  3757. }
  3758. }
  3759. }
  3760. if ss == "" && ParentParamMap != nil {
  3761. ss = getParamValue_(v, value, ParentParamMap)
  3762. }
  3763. if ss == "" && sameParamMap != nil {
  3764. ss = getParamValue(v, value, sameParamMap)
  3765. }
  3766. if ss == "" && ParamMap != nil {
  3767. ss = getParamValue(v, value, ParamMap)
  3768. }
  3769. s_params = append(s_params, ss)
  3770. }
  3771. }
  3772. }
  3773. }
  3774. }
  3775. if sql == "" {
  3776. sqltype = ""
  3777. }
  3778. if sql != "" {
  3779. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3780. if err != nil {
  3781. return nil, err
  3782. }
  3783. // fmt.Println(tempValParam)
  3784. return tempValParam.(map[string]interface{}), nil
  3785. } else {
  3786. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3787. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3788. if err != nil {
  3789. return nil, err
  3790. }
  3791. return nil, err
  3792. }
  3793. }
  3794. return nil, nil
  3795. }
  3796. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3797. var err error
  3798. subarray, ok := fasion["children"]
  3799. if ok {
  3800. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3801. tempVal_arrary := make([]map[string]interface{}, 0)
  3802. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3803. tempVal_ := make(map[string]interface{})
  3804. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3805. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3806. } else {
  3807. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3808. }
  3809. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3810. if err != nil {
  3811. return err
  3812. }
  3813. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3814. }
  3815. v.(map[string]interface{})["children"] = tempVal_arrary
  3816. }
  3817. }
  3818. return nil
  3819. }
  3820. func FpdImportExcel(c *gin.Context) {
  3821. appG := app.Gin{C: c}
  3822. inputdata := ""
  3823. c.Request.ParseForm()
  3824. params := c.Request.Form
  3825. file, _, err := c.Request.FormFile("file")
  3826. if err != nil {
  3827. appG.Response(http.StatusOK, e.ERROR, err)
  3828. return
  3829. }
  3830. sqlnamestrs := params.Get("name")
  3831. sheetname := params.Get("sheetname")
  3832. pastureid := params.Get("pastureid")
  3833. // importParams := params.Get("importParams")
  3834. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3835. // 必输项参数 (字符串格式 "field1,field2,field3")
  3836. requiredParams := params.Get("requiredParams")
  3837. // 日期参数
  3838. dateParams := params.Get("dateParams")
  3839. // 数字参数
  3840. numParams := params.Get("numParams")
  3841. //将字符串分割开
  3842. dateParamslist := strings.Split(dateParams, ",")
  3843. requiredParamslist := strings.Split(requiredParams, ",")
  3844. numParamslist := strings.Split(numParams, ",")
  3845. queryData := make([]interface{}, 0)
  3846. sqlslist := strings.Split(sqlnamestrs, ",")
  3847. xlsx1, err := excelize.OpenReader(file)
  3848. if err != nil {
  3849. fmt.Println(err)
  3850. return
  3851. }
  3852. ok := 0
  3853. error := 0
  3854. isdone := true
  3855. tx := restful.Engine.NewSession()
  3856. defer tx.Close()
  3857. languageStatus := GetLanguageStatus()
  3858. if languageStatus == "0" {
  3859. 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
  3860. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3861. if err != nil {
  3862. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3863. return
  3864. }
  3865. rows := xlsx1.GetRows(sheetname)
  3866. // 限制10000条,多余的截取掉
  3867. if len(rows) > 10000 {
  3868. rows = rows[:10000]
  3869. }
  3870. dataList := make(map[string][]*upFpdetail, 0)
  3871. for i, row := range rows {
  3872. if i > 0 {
  3873. entry := make(map[string]interface{})
  3874. outentry := make(map[string]interface{})
  3875. for j, colCell := range rows[0] {
  3876. for k, colCell1 := range row {
  3877. if j == k {
  3878. outentry[colCell] = colCell1
  3879. entry[colCell] = colCell1
  3880. }
  3881. }
  3882. }
  3883. inputdata = ""
  3884. a := ""
  3885. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3886. //校验日期格式
  3887. for _, v := range dateParamslist {
  3888. if v == "" {
  3889. continue
  3890. }
  3891. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3892. dtime, err := TransfTime(d.(string))
  3893. if err != nil {
  3894. a = strings.Trim(v, " ")
  3895. break
  3896. }
  3897. outentry[strings.Trim(v, " ")] = dtime
  3898. }
  3899. }
  3900. if a != "" {
  3901. outentry["error_msg"] = a + " 格式错误"
  3902. error++
  3903. queryData = append(queryData, outentry)
  3904. continue
  3905. }
  3906. a = ""
  3907. //校验必填格式
  3908. for _, v := range requiredParamslist {
  3909. if v == "" {
  3910. continue
  3911. }
  3912. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3913. a = strings.Trim(v, " ")
  3914. break
  3915. }
  3916. }
  3917. if a != "" {
  3918. outentry["error_msg"] = a + " 未填或格式错误"
  3919. error++
  3920. queryData = append(queryData, outentry)
  3921. continue
  3922. }
  3923. a = ""
  3924. //校验数字格式
  3925. for _, v := range numParamslist {
  3926. if v == "" {
  3927. continue
  3928. }
  3929. d, ok := outentry[strings.Trim(v, " ")]
  3930. if !ok || d == "" {
  3931. outentry[strings.Trim(v, " ")] = 0
  3932. } else {
  3933. var fl float64
  3934. switch d.(type) {
  3935. case string:
  3936. fl, err = strconv.ParseFloat(d.(string), 64)
  3937. }
  3938. if err != nil || fl < 0 {
  3939. a = strings.Trim(v, " ")
  3940. break
  3941. }
  3942. }
  3943. }
  3944. if a != "" {
  3945. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3946. error++
  3947. queryData = append(queryData, outentry)
  3948. continue
  3949. }
  3950. errExist := false
  3951. for _, sqlnamestr := range sqlslist {
  3952. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3953. paramslist := strings.Split(paramslists, ",")
  3954. if len(paramslist) > 0 {
  3955. s_params := make([]interface{}, 0)
  3956. for _, value := range paramslist {
  3957. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3958. if tempv, exists := c.Get("jwt_username"); exists {
  3959. s_params = append(s_params, tempv.(string))
  3960. } else {
  3961. s_params = append(s_params, "")
  3962. }
  3963. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3964. s_params = append(s_params, pastureid)
  3965. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3966. ids, err := setting.SnowIds.NextId()
  3967. if err != nil {
  3968. ids = time.Now().UnixNano()
  3969. logging.Info("create SnowIds err", err)
  3970. }
  3971. s_params = append(s_params, ids)
  3972. } else {
  3973. if outentry[strings.Trim(value, " ")] == nil {
  3974. s_params = append(s_params, "")
  3975. } else {
  3976. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3977. }
  3978. }
  3979. }
  3980. outentry["input"] = inputdata
  3981. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3982. if err != nil {
  3983. errExist = true
  3984. // if tx != nil {
  3985. // tx.Rollback()
  3986. // }
  3987. // if tx != nil {
  3988. // tx.Close()
  3989. // }
  3990. msg := geterrmsg(err.Error())
  3991. outentry["error_msg"] = msg
  3992. error++
  3993. queryData = append(queryData, outentry)
  3994. isdone = true
  3995. break
  3996. } else {
  3997. if len(returnmsgmap1) > 0 {
  3998. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3999. // if tx != nil {
  4000. // tx.Rollback()
  4001. // }
  4002. // if tx != nil {
  4003. // tx.Close()
  4004. // }
  4005. msg := geterrmsg(va.(string))
  4006. outentry["error_msg"] = msg
  4007. error++
  4008. queryData = append(queryData, outentry)
  4009. isdone = true
  4010. break
  4011. }
  4012. }
  4013. isdone = false
  4014. }
  4015. }
  4016. }
  4017. if !errExist {
  4018. dataexcel := make(map[string]interface{}, 0)
  4019. if _, ok := outentry["栏舍名称"]; ok {
  4020. dataexcel["barname"] = outentry["栏舍名称"]
  4021. }
  4022. if _, ok := outentry["实际牛头数"]; ok {
  4023. dataexcel["ccount"] = outentry["实际牛头数"]
  4024. }
  4025. if _, ok := outentry["系数(%)"]; ok {
  4026. dataexcel["ratio"] = outentry["系数(%)"]
  4027. }
  4028. if _, ok := outentry["配方模板"]; ok {
  4029. dataexcel["ftname"] = outentry["配方模板"]
  4030. }
  4031. if _, ok := outentry["补料配方"]; ok {
  4032. dataexcel["ptsfname"] = outentry["补料配方"]
  4033. }
  4034. if _, ok := outentry["第一班比例(%)"]; ok {
  4035. dataexcel["1"] = outentry["第一班比例(%)"]
  4036. }
  4037. if _, ok := outentry["第二班比例(%)"]; ok {
  4038. dataexcel["2"] = outentry["第二班比例(%)"]
  4039. }
  4040. if _, ok := outentry["第三班比例(%)"]; ok {
  4041. dataexcel["3"] = outentry["第三班比例(%)"]
  4042. }
  4043. if _, ok := outentry["第四班比例(%)"]; ok {
  4044. dataexcel["4"] = outentry["第四班比例(%)"]
  4045. }
  4046. if _, ok := outentry["第五班比例(%)"]; ok {
  4047. dataexcel["5"] = outentry["第五班比例(%)"]
  4048. }
  4049. if _, ok := outentry["第六班比例(%)"]; ok {
  4050. dataexcel["6"] = outentry["第六班比例(%)"]
  4051. }
  4052. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4053. if err != nil {
  4054. logs.Error(err)
  4055. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4056. return
  4057. }
  4058. if !existbar {
  4059. continue
  4060. }
  4061. _, 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()
  4062. if err != nil {
  4063. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4064. return
  4065. }
  4066. _, 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()
  4067. if err != nil {
  4068. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4069. return
  4070. }
  4071. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4072. if err != nil {
  4073. logs.Error(err)
  4074. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4075. return
  4076. }
  4077. if !existft {
  4078. continue
  4079. }
  4080. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4081. if err != nil {
  4082. logs.Error(err)
  4083. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4084. return
  4085. }
  4086. if !ftexist {
  4087. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4088. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4089. if err != nil {
  4090. logs.Error(err)
  4091. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4092. return
  4093. }
  4094. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4095. if err != nil {
  4096. logs.Error(err)
  4097. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4098. return
  4099. }
  4100. }
  4101. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4102. if err != nil {
  4103. logs.Error(err)
  4104. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4105. return
  4106. }
  4107. if !exist {
  4108. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4109. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4110. if err != nil {
  4111. logs.Error(err)
  4112. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4113. return
  4114. }
  4115. }
  4116. var feedpargs []interface{}
  4117. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4118. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4119. if _, ok := dataexcel["ftname"]; ok {
  4120. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4121. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4122. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4123. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4124. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4125. } else {
  4126. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4127. }
  4128. if _, ok := dataexcel["ptsfname"]; ok {
  4129. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4130. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4131. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4132. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4133. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4134. } else {
  4135. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4136. }
  4137. upFeedpSql += " where barname = ? and pastureid = ? "
  4138. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4139. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4140. if err != nil {
  4141. logs.Error(err)
  4142. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4143. return
  4144. }
  4145. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4146. if err != nil {
  4147. logs.Error(err)
  4148. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4149. return
  4150. }
  4151. if !exist1 {
  4152. _, 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) `,
  4153. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4154. if err != nil {
  4155. logs.Error(err)
  4156. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4157. return
  4158. }
  4159. }
  4160. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4161. if err != nil {
  4162. logs.Error(err)
  4163. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4164. return
  4165. }
  4166. if !exist2 {
  4167. _, 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) `,
  4168. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4169. if err != nil {
  4170. logs.Error(err)
  4171. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4172. return
  4173. }
  4174. }
  4175. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4176. if err != nil {
  4177. logs.Error(err)
  4178. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4179. return
  4180. }
  4181. if !exist3 {
  4182. _, 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) `,
  4183. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4184. if err != nil {
  4185. logs.Error(err)
  4186. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4187. return
  4188. }
  4189. }
  4190. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4191. if err != nil {
  4192. logs.Error(err)
  4193. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4194. return
  4195. }
  4196. if !exist4 {
  4197. _, 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) `,
  4198. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4199. if err != nil {
  4200. logs.Error(err)
  4201. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4202. return
  4203. }
  4204. }
  4205. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4206. if err != nil {
  4207. logs.Error(err)
  4208. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4209. return
  4210. }
  4211. if !exist5 {
  4212. _, 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) `,
  4213. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4214. if err != nil {
  4215. logs.Error(err)
  4216. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4217. return
  4218. }
  4219. }
  4220. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4221. if err != nil {
  4222. logs.Error(err)
  4223. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4224. return
  4225. }
  4226. if !exist6 {
  4227. _, 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) `,
  4228. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4229. if err != nil {
  4230. logs.Error(err)
  4231. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4232. return
  4233. }
  4234. }
  4235. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4236. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4237. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4238. and pastureid = ? and times = ?`
  4239. var fpdargs1 []interface{}
  4240. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4241. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4242. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4243. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4244. if err != nil {
  4245. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4246. return
  4247. }
  4248. var fpdargs2 []interface{}
  4249. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4250. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4251. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4252. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4253. if err != nil {
  4254. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4255. return
  4256. }
  4257. var fpdargs3 []interface{}
  4258. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4259. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4260. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4261. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4262. if err != nil {
  4263. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4264. return
  4265. }
  4266. var fpdargs4 []interface{}
  4267. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4268. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4269. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4270. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4271. if err != nil {
  4272. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4273. return
  4274. }
  4275. var fpdargs5 []interface{}
  4276. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4277. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4278. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4279. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4280. if err != nil {
  4281. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4282. return
  4283. }
  4284. var fpdargs6 []interface{}
  4285. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4286. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4287. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4288. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4289. if err != nil {
  4290. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4291. return
  4292. }
  4293. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4294. 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()
  4295. if err != nil {
  4296. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4297. return
  4298. }
  4299. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4300. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4301. upFpdetailList := make([]*upFpdetail, 0)
  4302. for _, newfpd := range newList {
  4303. for _, oldfpd := range oldFpdList {
  4304. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4305. var oldweight, newweight float64
  4306. if oldfpd["weight"] != nil {
  4307. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4308. }
  4309. if newfpd["weight"] != nil {
  4310. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4311. }
  4312. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4313. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4314. Old: oldweight,
  4315. New: newweight,
  4316. Times: newfpd["times"].(int64),
  4317. Ptid: newfpd["ptid"].(int64),
  4318. Fweight: fweight,
  4319. Id: oldfpd["id"].(int64),
  4320. })
  4321. break
  4322. }
  4323. }
  4324. }
  4325. // fmt.Println(dataexcel["barname"])
  4326. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4327. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4328. }
  4329. }
  4330. if !isdone {
  4331. ok++
  4332. isdone = true
  4333. }
  4334. }
  4335. for barname, v := range dataList {
  4336. for _, v1 := range v {
  4337. count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4338. and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4339. if count == 1 {
  4340. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4341. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4342. if err != nil {
  4343. logs.Error(err)
  4344. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4345. return
  4346. }
  4347. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4348. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4349. if err != nil {
  4350. logs.Error(err)
  4351. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4352. return
  4353. }
  4354. }
  4355. }
  4356. updateFpdetailByBar(pastureid, barname, v)
  4357. }
  4358. } else {
  4359. 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
  4360. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4361. if err != nil {
  4362. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4363. return
  4364. }
  4365. rows := xlsx1.GetRows(sheetname)
  4366. // 限制10000条,多余的截取掉
  4367. if len(rows) > 10000 {
  4368. rows = rows[:10000]
  4369. }
  4370. dataList := make(map[string][]*upFpdetail, 0)
  4371. for i, row := range rows {
  4372. if i > 0 {
  4373. entry := make(map[string]interface{})
  4374. outentry := make(map[string]interface{})
  4375. for j, colCell := range rows[0] {
  4376. for k, colCell1 := range row {
  4377. if j == k {
  4378. outentry[colCell] = colCell1
  4379. entry[colCell] = colCell1
  4380. }
  4381. }
  4382. }
  4383. inputdata = ""
  4384. a := ""
  4385. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4386. //校验日期格式
  4387. for _, v := range dateParamslist {
  4388. if v == "" {
  4389. continue
  4390. }
  4391. if d, ok := outentry[v]; ok {
  4392. dtime, err := TransfTime(d.(string))
  4393. if err != nil {
  4394. a = v
  4395. break
  4396. }
  4397. outentry[v] = dtime
  4398. }
  4399. }
  4400. if a != "" {
  4401. outentry["error_msg"] = a + " format error"
  4402. error++
  4403. queryData = append(queryData, outentry)
  4404. continue
  4405. }
  4406. a = ""
  4407. //校验必填格式
  4408. for _, v := range requiredParamslist {
  4409. if v == "" {
  4410. continue
  4411. }
  4412. if d, ok := outentry[v]; !ok || d == "" {
  4413. a = v
  4414. break
  4415. }
  4416. }
  4417. if a != "" {
  4418. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4419. error++
  4420. queryData = append(queryData, outentry)
  4421. continue
  4422. }
  4423. a = ""
  4424. //校验数字格式
  4425. for _, v := range numParamslist {
  4426. if v == "" {
  4427. continue
  4428. }
  4429. d, ok := outentry[v]
  4430. if !ok || d == "" {
  4431. outentry[v] = 0
  4432. } else {
  4433. var fl float64
  4434. switch d.(type) {
  4435. case string:
  4436. fl, err = strconv.ParseFloat(d.(string), 64)
  4437. }
  4438. if err != nil || fl < 0 {
  4439. a = v
  4440. break
  4441. }
  4442. }
  4443. }
  4444. if a != "" {
  4445. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4446. error++
  4447. queryData = append(queryData, outentry)
  4448. continue
  4449. }
  4450. errExist := false
  4451. for _, sqlnamestr := range sqlslist {
  4452. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4453. paramslist := strings.Split(paramslists, ",")
  4454. if len(paramslist) > 0 {
  4455. s_params := make([]interface{}, 0)
  4456. for _, value := range paramslist {
  4457. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4458. if tempv, exists := c.Get("jwt_username"); exists {
  4459. s_params = append(s_params, tempv.(string))
  4460. } else {
  4461. s_params = append(s_params, "")
  4462. }
  4463. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4464. s_params = append(s_params, pastureid)
  4465. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4466. ids, err := setting.SnowIds.NextId()
  4467. if err != nil {
  4468. ids = time.Now().UnixNano()
  4469. logging.Info("create SnowIds err", err)
  4470. }
  4471. s_params = append(s_params, ids)
  4472. } else {
  4473. if outentry[strings.Trim(value, " ")] == nil {
  4474. s_params = append(s_params, "")
  4475. } else {
  4476. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4477. }
  4478. }
  4479. }
  4480. outentry["input"] = inputdata
  4481. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4482. if err != nil {
  4483. errExist = true
  4484. // if tx != nil {
  4485. // tx.Rollback()
  4486. // }
  4487. // if tx != nil {
  4488. // tx.Close()
  4489. // }
  4490. msg := geterrmsg(err.Error())
  4491. outentry["error_msg"] = msg
  4492. error++
  4493. queryData = append(queryData, outentry)
  4494. isdone = true
  4495. break
  4496. } else {
  4497. if len(returnmsgmap1) > 0 {
  4498. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4499. // if tx != nil {
  4500. // tx.Rollback()
  4501. // }
  4502. // if tx != nil {
  4503. // tx.Close()
  4504. // }
  4505. msg := geterrmsg(va.(string))
  4506. outentry["error_msg"] = msg
  4507. error++
  4508. queryData = append(queryData, outentry)
  4509. isdone = true
  4510. break
  4511. }
  4512. }
  4513. isdone = false
  4514. }
  4515. }
  4516. }
  4517. if !errExist {
  4518. dataexcel := make(map[string]interface{}, 0)
  4519. if _, ok := outentry["Pen Name"]; ok {
  4520. dataexcel["barname"] = outentry["Pen Name"]
  4521. }
  4522. if _, ok := outentry["Actual Cattle Number"]; ok {
  4523. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4524. }
  4525. if _, ok := outentry["Coefficient(%)"]; ok {
  4526. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4527. }
  4528. if _, ok := outentry["Formula Template"]; ok {
  4529. dataexcel["ftname"] = outentry["Formula Template"]
  4530. }
  4531. if _, ok := outentry["Supplement Formula"]; ok {
  4532. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4533. }
  4534. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4535. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4536. }
  4537. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4538. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4539. }
  4540. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4541. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4542. }
  4543. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4544. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4545. }
  4546. if _, ok := outentry["Fifth shift Ratio(%)"]; ok {
  4547. dataexcel["5"] = outentry["Fifth shift Ratio(%)"]
  4548. }
  4549. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4550. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4551. }
  4552. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4553. if err != nil {
  4554. logs.Error(err)
  4555. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4556. return
  4557. }
  4558. if !existbar {
  4559. continue
  4560. }
  4561. _, 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()
  4562. if err != nil {
  4563. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4564. return
  4565. }
  4566. _, 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()
  4567. if err != nil {
  4568. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4569. return
  4570. }
  4571. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4572. if err != nil {
  4573. logs.Error(err)
  4574. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  4575. return
  4576. }
  4577. if !existft {
  4578. continue
  4579. }
  4580. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4581. if err != nil {
  4582. logs.Error(err)
  4583. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4584. return
  4585. }
  4586. if !ftexist {
  4587. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4588. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4589. if err != nil {
  4590. logs.Error(err)
  4591. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4592. return
  4593. }
  4594. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4595. if err != nil {
  4596. logs.Error(err)
  4597. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4598. return
  4599. }
  4600. }
  4601. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4602. if err != nil {
  4603. logs.Error(err)
  4604. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4605. return
  4606. }
  4607. if !exist {
  4608. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4609. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4610. if err != nil {
  4611. logs.Error(err)
  4612. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4613. return
  4614. }
  4615. }
  4616. var feedpargs []interface{}
  4617. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4618. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4619. if _, ok := dataexcel["ftname"]; ok {
  4620. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4621. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4622. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4623. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4624. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4625. } else {
  4626. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4627. }
  4628. if _, ok := dataexcel["ptsfname"]; ok {
  4629. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4630. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4631. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4632. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4633. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4634. } else {
  4635. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4636. }
  4637. upFeedpSql += " where barname = ? and pastureid = ? "
  4638. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4639. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4640. if err != nil {
  4641. logs.Error(err)
  4642. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4643. return
  4644. }
  4645. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4646. if err != nil {
  4647. logs.Error(err)
  4648. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4649. return
  4650. }
  4651. if !exist1 {
  4652. _, 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) `,
  4653. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4654. if err != nil {
  4655. logs.Error(err)
  4656. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4657. return
  4658. }
  4659. }
  4660. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4661. if err != nil {
  4662. logs.Error(err)
  4663. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4664. return
  4665. }
  4666. if !exist2 {
  4667. _, 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) `,
  4668. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4669. if err != nil {
  4670. logs.Error(err)
  4671. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4672. return
  4673. }
  4674. }
  4675. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4676. if err != nil {
  4677. logs.Error(err)
  4678. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4679. return
  4680. }
  4681. if !exist3 {
  4682. _, 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) `,
  4683. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4684. if err != nil {
  4685. logs.Error(err)
  4686. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4687. return
  4688. }
  4689. }
  4690. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4691. if err != nil {
  4692. logs.Error(err)
  4693. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4694. return
  4695. }
  4696. if !exist4 {
  4697. _, 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) `,
  4698. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4699. if err != nil {
  4700. logs.Error(err)
  4701. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4702. return
  4703. }
  4704. }
  4705. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4706. if err != nil {
  4707. logs.Error(err)
  4708. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4709. return
  4710. }
  4711. if !exist5 {
  4712. _, 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) `,
  4713. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4714. if err != nil {
  4715. logs.Error(err)
  4716. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4717. return
  4718. }
  4719. }
  4720. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4721. if err != nil {
  4722. logs.Error(err)
  4723. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4724. return
  4725. }
  4726. if !exist6 {
  4727. _, 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) `,
  4728. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4729. if err != nil {
  4730. logs.Error(err)
  4731. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4732. return
  4733. }
  4734. }
  4735. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4736. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4737. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4738. and pastureid = ? and times = ?`
  4739. var fpdargs1 []interface{}
  4740. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4741. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4742. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4743. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4744. if err != nil {
  4745. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4746. return
  4747. }
  4748. var fpdargs2 []interface{}
  4749. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4750. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4751. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4752. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4753. if err != nil {
  4754. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4755. return
  4756. }
  4757. var fpdargs3 []interface{}
  4758. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4759. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4760. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4761. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4762. if err != nil {
  4763. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4764. return
  4765. }
  4766. var fpdargs4 []interface{}
  4767. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4768. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4769. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4770. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4771. if err != nil {
  4772. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4773. return
  4774. }
  4775. var fpdargs5 []interface{}
  4776. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4777. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4778. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4779. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4780. if err != nil {
  4781. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4782. return
  4783. }
  4784. var fpdargs6 []interface{}
  4785. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4786. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4787. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4788. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4789. if err != nil {
  4790. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4791. return
  4792. }
  4793. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4794. 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()
  4795. if err != nil {
  4796. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4797. return
  4798. }
  4799. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4800. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4801. upFpdetailList := make([]*upFpdetail, 0)
  4802. for _, newfpd := range newList {
  4803. for _, oldfpd := range oldFpdList {
  4804. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4805. var oldweight, newweight float64
  4806. if oldfpd["weight"] != nil {
  4807. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4808. }
  4809. if newfpd["weight"] != nil {
  4810. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4811. }
  4812. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4813. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4814. Old: oldweight,
  4815. New: newweight,
  4816. Times: newfpd["times"].(int64),
  4817. Ptid: newfpd["ptid"].(int64),
  4818. Fweight: fweight,
  4819. Id: oldfpd["id"].(int64),
  4820. })
  4821. break
  4822. }
  4823. }
  4824. }
  4825. // fmt.Println(dataexcel["barname"])
  4826. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4827. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4828. }
  4829. }
  4830. if !isdone {
  4831. ok++
  4832. isdone = true
  4833. }
  4834. }
  4835. for barname, v := range dataList {
  4836. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  4837. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  4838. if err != nil {
  4839. logs.Error(err)
  4840. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4841. return
  4842. }
  4843. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4844. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  4845. if err != nil {
  4846. logs.Error(err)
  4847. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4848. return
  4849. }
  4850. updateFpdetailByBar(pastureid, barname, v)
  4851. }
  4852. }
  4853. data := make(map[string]interface{})
  4854. data["result"] = queryData
  4855. data["success"] = ok
  4856. data["err_count"] = error
  4857. appG.Response(http.StatusOK, e.SUCCESS, data)
  4858. }
  4859. type upFpdetail struct {
  4860. Old float64
  4861. New float64
  4862. Times int64
  4863. Ptid int64
  4864. Fweight float64
  4865. Id int64
  4866. // Ptsid string
  4867. }
  4868. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  4869. tx := restful.Engine.NewSession()
  4870. defer tx.Close()
  4871. tx.Begin()
  4872. 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 `,
  4873. pastureid, barname).Query().List()
  4874. if err != nil {
  4875. logs.Error(err)
  4876. }
  4877. for _, fpd := range fpdList {
  4878. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  4879. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  4880. pastureid, fpd["id"], fpd["times"]).Query().List()
  4881. if err != nil {
  4882. tx.Rollback()
  4883. logs.Error(err)
  4884. return err
  4885. }
  4886. var lweight float64
  4887. for _, lppland := range lpplandList {
  4888. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4889. lweight += lweight1
  4890. }
  4891. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4892. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4893. if fpdweight >= ptuse && lweight == ptuse {
  4894. continue
  4895. } else {
  4896. if lweight <= fpdweight {
  4897. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  4898. if err != nil {
  4899. tx.Rollback()
  4900. logs.Error(err)
  4901. return err
  4902. }
  4903. } else {
  4904. weight := lweight - fpdweight
  4905. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  4906. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  4907. if err != nil {
  4908. tx.Rollback()
  4909. logs.Error(err)
  4910. return err
  4911. }
  4912. for _, lppland := range lpplandList {
  4913. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4914. if weight >= lpplandlweight {
  4915. weight = weight - lpplandlweight
  4916. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  4917. if err != nil {
  4918. tx.Rollback()
  4919. logs.Error(err)
  4920. return err
  4921. }
  4922. } else {
  4923. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4924. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  4925. if err != nil {
  4926. tx.Rollback()
  4927. logs.Error(err)
  4928. return err
  4929. }
  4930. weight = 0
  4931. break
  4932. }
  4933. }
  4934. }
  4935. }
  4936. }
  4937. for _, list := range dataList {
  4938. ftmap := make(map[string]interface{})
  4939. ftmap["old"] = list.Old
  4940. ftmap["new"] = list.New
  4941. ftmap["times"] = list.Times
  4942. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  4943. ftmap["ptsid"] = ""
  4944. // fmt.Println(ftmap)
  4945. // 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 ,
  4946. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  4947. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  4948. // UNION
  4949. fpdDataList, err := tx.SQL(`
  4950. 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 ,
  4951. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  4952. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  4953. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  4954. if err != nil {
  4955. tx.Rollback()
  4956. logs.Error(err)
  4957. }
  4958. for _, fpd := range fpdDataList {
  4959. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  4960. // fttype := -1
  4961. // if fpd["fttype"].(string) == "1" {
  4962. fttype := 1
  4963. // }
  4964. var fweight float64
  4965. var lweight float64
  4966. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4967. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  4968. join lpplandtl1 lppland on lpp.id = lppland.lppid
  4969. join tmr t on t.id = lpp.tmrid
  4970. where lppland.fpdid =?
  4971. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4972. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  4973. if err != nil {
  4974. tx.Rollback()
  4975. logs.Error(err)
  4976. }
  4977. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  4978. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  4979. // 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
  4980. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4981. var w float64
  4982. var status int
  4983. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  4984. if weight >= 0 {
  4985. continue
  4986. }
  4987. w = weight
  4988. status = 0
  4989. } else {
  4990. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  4991. // continue
  4992. // }
  4993. w = weight
  4994. status = 1
  4995. }
  4996. // for _, lppland := range lpplandtl1List {
  4997. // lweight += lppland.Lweight
  4998. // }
  4999. for _, lppland := range lpplandtl1List {
  5000. lpplandInfo := new(lpplandtlInfo)
  5001. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5002. lweight = lpplandInfo.Lweight
  5003. if status == 1 {
  5004. // if w <= lppland.Lweight {
  5005. if lppland.Maxweight <= lweight {
  5006. continue
  5007. }
  5008. if w+lweight <= lppland.Maxweight {
  5009. lppland.Lweight += w
  5010. lweight += w
  5011. fweight += w
  5012. w = 0
  5013. } else {
  5014. w = w - (lppland.Maxweight - lweight)
  5015. n := (lppland.Maxweight - lweight)
  5016. lppland.Lweight = lppland.Lweight + n
  5017. lweight += n
  5018. fweight += n
  5019. }
  5020. } else {
  5021. if lppland.Lweight == 0 {
  5022. continue
  5023. }
  5024. if w+lppland.Lweight >= 0 {
  5025. lppland.Lweight = lppland.Lweight + w
  5026. lweight = lweight + w
  5027. fweight = fweight + w
  5028. w = 0
  5029. } else {
  5030. w = w + lppland.Lweight
  5031. lweight = lweight - lppland.Lweight
  5032. fweight = fweight - lppland.Lweight
  5033. lppland.Lweight = 0
  5034. }
  5035. }
  5036. if lppland.Lweight > 0 {
  5037. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5038. if err != nil {
  5039. tx.Rollback()
  5040. logs.Error(err)
  5041. return err
  5042. }
  5043. } else {
  5044. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5045. if err != nil {
  5046. tx.Rollback()
  5047. logs.Error(err)
  5048. return err
  5049. }
  5050. }
  5051. if w == 0 {
  5052. break
  5053. }
  5054. }
  5055. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5056. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5057. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5058. if err != nil {
  5059. tx.Rollback()
  5060. logs.Error(err)
  5061. }
  5062. if w == 0 {
  5063. break
  5064. }
  5065. }
  5066. }
  5067. }
  5068. // for _, data := range dataList {
  5069. // fttype := -1
  5070. // if data.Ptid != -1 {
  5071. // fttype = 1
  5072. // }
  5073. // var fweight float64
  5074. // var lweight float64
  5075. // lpplandtl1List := make([]*lpplandtlInfo, 0)
  5076. // err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  5077. // join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  5078. // and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5079. // data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  5080. // if err != nil {
  5081. // tx.Rollback()
  5082. // logs.Error(err)
  5083. // return err
  5084. // }
  5085. // weight := data.Fweight
  5086. // // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5087. // var w float64
  5088. // var status int
  5089. // if data.New < data.Old {
  5090. // if weight >= 0 {
  5091. // continue
  5092. // }
  5093. // w = weight
  5094. // status = 0
  5095. // } else {
  5096. // // if weight-(data.New-data.Old) > 0 {
  5097. // // continue
  5098. // // }
  5099. // w = data.New - data.Old
  5100. // status = 1
  5101. // }
  5102. // for _, lppland := range lpplandtl1List {
  5103. // var lppdata lpplandtlInfo
  5104. // tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  5105. // lppland.Lppid, pastureid).GetFirst(&lppdata)
  5106. // if err != nil {
  5107. // tx.Rollback()
  5108. // logs.Error(err)
  5109. // return err
  5110. // }
  5111. // lweight = lppdata.Lweight
  5112. // if status == 1 {
  5113. // // if w <= lppland.Lweight {
  5114. // if lppland.Maxweight <= lweight {
  5115. // continue
  5116. // }
  5117. // if w+lweight <= lppland.Maxweight {
  5118. // lppland.Lweight += w
  5119. // lweight += w
  5120. // fweight += w
  5121. // w = 0
  5122. // } else {
  5123. // w = w - (lppland.Maxweight - lweight)
  5124. // n := (lppland.Maxweight - lweight)
  5125. // lppland.Lweight = lppland.Lweight + n
  5126. // lweight += n
  5127. // fweight += n
  5128. // }
  5129. // } else {
  5130. // if lppland.Lweight == 0 {
  5131. // continue
  5132. // }
  5133. // if w+lppland.Lweight >= 0 {
  5134. // lppland.Lweight = lppland.Lweight + w
  5135. // lweight = lweight + w
  5136. // fweight = fweight + w
  5137. // w = 0
  5138. // } else {
  5139. // w = w + lppland.Lweight
  5140. // lweight = lweight - lppland.Lweight
  5141. // fweight = fweight - lppland.Lweight
  5142. // lppland.Lweight = 0
  5143. // }
  5144. // }
  5145. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5146. // if err != nil {
  5147. // tx.Rollback()
  5148. // logs.Error(err)
  5149. // return err
  5150. // }
  5151. // break
  5152. // }
  5153. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5154. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5155. // WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  5156. // if err != nil {
  5157. // tx.Rollback()
  5158. // logs.Error(err)
  5159. // return err
  5160. // }
  5161. // // if w == 0 {
  5162. // // break
  5163. // // }
  5164. // // }
  5165. // }
  5166. err = tx.Commit()
  5167. if err != nil {
  5168. logs.Error(err)
  5169. tx.Rollback()
  5170. return err
  5171. }
  5172. now := time.Now()
  5173. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5174. if err != nil {
  5175. logs.Error(err)
  5176. return nil
  5177. }
  5178. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5179. if err != nil {
  5180. logs.Error(err)
  5181. return nil
  5182. }
  5183. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5184. if err != nil {
  5185. logs.Error(err)
  5186. return nil
  5187. }
  5188. for _, newLpplandtl1 := range newLpplandtl1List {
  5189. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5190. background,cowcount,ccountradio,lweighthis,createdate)
  5191. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5192. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5193. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5194. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5195. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5196. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5197. if err != nil {
  5198. logs.Error(err)
  5199. // appG.Response(http.StatusOK, e.ERROR, false)
  5200. return err
  5201. }
  5202. }
  5203. for _, newFpd := range newFpdDataList {
  5204. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5205. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5206. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5207. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5208. if err != nil {
  5209. logs.Error(err)
  5210. // appG.Response(http.StatusOK, e.ERROR, false)
  5211. return err
  5212. }
  5213. }
  5214. for _, newFeedp := range newFeedpList {
  5215. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5216. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5217. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5218. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5219. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5220. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5221. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5222. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5223. if err != nil {
  5224. logs.Error(err)
  5225. // appG.Response(http.StatusOK, e.ERROR, false)
  5226. return err
  5227. }
  5228. }
  5229. return nil
  5230. }
  5231. func DeleteFTdetail(c *gin.Context) {
  5232. appG := app.Gin{C: c}
  5233. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5234. fsion := gofasion.NewFasion(string(dataByte))
  5235. parammaps := fsion.Get("parammaps")
  5236. pastureid := parammaps.Get("pastureid").ValueStr()
  5237. ftid := parammaps.Get("ftid").ValueStr()
  5238. tx := restful.Engine.NewSession()
  5239. defer tx.Close()
  5240. tx.Begin()
  5241. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5242. if err != nil {
  5243. tx.Rollback()
  5244. logs.Error(err)
  5245. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5246. return
  5247. }
  5248. if parammaps.Get("type").ValueStr() == "1" {
  5249. _, err := tx.SQL(`UPDATE feedp fp
  5250. set
  5251. fp.ftweight= IFNULL(IF(
  5252. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5253. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5254. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5255. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5256. ),0),fp.feedweight = IFNULL(IF(
  5257. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5258. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5259. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5260. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5261. ),0) +ifnull(fp.supplyweight,0)
  5262. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5263. if err != nil {
  5264. tx.Rollback()
  5265. logs.Error(err)
  5266. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5267. return
  5268. }
  5269. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5270. _, err = tx.SQL(`
  5271. UPDATE fpdetail fpd
  5272. INNER JOIN feedp fp
  5273. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5274. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5275. ptuse= 0
  5276. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5277. if err != nil {
  5278. tx.Rollback()
  5279. logs.Error(err)
  5280. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5281. return
  5282. }
  5283. } else {
  5284. _, err := tx.SQL(`UPDATE feedp fp
  5285. SET
  5286. fp.supplyweight= IFNULL(IF(
  5287. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5288. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5289. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5290. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5291. ),0),fp.feedweight = IFNULL(IF(
  5292. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5293. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5294. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5295. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5296. ),0) + ifnull(fp.supplyweight,0)
  5297. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5298. if err != nil {
  5299. tx.Rollback()
  5300. logs.Error(err)
  5301. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5302. return
  5303. }
  5304. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5305. _, err = tx.SQL(`
  5306. UPDATE fpdetail fpd
  5307. INNER JOIN feedp fp
  5308. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5309. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5310. ptsrate = 0
  5311. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5312. if err != nil {
  5313. tx.Rollback()
  5314. logs.Error(err)
  5315. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5316. return
  5317. }
  5318. }
  5319. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5320. if err != nil {
  5321. tx.Rollback()
  5322. logs.Error(err)
  5323. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5324. return
  5325. }
  5326. err = tx.Commit()
  5327. if err != nil {
  5328. tx.Rollback()
  5329. logs.Error(err)
  5330. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5331. return
  5332. }
  5333. appG.Response(http.StatusOK, e.SUCCESS, true)
  5334. }
  5335. func DeleteSpillageAll(c *gin.Context) {
  5336. appG := app.Gin{C: c}
  5337. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5338. fsion := gofasion.NewFasion(string(dataByte))
  5339. parammaps := fsion.Get("parammaps")
  5340. pastureid := parammaps.Get("pastureid").ValueStr()
  5341. times := parammaps.Get("times").ValueStr()
  5342. barid := parammaps.Get("barid").ValueStr()
  5343. tx := restful.Engine.NewSession()
  5344. defer tx.Close()
  5345. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5346. if err != nil {
  5347. logs.Error(err)
  5348. appG.Response(http.StatusOK, e.ERROR, false)
  5349. return
  5350. }
  5351. now := time.Now()
  5352. for _, item := range lpplandtl1List {
  5353. go func(item map[string]interface{}) {
  5354. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5355. background,cowcount,ccountradio,lweighthis,createdate)
  5356. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5357. item["pastureid"], item["lppid"], item["barid"],
  5358. item["barname"], item["fpdid"], item["fttype"],
  5359. item["lweight"], item["sort"], item["tmrid"],
  5360. item["tmrname"], item["background"], item["cowcount"],
  5361. item["ccountradio"], item["lweighthis"], now).Execute()
  5362. if err != nil {
  5363. logs.Error(err)
  5364. appG.Response(http.StatusOK, e.ERROR, false)
  5365. return
  5366. }
  5367. }(item)
  5368. }
  5369. tx.Begin()
  5370. _, 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()
  5371. if err != nil {
  5372. tx.Rollback()
  5373. logs.Error(err)
  5374. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5375. return
  5376. }
  5377. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5378. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5379. if err != nil {
  5380. tx.Rollback()
  5381. logs.Error(err)
  5382. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5383. return
  5384. }
  5385. err = tx.Commit()
  5386. if err != nil {
  5387. tx.Rollback()
  5388. logs.Error(err)
  5389. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5390. return
  5391. }
  5392. appG.Response(http.StatusOK, e.SUCCESS, true)
  5393. }
  5394. func GetTMRListEnableTypeAll(c *gin.Context) {
  5395. appG := app.Gin{C: c}
  5396. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5397. fsion := gofasion.NewFasion(string(dataByte))
  5398. parammaps := fsion.Get("parammaps")
  5399. pastureid := parammaps.Get("pastureid").ValueStr()
  5400. tx := restful.Engine.NewSession()
  5401. defer tx.Close()
  5402. dataList, err := tx.SQL(`SELECT
  5403. eqcode,
  5404. tname,
  5405. datacaptureno,
  5406. trim(tclassid) tclassid,
  5407. concat(tname,' / ',eqcode) tmrmix,
  5408. d.label tclassname,
  5409. maxstirfeed,
  5410. remark,
  5411. tmr.enable,
  5412. TRIM(tmr.id) id,
  5413. TRIM(tmr.pastureid)pastureid
  5414. FROM
  5415. tmr
  5416. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5417. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5418. ORDER BY id DESC`, pastureid).Query().List()
  5419. if err != nil {
  5420. logs.Error(err)
  5421. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5422. return
  5423. }
  5424. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5425. if err != nil {
  5426. logs.Error(err)
  5427. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5428. return
  5429. }
  5430. var carNum int64
  5431. for _, sysopt := range sysoptData {
  5432. if sysopt["inforvalue"] == nil {
  5433. carNum = 1
  5434. } else {
  5435. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5436. }
  5437. }
  5438. id := 200
  5439. n := 0
  5440. for i := carNum; i > 0; i-- {
  5441. id++
  5442. n++
  5443. data := make(map[string]interface{}, 0)
  5444. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5445. data["tname"] = fmt.Sprintf("任意车%d", n)
  5446. data["datacaptureno"] = -2
  5447. data["tclassid"] = -2
  5448. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5449. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5450. data["maxstirfeed"] = 100000
  5451. data["remark"] = fmt.Sprintf("任意车%d", n)
  5452. data["enable"] = 1
  5453. data["id"] = fmt.Sprintf("%d", id)
  5454. data["pastureid"] = pastureid
  5455. dataList = append(dataList, data)
  5456. }
  5457. // UNION ALL
  5458. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5459. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5460. }
  5461. func GetFeedpHistory(c *gin.Context) {
  5462. appG := app.Gin{C: c}
  5463. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5464. fsion := gofasion.NewFasion(string(dataByte))
  5465. // parammaps := fsion.Get("parammaps")
  5466. bar := fsion.Get("barname").ValueStr()
  5467. startDate := fsion.Get("startDate").ValueStr()
  5468. endDate := fsion.Get("endDate").ValueStr()
  5469. tx := restful.Engine.NewSession()
  5470. defer tx.Close()
  5471. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5472. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5473. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5474. if err != nil {
  5475. logs.Error(err)
  5476. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5477. return
  5478. }
  5479. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5480. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5481. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5482. if err != nil {
  5483. logs.Error(err)
  5484. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5485. return
  5486. }
  5487. for _, feedp := range feedpList {
  5488. // LastftList, err := tx.SQL(` select tname ,id
  5489. // from feedtemplethistory where id = ?
  5490. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5491. // if err != nil {
  5492. // logs.Error(err)
  5493. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5494. // return
  5495. // }
  5496. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5497. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5498. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5499. if err != nil {
  5500. logs.Error(err)
  5501. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5502. return
  5503. }
  5504. var ftname interface{}
  5505. ftnamestatus := 0
  5506. ftname = feedp["ftname"]
  5507. var lastftid int64
  5508. if len(nextfeedpList) > 0 {
  5509. for _, ft := range nextfeedpList {
  5510. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5511. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5512. lastftid = ft["ftid"].(int64)
  5513. ftnamestatus = 1
  5514. break
  5515. }
  5516. }
  5517. }
  5518. for i, fpd := range fpdList {
  5519. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5520. fpd["weightstatus"] = 0
  5521. fpd["tratiostatus"] = 0
  5522. fpd["ftnamestatus"] = ftnamestatus
  5523. for k, fpd2 := range fpdList {
  5524. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5525. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5526. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5527. fpd["weightstatus"] = 1
  5528. }
  5529. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5530. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5531. fpd["tratiostatus"] = 1
  5532. }
  5533. break
  5534. }
  5535. }
  5536. fpd["barid"] = feedp["barid"]
  5537. fpd["barname"] = feedp["barname"]
  5538. fpd["ccount"] = feedp["ccount"]
  5539. fpd["ratio"] = feedp["ratio"]
  5540. fpd["ccountratio"] = feedp["ccountratio"]
  5541. fpd["ftid"] = feedp["ftid"]
  5542. fpd["ftname"] = ftname
  5543. fpd["ccountstatus"] = 0
  5544. fpd["ccountratiostatus"] = 0
  5545. fpd["ratiostatus"] = 0
  5546. fpd["ftnamestatus"] = 0
  5547. fpd["lastftid"] = lastftid
  5548. for _, next := range nextfeedpList {
  5549. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5550. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5551. fpd["ccountstatus"] = 1
  5552. }
  5553. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5554. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5555. fpd["ccountratiostatus"] = 1
  5556. }
  5557. if next["ratio"].(string) != fpd["ratio"].(string) {
  5558. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5559. fpd["ratiostatus"] = 1
  5560. }
  5561. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5562. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5563. // fpd["ftnamestatus"] = 1
  5564. // }
  5565. }
  5566. }
  5567. }
  5568. }
  5569. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5570. }
  5571. // func GetLpplandtl1History(c *gin.Context) {
  5572. // appG := app.Gin{C: c}
  5573. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5574. // fsion := gofasion.NewFasion(string(dataByte))
  5575. // // parammaps := fsion.Get("parammaps")
  5576. // barid := fsion.Get("barid").ValueStr()
  5577. // startDate := fsion.Get("startDate").ValueStr()
  5578. // endDate := fsion.Get("endDate").ValueStr()
  5579. // tx := restful.Engine.NewSession()
  5580. // defer tx.Close()
  5581. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5582. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5583. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5584. // // if err != nil {
  5585. // // logs.Error(err)
  5586. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5587. // // return
  5588. // // }
  5589. // // for _, feedp := range feedpList {
  5590. // // fmt.Println(feedp)
  5591. // // for i, fpd := range fpdList {
  5592. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5593. // // for k, fpd2 := range fpdList {
  5594. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5595. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5596. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5597. // // }
  5598. // // break
  5599. // // }
  5600. // // }
  5601. // // fpd["barid"] = feedp["barid"]
  5602. // // fpd["barname"] = feedp["barname"]
  5603. // // fpd["ccount"] = feedp["ccount"]
  5604. // // fpd["ratio"] = feedp["ratio"]
  5605. // // fpd["ccountratio"] = feedp["ccountratio"]
  5606. // // fpd["ftid"] = feedp["ftid"]
  5607. // // fpd["ftname"] = feedp["ftname"]
  5608. // // }
  5609. // // }
  5610. // // }
  5611. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5612. // }
  5613. func GetRemind(c *gin.Context) {
  5614. appG := app.Gin{C: c}
  5615. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5616. fsion := gofasion.NewFasion(string(dataByte))
  5617. parammaps := fsion.Get("parammaps")
  5618. pastureid := parammaps.Get("pastureid").ValueStr()
  5619. tx := restful.Engine.NewSession()
  5620. defer tx.Close()
  5621. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5622. if err != nil {
  5623. logs.Error(err)
  5624. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5625. return
  5626. }
  5627. // pastureid = "3"
  5628. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5629. if err != nil {
  5630. logs.Error(err)
  5631. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5632. return
  5633. }
  5634. defer resp.Body.Close()
  5635. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5636. buf.ReadFrom(resp.Body)
  5637. fmt.Println(string(buf.Bytes()))
  5638. respMap := make(map[string]interface{}, 0)
  5639. err = json.Unmarshal(buf.Bytes(), &respMap)
  5640. if err != nil {
  5641. logs.Error(err)
  5642. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5643. return
  5644. }
  5645. for _, data := range dataList {
  5646. r := make(map[string]interface{}, 0)
  5647. r["sys_name"] = ""
  5648. r["service_id"] = ""
  5649. r["pasture_id"] = ""
  5650. r["type_name"] = ""
  5651. r["remind_type_id"] = ""
  5652. r["remind_type"] = ""
  5653. r["push_date"] = ""
  5654. r["push_time"] = ""
  5655. r["interval_time"] = ""
  5656. r["push_limit"] = ""
  5657. r["template_id"] = ""
  5658. r["roles_id"] = ""
  5659. r["users_id"] = ""
  5660. r["date_type"] = ""
  5661. r["cycle_type"] = ""
  5662. data["data"] = r
  5663. for _, resp := range respMap["data"].([]interface{}) {
  5664. resp1 := resp.(map[string]interface{})
  5665. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5666. if resp1["push_time"] == nil {
  5667. resp1["push_time"] = ""
  5668. }
  5669. data["data"] = resp1
  5670. break
  5671. }
  5672. }
  5673. }
  5674. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5675. }
  5676. type NoticeMsgtype struct {
  5677. SysName string `json:"sys_name"`
  5678. PastureId int64 `json:"pasture_id"`
  5679. ServiceId int64 `json:"service_id"`
  5680. TypeName string `json:"type_name"`
  5681. RemindType int64 `json:"remind_type"`
  5682. PushDate int64 `json:"push_date"`
  5683. PushTime string `json:"push_time"`
  5684. IntervalTime int64 `json:"interval_time"`
  5685. PushLimit int64 `json:"push_limit"`
  5686. TemplateId string `json:"template_id"`
  5687. UsersId string `json:"users_id"`
  5688. DateType int64 `json:"date_type"`
  5689. CycleType int64 `json:"cycle_type"`
  5690. DelayTime int64 `json:"delay_time"`
  5691. Status int64 `json:"status"`
  5692. }
  5693. func UpdateRemind(c *gin.Context) {
  5694. appG := app.Gin{C: c}
  5695. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5696. parammaps := gofasion.NewFasion(string(dataByte))
  5697. // parammaps := fsion.Get("parammaps")
  5698. // user := parammaps.Get("user").ValueStr()
  5699. id := parammaps.Get("id").ValueInt64()
  5700. noticeMsgtype := new(NoticeMsgtype)
  5701. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  5702. noticeMsgtype.ServiceId = id
  5703. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  5704. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  5705. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  5706. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  5707. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  5708. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  5709. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  5710. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  5711. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  5712. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  5713. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  5714. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  5715. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  5716. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  5717. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  5718. //TODO
  5719. noticeMsgtype.SysName = "tmrWatch"
  5720. userList := parammaps.Get("user").Array()
  5721. var userstr []string
  5722. for _, user := range userList {
  5723. userstr = append(userstr, user.ValueStr())
  5724. }
  5725. tx := restful.Engine.NewSession()
  5726. defer tx.Close()
  5727. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  5728. if err != nil {
  5729. logs.Error(err)
  5730. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5731. return
  5732. }
  5733. // var jsonStr = []byte(noticeMsgtype
  5734. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  5735. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  5736. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  5737. req.Header.Set("Content-Type", "application/json")
  5738. client := &http.Client{}
  5739. resp, err := client.Do(req)
  5740. if err != nil {
  5741. logs.Error(err)
  5742. }
  5743. defer resp.Body.Close()
  5744. body, _ := ioutil.ReadAll(resp.Body)
  5745. fmt.Println("response Body:", string(body))
  5746. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  5747. if err != nil {
  5748. logs.Error(err)
  5749. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5750. return
  5751. }
  5752. defer getresp.Body.Close()
  5753. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5754. buf.ReadFrom(getresp.Body)
  5755. // fmt.Println(string(buf.Bytes()))
  5756. respMap := make(map[string]interface{}, 0)
  5757. err = json.Unmarshal(buf.Bytes(), &respMap)
  5758. if err != nil {
  5759. logs.Error(err)
  5760. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5761. return
  5762. }
  5763. for _, resp := range respMap["data"].([]interface{}) {
  5764. resp1 := resp.(map[string]interface{})
  5765. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  5766. if err != nil {
  5767. logs.Error(err)
  5768. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5769. return
  5770. }
  5771. }
  5772. appG.Response(http.StatusOK, e.SUCCESS, true)
  5773. }
  5774. func GetSpillageallHistory(c *gin.Context) {
  5775. appG := app.Gin{C: c}
  5776. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5777. parammaps := gofasion.NewFasion(string(dataByte))
  5778. barname := parammaps.Get("barname").ValueStr()
  5779. pastureid := parammaps.Get("pastureid").ValueStr()
  5780. startdate := parammaps.Get("startDate").ValueStr()
  5781. enddate := parammaps.Get("endDate").ValueStr()
  5782. tx := restful.Engine.NewSession()
  5783. defer tx.Close()
  5784. 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
  5785. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  5786. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  5787. if err != nil {
  5788. logs.Error(err)
  5789. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5790. return
  5791. }
  5792. respMap := make([]map[string]interface{}, 0)
  5793. data := make(map[interface{}]interface{})
  5794. for _, history := range historyList {
  5795. data[history["createdate"]] = history["createdate"]
  5796. }
  5797. createList := []string{}
  5798. for _, v := range data {
  5799. createList = append(createList, v.(string))
  5800. }
  5801. // sort.Sort()
  5802. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  5803. sort.Slice(createList, func(i, j int) bool {
  5804. return createList[i] > createList[j]
  5805. })
  5806. for _, v := range createList {
  5807. a := make(map[string]interface{})
  5808. a["createdate"] = data[v]
  5809. // createList = append(createList, v.(string))
  5810. respMap = append(respMap, a)
  5811. }
  5812. number := 0
  5813. dataMap := make([]interface{}, 0)
  5814. for k, resp := range respMap {
  5815. createdate := resp["createdate"].(string)
  5816. var nextcreatedate string
  5817. if len(respMap) > k+1 {
  5818. nextcreatedate = respMap[k+1]["createdate"].(string)
  5819. }
  5820. // dataList := make(map[string][]interface{})
  5821. // list := make(map[string]interface{})
  5822. times := make(map[interface{}]int)
  5823. for _, history := range historyList {
  5824. // List := make(map[interface{}][]interface{})
  5825. i := 0
  5826. if history["createdate"].(string) == createdate {
  5827. times[history["times"]]++
  5828. data := make(map[string]interface{})
  5829. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  5830. // exist := false
  5831. if nextcreatedate != "" {
  5832. for _, history1 := range historyList {
  5833. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  5834. history1["times"].(int64) == history["times"].(int64) {
  5835. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  5836. break
  5837. // exist = true
  5838. }
  5839. }
  5840. }
  5841. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5842. i++
  5843. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  5844. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  5845. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  5846. // resp["times"] = history["times"]
  5847. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5848. data1 := make(map[string]interface{})
  5849. data1["times"] = history["times"]
  5850. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5851. data1["createdate"] = resp["createdate"]
  5852. // fmt.Println(dataList)
  5853. dataMap = append(dataMap, data1)
  5854. }
  5855. if i > number {
  5856. number = i
  5857. }
  5858. // respMap = append(respMap, dataList)
  5859. }
  5860. // for k, data := range dataList {
  5861. // resp[k] = data
  5862. // }
  5863. // resp["data"] = dataList
  5864. }
  5865. // resp := make(map[string]interface{})
  5866. // sort.Strings(createList)
  5867. //
  5868. // for _, create := range createList {
  5869. // for _, r := range respMap {
  5870. // if create == r["createdate"].(string) {
  5871. // resp[create] = r
  5872. // break
  5873. // }
  5874. // }
  5875. // }
  5876. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  5877. var trainsList []interface{}
  5878. for i := 0; i < number; i++ {
  5879. trains := make(map[string]interface{})
  5880. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  5881. trains["prop"] = fmt.Sprintf("a%d", i+1)
  5882. trainsList = append(trainsList, trains)
  5883. }
  5884. respdata := make(map[string]interface{})
  5885. respdata["data"] = dataMap
  5886. respdata["trains"] = trainsList
  5887. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  5888. }
  5889. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  5890. appG := app.Gin{C: c}
  5891. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5892. parammaps := gofasion.NewFasion(string(dataByte))
  5893. ftid := parammaps.Get("ftid").ValueInt64()
  5894. lastftid := parammaps.Get("lastftid").ValueInt64()
  5895. pastureid := parammaps.Get("pastureid").ValueInt64()
  5896. // createdate := parammaps.Get("createdate").ValueStr()
  5897. tx := restful.Engine.NewSession()
  5898. defer tx.Close()
  5899. data := make(map[string]interface{})
  5900. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5901. and fthis.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 := make(map[string]interface{})
  5908. for _, f := range feedtempletList {
  5909. feedtemplet = f
  5910. }
  5911. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  5912. if err != nil {
  5913. logs.Error(err)
  5914. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5915. return
  5916. }
  5917. feedtemplet["fit"] = fitList
  5918. data["current"] = feedtemplet
  5919. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5920. and fthis.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 := make(map[string]interface{})
  5927. for _, f := range lastfeedtempletList {
  5928. lastfeedtemplet = f
  5929. }
  5930. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  5931. if err != nil {
  5932. logs.Error(err)
  5933. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5934. return
  5935. }
  5936. lastfeedtemplet["fit"] = lastfitList
  5937. data["last"] = lastfeedtemplet
  5938. appG.Response(http.StatusOK, e.SUCCESS, data)
  5939. }
  5940. func GetFeedtempletHistory(c *gin.Context) {
  5941. appG := app.Gin{C: c}
  5942. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5943. parammaps := gofasion.NewFasion(string(dataByte))
  5944. ftid := parammaps.Get("ftid").ValueStr()
  5945. pastureid := parammaps.Get("pastureid").ValueInt64()
  5946. start := parammaps.Get("startdate").ValueStr()
  5947. end := parammaps.Get("enddate").ValueStr()
  5948. tx := restful.Engine.NewSession()
  5949. defer tx.Close()
  5950. 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 ?
  5951. and id = ? and pastureid = ? order by createdate desc `,
  5952. start, end, ftid, pastureid).Query().List()
  5953. if err != nil {
  5954. logs.Error(err)
  5955. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5956. return
  5957. }
  5958. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  5959. ftid, pastureid).Query().List()
  5960. if err != nil {
  5961. logs.Error(err)
  5962. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5963. return
  5964. }
  5965. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  5966. for i, ft := range ftList {
  5967. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  5968. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  5969. (select empname from user where id = fit.userId) empname,
  5970. 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
  5971. where fit.fitid = ?
  5972. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  5973. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  5974. if err != nil {
  5975. logs.Error(err)
  5976. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5977. return
  5978. }
  5979. ft["createdate"] = ft["createdate1"]
  5980. // data["tname"] = ft["tname"]
  5981. // data["tcode"] = ft["tcode"]
  5982. // data["tcolor"] = ft["tcolor"]
  5983. // data["fttype"] = ft["fttype"]
  5984. // data["ccname"] = ft["ccname"]
  5985. // data["source"] = ft["source"]
  5986. // data["version"] = ft["version"]
  5987. // data["remark"] = ft["remark"]
  5988. for n, ft2 := range ftList {
  5989. if i < n {
  5990. if ft["tname"].(string) != ft2["tname"].(string) {
  5991. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  5992. }
  5993. if _, ok := ft["tcode"]; ok {
  5994. if _, ok := ft2["tcode"]; ok {
  5995. if ft["tcode"].(string) != ft2["tcode"].(string) {
  5996. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  5997. }
  5998. }
  5999. }
  6000. if _, ok := ft["tcolor"]; ok {
  6001. if _, ok := ft2["tcolor"]; ok {
  6002. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6003. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6004. }
  6005. }
  6006. }
  6007. if _, ok := ft["fttype"]; ok {
  6008. if _, ok := ft2["fttype"]; ok {
  6009. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6010. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6011. }
  6012. }
  6013. }
  6014. if _, ok := ft["ccname"]; ok {
  6015. if _, ok := ft2["ccname"]; ok {
  6016. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6017. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6018. }
  6019. }
  6020. }
  6021. if _, ok := ft["source"]; ok {
  6022. if _, ok := ft2["source"]; ok {
  6023. if ft["source"].(string) != ft2["source"].(string) {
  6024. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6025. }
  6026. }
  6027. }
  6028. if _, ok := ft["version"]; ok {
  6029. if _, ok := ft2["version"]; ok {
  6030. if ft["version"].(int64) != ft2["version"].(int64) {
  6031. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6032. }
  6033. }
  6034. }
  6035. if _, ok := ft["remark"]; ok {
  6036. if _, ok := ft2["remark"]; ok {
  6037. if ft["remark"].(string) != ft2["remark"].(string) {
  6038. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6039. }
  6040. }
  6041. }
  6042. break
  6043. }
  6044. }
  6045. dataList := make([]map[string]interface{}, 0)
  6046. if len(fithisList) > 0 {
  6047. for _, fit := range fithisList {
  6048. data := make(map[string]interface{})
  6049. data["feedgroup"] = fit["feedgroup"]
  6050. data["fname"] = fit["fname"]
  6051. data["empname"] = fit["empname"]
  6052. if fit["Eweight"] != nil {
  6053. if fit["Eweight"].(string) != fit["weight"].(string) {
  6054. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6055. } else {
  6056. data["fweight"] = fit["Eweight"]
  6057. }
  6058. data["fweightstatus"] = 1
  6059. } else {
  6060. data["fweight"] = fit["weight"]
  6061. data["fweightstatus"] = 0
  6062. }
  6063. data["autosecond"] = fit["autosecond"]
  6064. // data["tname"] = ft["tname"]
  6065. // data["tcode"] = ft["tcode"]
  6066. // data["tcolor"] = ft["tcolor"]
  6067. // data["fttype"] = ft["fttype"]
  6068. // data["ccname"] = ft["ccname"]
  6069. // data["source"] = ft["source"]
  6070. // data["version"] = ft["version"]
  6071. // data["remark"] = ft["remark"]
  6072. // data["createdate"] = ft["createdate1"]
  6073. // ft["fit"] = data
  6074. dataList = append(dataList, data)
  6075. }
  6076. } else {
  6077. for _, fit := range ftdetailList {
  6078. data := make(map[string]interface{})
  6079. data["feedgroup"] = fit["feedgroup"]
  6080. data["fname"] = fit["fname"]
  6081. // if fit["Eweight"] != nil {
  6082. // data["weight"] = fit["Eweight"]
  6083. // } else {
  6084. data["fweight"] = fit["fweight"]
  6085. // }
  6086. data["autosecond"] = fit["autosecond"]
  6087. // ft["fit"] = data
  6088. dataList = append(dataList, data)
  6089. }
  6090. }
  6091. ft["fit"] = dataList
  6092. }
  6093. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6094. }
  6095. func UpdateMaterialTMR(c *gin.Context) {
  6096. appG := app.Gin{C: c}
  6097. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6098. parammaps := gofasion.NewFasion(string(dataByte))
  6099. tmrid := parammaps.Get("tmrid").ValueStr()
  6100. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6101. lppid := parammaps.Get("lppid").ValueStr()
  6102. times := parammaps.Get("times").ValueStr()
  6103. pastureid := parammaps.Get("pastureid").ValueStr()
  6104. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6105. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6106. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6107. tx := restful.Engine.NewSession()
  6108. defer tx.Close()
  6109. tx.Begin()
  6110. if tmrid != "1000" {
  6111. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6112. if err != nil {
  6113. logs.Error(err)
  6114. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6115. return
  6116. }
  6117. var maxstirfeed float64
  6118. for _, tmr := range tmrList {
  6119. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6120. }
  6121. if status == 0 {
  6122. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6123. if err != nil {
  6124. tx.Rollback()
  6125. logs.Error(err)
  6126. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6127. return
  6128. }
  6129. var lweight float64
  6130. for _, item := range lpplandtl1List {
  6131. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6132. lweight += fl
  6133. }
  6134. if lweight > maxstirfeed {
  6135. lweight = lweight - maxstirfeed
  6136. } else {
  6137. lweight = 0
  6138. }
  6139. if lweight > 0 {
  6140. lweight1 := lweight / float64(len(lpplandtl1List))
  6141. number := 0
  6142. for _, item := range lpplandtl1List {
  6143. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6144. if lweight1 >= fl {
  6145. number++
  6146. }
  6147. }
  6148. lweight := lweight / float64((len(lpplandtl1List) - number))
  6149. for _, item := range lpplandtl1List {
  6150. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6151. if lweight1 >= fl {
  6152. continue
  6153. }
  6154. if tmrtype == "1" {
  6155. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6156. if err != nil {
  6157. tx.Rollback()
  6158. logs.Error(err)
  6159. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6160. return
  6161. }
  6162. } else if tmrtype == "2" {
  6163. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6164. if err != nil {
  6165. tx.Rollback()
  6166. logs.Error(err)
  6167. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6168. return
  6169. }
  6170. }
  6171. if item["fttype"].(int64) == 0 {
  6172. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6173. if err != nil {
  6174. tx.Rollback()
  6175. logs.Error(err)
  6176. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6177. return
  6178. }
  6179. } else {
  6180. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6181. if err != nil {
  6182. tx.Rollback()
  6183. logs.Error(err)
  6184. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6185. return
  6186. }
  6187. }
  6188. }
  6189. } else {
  6190. for _, item := range lpplandtl1List {
  6191. // 自走式
  6192. if tmrtype == "1" {
  6193. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6194. if err != nil {
  6195. logs.Error(err)
  6196. tx.Rollback()
  6197. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6198. return
  6199. }
  6200. } else if tmrtype == "2" {
  6201. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6202. if err != nil {
  6203. logs.Error(err)
  6204. tx.Rollback()
  6205. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6206. return
  6207. }
  6208. }
  6209. }
  6210. }
  6211. } else if status == 1 {
  6212. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6213. if err != nil {
  6214. logs.Error(err)
  6215. tx.Rollback()
  6216. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6217. return
  6218. }
  6219. var lweight float64
  6220. for _, item := range lpplandtl1List {
  6221. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6222. lweight += fl
  6223. }
  6224. if lweight > maxstirfeed {
  6225. lweight = lweight - maxstirfeed
  6226. } else {
  6227. lweight = 0
  6228. }
  6229. for _, item := range lpplandtl1List {
  6230. if lweight > 0 {
  6231. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6232. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6233. if fl >= lweight {
  6234. item["lweight"] = fl - lweight
  6235. lweight = 0
  6236. if tmrtype == "1" {
  6237. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6238. if err != nil {
  6239. logs.Error(err)
  6240. tx.Rollback()
  6241. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6242. return
  6243. }
  6244. } else if tmrtype == "2" {
  6245. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6246. if err != nil {
  6247. logs.Error(err)
  6248. tx.Rollback()
  6249. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6250. return
  6251. }
  6252. }
  6253. if item["fttype"].(int64) == 0 {
  6254. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6255. if err != nil {
  6256. logs.Error(err)
  6257. tx.Rollback()
  6258. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6259. return
  6260. }
  6261. } else {
  6262. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6263. if err != nil {
  6264. logs.Error(err)
  6265. tx.Rollback()
  6266. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6267. return
  6268. }
  6269. }
  6270. } else {
  6271. lweight = lweight - fl
  6272. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6273. if err != nil {
  6274. logs.Error(err)
  6275. tx.Rollback()
  6276. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6277. return
  6278. }
  6279. if item["fttype"].(int64) == 0 {
  6280. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6281. if err != nil {
  6282. logs.Error(err)
  6283. tx.Rollback()
  6284. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6285. return
  6286. }
  6287. } else {
  6288. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6289. if err != nil {
  6290. logs.Error(err)
  6291. tx.Rollback()
  6292. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6293. return
  6294. }
  6295. }
  6296. }
  6297. } else {
  6298. // 自走式
  6299. if tmrtype == "1" {
  6300. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6301. if err != nil {
  6302. logs.Error(err)
  6303. tx.Rollback()
  6304. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6305. return
  6306. }
  6307. } else if tmrtype == "2" {
  6308. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6309. if err != nil {
  6310. logs.Error(err)
  6311. tx.Rollback()
  6312. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6313. return
  6314. }
  6315. }
  6316. }
  6317. }
  6318. } else {
  6319. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6320. if err != nil {
  6321. logs.Error(err)
  6322. tx.Rollback()
  6323. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6324. return
  6325. }
  6326. for _, item := range lpplandtl1List {
  6327. if item["fttype"].(int64) == 0 {
  6328. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6329. if err != nil {
  6330. logs.Error(err)
  6331. tx.Rollback()
  6332. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6333. return
  6334. }
  6335. } else {
  6336. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6337. if err != nil {
  6338. logs.Error(err)
  6339. tx.Rollback()
  6340. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6341. return
  6342. }
  6343. }
  6344. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6345. if err != nil {
  6346. logs.Error(err)
  6347. tx.Rollback()
  6348. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6349. return
  6350. }
  6351. }
  6352. }
  6353. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6354. if err != nil {
  6355. logs.Error(err)
  6356. tx.Rollback()
  6357. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6358. return
  6359. }
  6360. } else {
  6361. if status == 2 {
  6362. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6363. if err != nil {
  6364. logs.Error(err)
  6365. tx.Rollback()
  6366. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6367. return
  6368. }
  6369. for _, item := range lpplandtl1List {
  6370. if item["fttype"].(int64) == 0 {
  6371. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6372. if err != nil {
  6373. logs.Error(err)
  6374. tx.Rollback()
  6375. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6376. return
  6377. }
  6378. } else {
  6379. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6380. if err != nil {
  6381. logs.Error(err)
  6382. tx.Rollback()
  6383. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6384. return
  6385. }
  6386. }
  6387. }
  6388. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6389. if err != nil {
  6390. logs.Error(err)
  6391. tx.Rollback()
  6392. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6393. return
  6394. }
  6395. } else {
  6396. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6397. if err != nil {
  6398. logs.Error(err)
  6399. tx.Rollback()
  6400. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6401. return
  6402. }
  6403. }
  6404. }
  6405. err := tx.Commit()
  6406. if err != nil {
  6407. logs.Error(err)
  6408. tx.Rollback()
  6409. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6410. return
  6411. }
  6412. appG.Response(http.StatusOK, e.SUCCESS, true)
  6413. }
  6414. func UpdateMaterialTMRDate(c *gin.Context) {
  6415. appG := app.Gin{C: c}
  6416. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6417. parammaps := gofasion.NewFasion(string(dataByte))
  6418. tmrid := parammaps.Get("tmrid").ValueStr()
  6419. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6420. lppid := parammaps.Get("lppid").ValueStr()
  6421. times := parammaps.Get("times").ValueStr()
  6422. pastureid := parammaps.Get("pastureid").ValueStr()
  6423. date := parammaps.Get("date").ValueStr()
  6424. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6425. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6426. tx := restful.Engine.NewSession()
  6427. defer tx.Close()
  6428. tx.Begin()
  6429. if tmrid != "1000" {
  6430. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6431. if err != nil {
  6432. logs.Error(err)
  6433. tx.Rollback()
  6434. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6435. return
  6436. }
  6437. var maxstirfeed float64
  6438. for _, tmr := range tmrList {
  6439. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6440. }
  6441. if status == 0 {
  6442. 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()
  6443. if err != nil {
  6444. logs.Error(err)
  6445. tx.Rollback()
  6446. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6447. return
  6448. }
  6449. var lweight float64
  6450. for _, item := range lpplandtl1List {
  6451. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6452. lweight += fl
  6453. }
  6454. if lweight > maxstirfeed {
  6455. lweight = lweight - maxstirfeed
  6456. } else {
  6457. lweight = 0
  6458. }
  6459. if lweight > 0 {
  6460. lweight1 := lweight / float64(len(lpplandtl1List))
  6461. number := 0
  6462. for _, item := range lpplandtl1List {
  6463. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6464. if lweight1 >= fl {
  6465. number++
  6466. }
  6467. }
  6468. lweight := lweight / float64((len(lpplandtl1List) - number))
  6469. for _, item := range lpplandtl1List {
  6470. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6471. if lweight1 >= fl {
  6472. continue
  6473. }
  6474. if tmrtype == "1" {
  6475. _, 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()
  6476. if err != nil {
  6477. logs.Error(err)
  6478. tx.Rollback()
  6479. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6480. return
  6481. }
  6482. } else if tmrtype == "2" {
  6483. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6484. if err != nil {
  6485. logs.Error(err)
  6486. tx.Rollback()
  6487. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6488. return
  6489. }
  6490. }
  6491. if item["fttype"].(int64) == 0 {
  6492. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6493. if err != nil {
  6494. logs.Error(err)
  6495. tx.Rollback()
  6496. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6497. return
  6498. }
  6499. } else {
  6500. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6501. if err != nil {
  6502. logs.Error(err)
  6503. tx.Rollback()
  6504. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6505. return
  6506. }
  6507. }
  6508. }
  6509. } else {
  6510. for _, item := range lpplandtl1List {
  6511. // 自走式
  6512. if tmrtype == "1" {
  6513. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6514. if err != nil {
  6515. logs.Error(err)
  6516. tx.Rollback()
  6517. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6518. return
  6519. }
  6520. } else if tmrtype == "2" {
  6521. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6522. if err != nil {
  6523. logs.Error(err)
  6524. tx.Rollback()
  6525. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6526. return
  6527. }
  6528. }
  6529. }
  6530. }
  6531. } else if status == 1 {
  6532. 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()
  6533. if err != nil {
  6534. logs.Error(err)
  6535. tx.Rollback()
  6536. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6537. return
  6538. }
  6539. var lweight float64
  6540. for _, item := range lpplandtl1List {
  6541. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6542. lweight += fl
  6543. }
  6544. if lweight > maxstirfeed {
  6545. lweight = lweight - maxstirfeed
  6546. } else {
  6547. lweight = 0
  6548. }
  6549. for _, item := range lpplandtl1List {
  6550. if lweight > 0 {
  6551. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6552. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6553. if fl >= lweight {
  6554. item["lweight"] = fl - lweight
  6555. lweight = 0
  6556. if tmrtype == "1" {
  6557. _, 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()
  6558. if err != nil {
  6559. logs.Error(err)
  6560. tx.Rollback()
  6561. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6562. return
  6563. }
  6564. } else if tmrtype == "2" {
  6565. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6566. if err != nil {
  6567. logs.Error(err)
  6568. tx.Rollback()
  6569. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6570. return
  6571. }
  6572. }
  6573. if item["fttype"].(int64) == 0 {
  6574. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6575. if err != nil {
  6576. logs.Error(err)
  6577. tx.Rollback()
  6578. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6579. return
  6580. }
  6581. } else {
  6582. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], 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. }
  6590. } else {
  6591. lweight = lweight - fl
  6592. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6593. if err != nil {
  6594. logs.Error(err)
  6595. tx.Rollback()
  6596. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6597. return
  6598. }
  6599. if item["fttype"].(int64) == 0 {
  6600. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6601. if err != nil {
  6602. logs.Error(err)
  6603. tx.Rollback()
  6604. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6605. return
  6606. }
  6607. } else {
  6608. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6609. if err != nil {
  6610. logs.Error(err)
  6611. tx.Rollback()
  6612. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6613. return
  6614. }
  6615. }
  6616. }
  6617. } else {
  6618. // 自走式
  6619. if tmrtype == "1" {
  6620. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6621. if err != nil {
  6622. logs.Error(err)
  6623. tx.Rollback()
  6624. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6625. return
  6626. }
  6627. } else if tmrtype == "2" {
  6628. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6629. if err != nil {
  6630. logs.Error(err)
  6631. tx.Rollback()
  6632. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6633. return
  6634. }
  6635. }
  6636. }
  6637. }
  6638. } else {
  6639. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6640. if err != nil {
  6641. logs.Error(err)
  6642. tx.Rollback()
  6643. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6644. return
  6645. }
  6646. for _, item := range lpplandtl1List {
  6647. if item["fttype"].(int64) == 0 {
  6648. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6649. if err != nil {
  6650. logs.Error(err)
  6651. tx.Rollback()
  6652. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6653. return
  6654. }
  6655. } else {
  6656. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6657. if err != nil {
  6658. logs.Error(err)
  6659. tx.Rollback()
  6660. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6661. return
  6662. }
  6663. }
  6664. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6665. if err != nil {
  6666. logs.Error(err)
  6667. tx.Rollback()
  6668. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6669. return
  6670. }
  6671. }
  6672. }
  6673. _, 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()
  6674. if err != nil {
  6675. logs.Error(err)
  6676. tx.Rollback()
  6677. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6678. return
  6679. }
  6680. } else {
  6681. if status == 2 {
  6682. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  6683. if err != nil {
  6684. logs.Error(err)
  6685. tx.Rollback()
  6686. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6687. return
  6688. }
  6689. for _, item := range lpplandtl1List {
  6690. if item["fttype"].(int64) == 0 {
  6691. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6692. if err != nil {
  6693. logs.Error(err)
  6694. tx.Rollback()
  6695. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6696. return
  6697. }
  6698. } else {
  6699. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6700. if err != nil {
  6701. logs.Error(err)
  6702. tx.Rollback()
  6703. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6704. return
  6705. }
  6706. }
  6707. }
  6708. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  6709. if err != nil {
  6710. logs.Error(err)
  6711. tx.Rollback()
  6712. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6713. return
  6714. }
  6715. } else {
  6716. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  6717. if err != nil {
  6718. logs.Error(err)
  6719. tx.Rollback()
  6720. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6721. return
  6722. }
  6723. }
  6724. }
  6725. err := tx.Commit()
  6726. if err != nil {
  6727. logs.Error(err)
  6728. tx.Rollback()
  6729. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6730. return
  6731. }
  6732. appG.Response(http.StatusOK, e.SUCCESS, true)
  6733. }
  6734. func Decimal(value float64) float64 {
  6735. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  6736. return value
  6737. }
  6738. func UpdateDailyData(c *gin.Context) {
  6739. appG := app.Gin{C: c}
  6740. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6741. parammaps := gofasion.NewFasion(string(dataByte))
  6742. pid := parammaps.Get("pid").ValueDefaultStr("0")
  6743. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  6744. sort := parammaps.Get("sort").ValueDefaultStr("0")
  6745. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  6746. date := parammaps.Get("date").ValueStr()
  6747. tx := restful.Engine.NewSession()
  6748. defer tx.Close()
  6749. 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()
  6750. if err != nil {
  6751. logs.Error("UpdateDailyData-error-0:", err)
  6752. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  6753. return
  6754. }
  6755. if count > 0 {
  6756. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  6757. return
  6758. }
  6759. tx.Begin()
  6760. if location == 0 {
  6761. fid := parammaps.Get("fid").ValueStr()
  6762. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  6763. if err != nil {
  6764. logs.Error("UpdateDailyData-error-1:", err)
  6765. tx.Rollback()
  6766. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6767. return
  6768. }
  6769. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6770. if err != nil {
  6771. logs.Error("UpdateDailyData-error-1:", err)
  6772. tx.Rollback()
  6773. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6774. return
  6775. }
  6776. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  6777. if err != nil {
  6778. fmt.Println("Error:", err)
  6779. return
  6780. }
  6781. actualWeight := weight - num
  6782. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  6783. if err != nil {
  6784. logs.Error("UpdateDailyData-error-2:", err)
  6785. tx.Rollback()
  6786. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6787. return
  6788. }
  6789. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  6790. if err != nil {
  6791. logs.Error("UpdateDailyData-error-3:", err)
  6792. tx.Rollback()
  6793. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6794. return
  6795. }
  6796. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6797. if err != nil {
  6798. logs.Error("UpdateDailyData-error-4:", err)
  6799. tx.Rollback()
  6800. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6801. return
  6802. }
  6803. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6804. if err != nil {
  6805. logs.Error("UpdateDailyData-error-5:", err)
  6806. tx.Rollback()
  6807. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6808. return
  6809. }
  6810. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6811. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6812. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6813. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6814. if err != nil {
  6815. fmt.Println("Error:", err)
  6816. return
  6817. }
  6818. // actual := actualWeight / float64(len(downloadedplanList))
  6819. for _, item := range downloadedplanList {
  6820. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6821. if err != nil {
  6822. fmt.Println("Error:", err)
  6823. return
  6824. }
  6825. actual := itemLweight / lweight * actualWeight
  6826. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6827. if err != nil {
  6828. logs.Error("UpdateDailyData-error-6:", err)
  6829. tx.Rollback()
  6830. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6831. return
  6832. }
  6833. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6834. if err != nil {
  6835. logs.Error("UpdateDailyData-error-7:", err)
  6836. tx.Rollback()
  6837. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6838. return
  6839. }
  6840. _, 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()
  6841. if err != nil {
  6842. logs.Error("UpdateDailyData-error-8:", err)
  6843. tx.Rollback()
  6844. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6845. return
  6846. }
  6847. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6848. if err != nil {
  6849. logs.Error("UpdateDailyData-error-9:", err)
  6850. tx.Rollback()
  6851. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6852. return
  6853. }
  6854. }
  6855. } else {
  6856. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6857. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6858. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6859. // if err != nil {
  6860. // fmt.Println("Error:", err)
  6861. // return
  6862. // }
  6863. for _, item := range downloadedplanList {
  6864. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6865. if err != nil {
  6866. logs.Error("UpdateDailyData-error-6:", err)
  6867. tx.Rollback()
  6868. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6869. return
  6870. }
  6871. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6872. item["lweight"], actualWeight, item["id"]).Execute()
  6873. if err != nil {
  6874. logs.Error("UpdateDailyData-error-7:", err)
  6875. tx.Rollback()
  6876. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6877. return
  6878. }
  6879. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6880. where pid = ?`, item["id"]).Execute()
  6881. if err != nil {
  6882. logs.Error("UpdateDailyData-error-8:", err)
  6883. tx.Rollback()
  6884. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6885. return
  6886. }
  6887. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6888. if err != nil {
  6889. logs.Error("UpdateDailyData-error-9:", err)
  6890. tx.Rollback()
  6891. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6892. return
  6893. }
  6894. }
  6895. }
  6896. } else {
  6897. fbarid := parammaps.Get("fbarid").ValueStr()
  6898. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  6899. if err != nil {
  6900. logs.Error("UpdateDailyData-error-10:", err)
  6901. tx.Rollback()
  6902. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6903. return
  6904. }
  6905. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6906. if err != nil {
  6907. logs.Error("UpdateDailyData-error-1:", err)
  6908. tx.Rollback()
  6909. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6910. return
  6911. }
  6912. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  6913. if err != nil {
  6914. fmt.Println("Error:", err)
  6915. return
  6916. }
  6917. actualWeight := weight - num
  6918. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  6919. if err != nil {
  6920. logs.Error("UpdateDailyData-error-11:", err)
  6921. tx.Rollback()
  6922. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6923. return
  6924. }
  6925. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  6926. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6927. if err != nil {
  6928. logs.Error("UpdateDailyData-error-12:", err)
  6929. tx.Rollback()
  6930. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6931. return
  6932. }
  6933. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6934. where pid = ? `, pid).Execute()
  6935. if err != nil {
  6936. logs.Error("UpdateDailyData-error-13:", err)
  6937. tx.Rollback()
  6938. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6939. return
  6940. }
  6941. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6942. if err != nil {
  6943. logs.Error("UpdateDailyData-error-14:", err)
  6944. tx.Rollback()
  6945. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6946. return
  6947. }
  6948. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6949. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6950. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6951. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6952. if err != nil {
  6953. fmt.Println("Error:", err)
  6954. return
  6955. }
  6956. for _, item := range downloadedplanList {
  6957. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6958. if err != nil {
  6959. fmt.Println("Error:", err)
  6960. return
  6961. }
  6962. actual := itemLweight / lweight * actualWeight
  6963. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6964. if err != nil {
  6965. logs.Error("UpdateDailyData-error-6:", err)
  6966. tx.Rollback()
  6967. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6968. return
  6969. }
  6970. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6971. if err != nil {
  6972. logs.Error("UpdateDailyData-error-7:", err)
  6973. tx.Rollback()
  6974. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6975. return
  6976. }
  6977. _, 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()
  6978. if err != nil {
  6979. logs.Error("UpdateDailyData-error-8:", err)
  6980. tx.Rollback()
  6981. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6982. return
  6983. }
  6984. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6985. if err != nil {
  6986. logs.Error("UpdateDailyData-error-9:", err)
  6987. tx.Rollback()
  6988. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6989. return
  6990. }
  6991. }
  6992. } else {
  6993. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6994. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6995. for _, item := range downloadedplanList {
  6996. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6997. // if err != nil {
  6998. // fmt.Println("Error:", err)
  6999. // return
  7000. // }
  7001. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7002. if err != nil {
  7003. logs.Error("UpdateDailyData-error-6:", err)
  7004. tx.Rollback()
  7005. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7006. return
  7007. }
  7008. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7009. item["lweight"], actualWeight, item["id"]).Execute()
  7010. if err != nil {
  7011. logs.Error("UpdateDailyData-error-7:", err)
  7012. tx.Rollback()
  7013. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7014. return
  7015. }
  7016. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7017. where pid = ?`, item["id"]).Execute()
  7018. if err != nil {
  7019. logs.Error("UpdateDailyData-error-8:", err)
  7020. tx.Rollback()
  7021. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7022. return
  7023. }
  7024. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7025. if err != nil {
  7026. logs.Error("UpdateDailyData-error-9:", err)
  7027. tx.Rollback()
  7028. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7029. return
  7030. }
  7031. }
  7032. }
  7033. }
  7034. err = tx.Commit()
  7035. if err != nil {
  7036. logs.Error("UpdateDailyData-error-20:", err)
  7037. tx.Rollback()
  7038. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7039. return
  7040. }
  7041. appG.Response(http.StatusOK, e.SUCCESS, true)
  7042. }
  7043. func GetFormulaStatistics(c *gin.Context) {
  7044. appG := app.Gin{C: c}
  7045. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7046. parammaps := gofasion.NewFasion(string(dataByte))
  7047. startTime := parammaps.Get("startTime").ValueStr()
  7048. endTime := parammaps.Get("endTime").ValueStr()
  7049. pastureId := parammaps.Get("pastureId").ValueStr()
  7050. tx := restful.Engine.NewSession()
  7051. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7052. if err != nil {
  7053. logs.Error("GetFormulaStatistics-error-1:", err)
  7054. tx.Rollback()
  7055. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7056. return
  7057. }
  7058. var feedtemplet, dateList []string
  7059. for _, f := range feedtempletList {
  7060. feedtemplet = append(feedtemplet, f["tname"].(string))
  7061. }
  7062. layout := "2006-01-02"
  7063. // s := "2023-05-01"
  7064. // e := "2023-05-23"
  7065. start, err := time.Parse(layout, startTime)
  7066. if err != nil {
  7067. fmt.Println(err)
  7068. return
  7069. }
  7070. end, err := time.Parse(layout, endTime)
  7071. if err != nil {
  7072. fmt.Println(err)
  7073. return
  7074. }
  7075. end = end.AddDate(0, 0, 1)
  7076. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7077. dateList = append(dateList, d.Format("2006-01-02"))
  7078. }
  7079. downloadedplanList, err := tx.SQL(`select count(1) total,ft.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7080. 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= ?
  7081. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7082. if err != nil {
  7083. logs.Error("GetFormulaStatistics-error-2:", err)
  7084. tx.Rollback()
  7085. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7086. return
  7087. }
  7088. var data2 [][]interface{}
  7089. for _, f := range feedtemplet {
  7090. var data1 []interface{}
  7091. for _, date := range dateList {
  7092. exist := false
  7093. for _, item := range downloadedplanList {
  7094. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7095. data1 = append(data1, item["total"])
  7096. exist = true
  7097. break
  7098. }
  7099. }
  7100. if !exist {
  7101. data1 = append(data1, 0)
  7102. }
  7103. }
  7104. data2 = append(data2, data1)
  7105. }
  7106. //前端让加的
  7107. feedtemplet = append(feedtemplet, "")
  7108. {
  7109. var data1 []interface{}
  7110. for _, f := range dateList {
  7111. // f = f + "\n"
  7112. fmt.Println(f)
  7113. data1 = append(data1, 0)
  7114. }
  7115. data2 = append(data2, data1)
  7116. }
  7117. resp := make(map[string]interface{}, 0)
  7118. resp["xdata"] = dateList
  7119. resp["data1"] = feedtemplet
  7120. resp["data2"] = data2
  7121. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7122. }
  7123. func GetPlanData(c *gin.Context) {
  7124. appG := app.Gin{C: c}
  7125. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7126. fsion := gofasion.NewFasion(string(dataByte))
  7127. sqlnamestr := fsion.Get("name").ValueStr()
  7128. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7129. offset := fsion.Get("offset").ValueDefaultInt(0)
  7130. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7131. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7132. month := fsion.Get("month").ValueDefaultStr("map")
  7133. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7134. tx := restful.Engine.NewSession()
  7135. err := tx.Begin()
  7136. defer func() {
  7137. switch {
  7138. case err != nil:
  7139. if tx != nil {
  7140. tx.Rollback()
  7141. }
  7142. default:
  7143. if tx != nil {
  7144. err = tx.Commit()
  7145. }
  7146. }
  7147. if tx != nil {
  7148. tx.Close()
  7149. }
  7150. }()
  7151. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7152. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7153. if sql != "" {
  7154. s_params := make([]interface{}, 0)
  7155. if fsion.HasKey("parammaps") {
  7156. parammaps := fsion.Get("parammaps")
  7157. paramslist := strings.Split(p, ",")
  7158. if len(paramslist) > 0 && p != "" {
  7159. for _, value := range paramslist {
  7160. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7161. if tempv, exists := c.Get("jwt_username"); exists {
  7162. s_params = append(s_params, tempv.(string))
  7163. } else {
  7164. s_params = append(s_params, "")
  7165. }
  7166. } else {
  7167. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7168. }
  7169. }
  7170. }
  7171. }
  7172. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7173. if err != nil {
  7174. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7175. } else {
  7176. paramslist1 := strings.Split(p1, ",")
  7177. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7178. s_params1 := make([]interface{}, 0)
  7179. if len(paramslist1) > 0 && p1 != "" {
  7180. for _, v := range paramslist1 {
  7181. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7182. }
  7183. }
  7184. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7185. for _, item := range arr {
  7186. trgaddressList := []string{}
  7187. if _, ok := item["trgaddress"]; ok {
  7188. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7189. for _, str := range trgaddressList1 {
  7190. if str != "" {
  7191. trgaddressList = append(trgaddressList, str)
  7192. }
  7193. }
  7194. }
  7195. item["trgaddressList"] = trgaddressList
  7196. }
  7197. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7198. }
  7199. // var wg sync.WaitGroup
  7200. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7201. // wg.Add(1)
  7202. // go func(value map[string]interface{}) {
  7203. // defer wg.Done()
  7204. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7205. // }(value)
  7206. // }
  7207. // wg.Wait()
  7208. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7209. }
  7210. } else {
  7211. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7212. }
  7213. }
  7214. func PostPlanData(c *gin.Context) {
  7215. appG := app.Gin{C: c}
  7216. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7217. fsion := gofasion.NewFasion(string(dataByte))
  7218. logging.Info("PostRJSBData err: ", string(dataByte))
  7219. s_params := make([]interface{}, 0)
  7220. tx := restful.Engine.NewSession()
  7221. err := tx.Begin()
  7222. defer func() {
  7223. switch {
  7224. case err != nil:
  7225. if tx != nil {
  7226. tx.Rollback()
  7227. }
  7228. default:
  7229. if tx != nil {
  7230. err = tx.Commit()
  7231. }
  7232. }
  7233. if tx != nil {
  7234. tx.Close()
  7235. }
  7236. }()
  7237. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7238. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7239. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7240. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7241. if !fsion.HasKey("parammaps") {
  7242. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7243. return
  7244. }
  7245. parammaps := fsion.Get("parammaps")
  7246. // paramslist := strings.Split(p, ",")
  7247. // if len(paramslist) > 0 && p != "" {
  7248. // for _, value := range paramslist {
  7249. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7250. // }
  7251. // }
  7252. // _, err = tx.SQL(sql, s_params...).Execute()
  7253. // if err != nil {
  7254. // logging.Error("PostRJSBData err: ", err)
  7255. // msg := geterrmsg(err.Error())
  7256. // appG.Response(http.StatusOK, e.ERROR, msg)
  7257. // return
  7258. // }
  7259. s_params = make([]interface{}, 0)
  7260. paramslist := strings.Split(p1, ",")
  7261. if len(paramslist) > 0 && p1 != "" {
  7262. for _, value := range paramslist {
  7263. // if value == "ID" {
  7264. // id := parammaps.Get("ID").ValueStr()
  7265. // pastureid := parammaps.Get("pastureid").ValueStr()
  7266. // 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
  7267. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7268. // if err != nil {
  7269. // logging.Error("PostRJSBData err: ", err)
  7270. // msg := geterrmsg(err.Error())
  7271. // appG.Response(http.StatusOK, e.ERROR, msg)
  7272. // return
  7273. // }
  7274. // for _, item := range datalist {
  7275. // id = item["id"]
  7276. // }
  7277. // s_params = append(s_params, id)
  7278. // } else {
  7279. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7280. // }
  7281. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7282. }
  7283. }
  7284. _, err = tx.SQL(sql1, s_params...).Execute()
  7285. if err != nil {
  7286. logging.Error("PostRJSBData1 err: ", err)
  7287. msg := geterrmsg(err.Error())
  7288. appG.Response(http.StatusOK, e.ERROR, msg)
  7289. return
  7290. }
  7291. s_params = make([]interface{}, 0)
  7292. paramslist = strings.Split(p2, ",")
  7293. if len(paramslist) > 0 && p2 != "" {
  7294. for _, value := range paramslist {
  7295. if value == "ID" {
  7296. id := parammaps.Get("ID").ValueStr()
  7297. pastureid := parammaps.Get("pastureid").ValueStr()
  7298. 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
  7299. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7300. if err != nil {
  7301. logging.Error("PostRJSBData err: ", err)
  7302. msg := geterrmsg(err.Error())
  7303. appG.Response(http.StatusOK, e.ERROR, msg)
  7304. return
  7305. }
  7306. for _, item := range datalist {
  7307. id = item["id"]
  7308. }
  7309. s_params = append(s_params, id)
  7310. } else {
  7311. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7312. }
  7313. }
  7314. }
  7315. _, err = tx.SQL(sql2, s_params...).Execute()
  7316. if err != nil {
  7317. logging.Error("PostRJSBData2 err: ", err)
  7318. msg := geterrmsg(err.Error())
  7319. appG.Response(http.StatusOK, e.ERROR, msg)
  7320. return
  7321. }
  7322. s_params = make([]interface{}, 0)
  7323. paramslist = strings.Split(p3, ",")
  7324. if len(paramslist) > 0 && p3 != "" {
  7325. for _, value := range paramslist {
  7326. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7327. }
  7328. }
  7329. _, err = tx.SQL(sql3, s_params...).Execute()
  7330. if err != nil {
  7331. logging.Error("PostRJSBData3 err: ", err)
  7332. msg := geterrmsg(err.Error())
  7333. appG.Response(http.StatusOK, e.ERROR, msg)
  7334. return
  7335. }
  7336. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7337. }
  7338. func CheckFeedTrgaddress(c *gin.Context) {
  7339. appG := app.Gin{C: c}
  7340. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7341. fsion := gofasion.NewFasion(string(dataByte))
  7342. fclassid := fsion.Get("fclassid").ValueStr()
  7343. feedId := fsion.Get("feedId").ValueStr()
  7344. backup1 := fsion.Get("backup1").ValueStr()
  7345. backup1List := strings.Split(backup1, ",")
  7346. tx := restful.Engine.NewSession()
  7347. defer tx.Close()
  7348. // if backup1 != "" {
  7349. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7350. for _, feed := range feedList {
  7351. if feed["backup1"] == "" {
  7352. continue
  7353. }
  7354. feedbackupList := strings.Split(feed["backup1"], ",")
  7355. for _, feedbackup := range feedbackupList {
  7356. for _, backup := range backup1List {
  7357. if feedbackup == backup {
  7358. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7359. return
  7360. }
  7361. }
  7362. }
  7363. }
  7364. // }
  7365. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7366. }
  7367. func ThiGetDataByName(c *gin.Context) {
  7368. appG := app.Gin{C: c}
  7369. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7370. fsion := gofasion.NewFasion(string(dataByte))
  7371. sqlnamestr := fsion.Get("name").ValueStr()
  7372. offset := fsion.Get("offset").ValueDefaultInt(0)
  7373. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7374. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7375. tx := restful.Engine.NewSession()
  7376. err := tx.Begin()
  7377. defer func() {
  7378. switch {
  7379. case err != nil:
  7380. logging.Error("tx.Begin 事务启动失败__error:", err)
  7381. if tx != nil {
  7382. tx.Rollback()
  7383. }
  7384. default:
  7385. if tx != nil {
  7386. err = tx.Commit()
  7387. }
  7388. }
  7389. if tx != nil {
  7390. tx.Close()
  7391. }
  7392. }()
  7393. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7394. if sql != "" {
  7395. s_params := make([]interface{}, 0)
  7396. if fsion.HasKey("parammaps") {
  7397. parammaps := fsion.Get("parammaps")
  7398. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7399. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7400. }
  7401. paramslist := strings.Split(p, ",")
  7402. if len(paramslist) > 0 && p != "" {
  7403. for _, value := range paramslist {
  7404. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7405. if tempv, exists := c.Get("jwt_username"); exists {
  7406. s_params = append(s_params, tempv.(string))
  7407. } else {
  7408. s_params = append(s_params, "")
  7409. }
  7410. } else {
  7411. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7412. }
  7413. }
  7414. }
  7415. } else if fsion.HasKey("params") {
  7416. params := fsion.Get("params").Array()
  7417. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7418. for _, v_params := range params {
  7419. s_params = append(s_params, v_params.ValueStr())
  7420. }
  7421. }
  7422. if returntype == "xlsx" {
  7423. var xlsxfile *xlsx.File
  7424. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7425. //c.File("c:/dd.xlsx")
  7426. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7427. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7428. c.Header("Content-Transfer-Encoding", "binary")
  7429. _ = xlsxfile.Write(c.Writer)
  7430. } else {
  7431. if sqlnamestr == "getHomepageStr" {
  7432. parammaps := fsion.Get("parammaps")
  7433. pastureid := parammaps.Get("pastureid").ValueStr()
  7434. var montimeList []float64
  7435. var montime float64
  7436. var wg sync.WaitGroup
  7437. now := time.Now()
  7438. for i := 0; i < 30; i++ {
  7439. wg.Add(1)
  7440. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7441. go func(nowstr string) {
  7442. defer wg.Done()
  7443. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7444. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7445. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7446. montimeList = append(montimeList, m)
  7447. }(nowstr)
  7448. }
  7449. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7450. if err != nil {
  7451. logging.Error("GetDataByName err: ", err)
  7452. msg := geterrmsg(err.Error())
  7453. appG.Response(http.StatusOK, e.ERROR, msg)
  7454. }
  7455. wg.Wait()
  7456. for _, m := range montimeList {
  7457. montime += m
  7458. }
  7459. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7460. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7461. return
  7462. }
  7463. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7464. if err != nil {
  7465. logging.Error("GetDataByName err: ", err)
  7466. msg := geterrmsg(err.Error())
  7467. appG.Response(http.StatusOK, e.ERROR, msg)
  7468. } else {
  7469. if sqlnamestr == "getFeedTrgaddressList" {
  7470. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7471. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7472. trgaddressList := []string{}
  7473. for _, str := range trgaddressList1 {
  7474. if str != "" {
  7475. trgaddressList = append(trgaddressList, str)
  7476. }
  7477. }
  7478. item["trgaddressList"] = trgaddressList
  7479. }
  7480. }
  7481. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7482. }
  7483. }
  7484. } else {
  7485. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7486. }
  7487. }
  7488. // func ToggleCcount(c *gin.Context) {
  7489. // appG := app.Gin{C: c}
  7490. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7491. // fsion := gofasion.NewFasion(string(dataByte))
  7492. // // 0 实际 1 软件
  7493. // status := fsion.Get("status").ValueDefaultInt64(0)
  7494. // pastureId := fsion.Get("pastureId").ValueStr()
  7495. // tx := restful.Engine.NewSession()
  7496. // err := tx.Begin()
  7497. // defer func() {
  7498. // switch {
  7499. // case err != nil:
  7500. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7501. // if tx != nil {
  7502. // tx.Rollback()
  7503. // }
  7504. // default:
  7505. // if tx != nil {
  7506. // err = tx.Commit()
  7507. // }
  7508. // }
  7509. // if tx != nil {
  7510. // tx.Close()
  7511. // }
  7512. // }()
  7513. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7514. // if err != nil {
  7515. // logs.Error(err)
  7516. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7517. // return
  7518. // }
  7519. // for _, bar := range barList {
  7520. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7521. // if err != nil {
  7522. // logs.Error(err)
  7523. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7524. // return
  7525. // }
  7526. // if !exist {
  7527. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7528. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7529. // if err != nil {
  7530. // logs.Error(err)
  7531. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7532. // return
  7533. // }
  7534. // }
  7535. // }
  7536. // if status == 0 {
  7537. // tx.Exec(`update feedp set ccount = actualcount `)
  7538. // }else{
  7539. // tx.Exec(`update feedp set ccount = softccount `)
  7540. // }
  7541. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7542. // if err != nil {
  7543. // logs.Error(err)
  7544. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7545. // return
  7546. // }
  7547. // for _, feedpData :=range feedpList{
  7548. // var feedpargs []interface{}
  7549. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7550. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7551. // if _, ok := feedpData["ftname"]; ok {
  7552. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7553. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7554. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7555. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7556. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7557. // } else {
  7558. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7559. // }
  7560. // if _, ok := feedpData["ptsfname"]; ok {
  7561. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7562. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7563. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7564. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7565. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7566. // } else {
  7567. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7568. // }
  7569. // upFeedpSql += " where barname = ? and pastureid = ? "
  7570. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7571. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7572. // if err != nil {
  7573. // logs.Error(err)
  7574. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7575. // return
  7576. // }
  7577. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7578. // if err != nil {
  7579. // logs.Error(err)
  7580. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7581. // return
  7582. // }
  7583. // if !exist1 {
  7584. // _, 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) `,
  7585. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7586. // if err != nil {
  7587. // logs.Error(err)
  7588. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7589. // return
  7590. // }
  7591. // }
  7592. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7593. // if err != nil {
  7594. // logs.Error(err)
  7595. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7596. // return
  7597. // }
  7598. // if !exist2 {
  7599. // _, 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) `,
  7600. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7601. // if err != nil {
  7602. // logs.Error(err)
  7603. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7604. // return
  7605. // }
  7606. // }
  7607. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7608. // if err != nil {
  7609. // logs.Error(err)
  7610. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7611. // return
  7612. // }
  7613. // if !exist3 {
  7614. // _, 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) `,
  7615. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7616. // if err != nil {
  7617. // logs.Error(err)
  7618. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7619. // return
  7620. // }
  7621. // }
  7622. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7623. // if err != nil {
  7624. // logs.Error(err)
  7625. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7626. // return
  7627. // }
  7628. // if !exist4 {
  7629. // _, 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) `,
  7630. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7631. // if err != nil {
  7632. // logs.Error(err)
  7633. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7634. // return
  7635. // }
  7636. // }
  7637. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7638. // if err != nil {
  7639. // logs.Error(err)
  7640. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7641. // return
  7642. // }
  7643. // if !exist5 {
  7644. // _, 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) `,
  7645. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7646. // if err != nil {
  7647. // logs.Error(err)
  7648. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7649. // return
  7650. // }
  7651. // }
  7652. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7653. // if err != nil {
  7654. // logs.Error(err)
  7655. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7656. // return
  7657. // }
  7658. // if !exist6 {
  7659. // _, 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) `,
  7660. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7661. // if err != nil {
  7662. // logs.Error(err)
  7663. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7664. // return
  7665. // }
  7666. // }
  7667. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7668. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7669. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7670. // and pastureid = ? and times = ?`
  7671. // var fpdargs1 []interface{}
  7672. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7673. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7674. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7675. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7676. // if err != nil {
  7677. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7678. // return
  7679. // }
  7680. // var fpdargs2 []interface{}
  7681. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7682. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7683. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7684. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7685. // if err != nil {
  7686. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7687. // return
  7688. // }
  7689. // var fpdargs3 []interface{}
  7690. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7691. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7692. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7693. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7694. // if err != nil {
  7695. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7696. // return
  7697. // }
  7698. // var fpdargs4 []interface{}
  7699. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7700. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7701. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7702. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7703. // if err != nil {
  7704. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7705. // return
  7706. // }
  7707. // var fpdargs5 []interface{}
  7708. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7709. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7710. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7711. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7712. // if err != nil {
  7713. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7714. // return
  7715. // }
  7716. // var fpdargs6 []interface{}
  7717. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7718. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7719. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7720. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7721. // if err != nil {
  7722. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7723. // return
  7724. // }
  7725. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7726. // 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()
  7727. // if err != nil {
  7728. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7729. // return
  7730. // }
  7731. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7732. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7733. // upFpdetailList := make([]*upFpdetail, 0)
  7734. // for _, newfpd := range newList {
  7735. // for _, oldfpd := range oldFpdList {
  7736. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7737. // var oldweight, newweight float64
  7738. // if oldfpd["weight"] != nil {
  7739. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7740. // }
  7741. // if newfpd["weight"] != nil {
  7742. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7743. // }
  7744. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7745. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  7746. // Old: oldweight,
  7747. // New: newweight,
  7748. // Times: newfpd["times"].(int64),
  7749. // Ptid: newfpd["ptid"].(int64),
  7750. // Fweight: fweight,
  7751. // Id: oldfpd["id"].(int64),
  7752. // })
  7753. // break
  7754. // }
  7755. // }
  7756. // }
  7757. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  7758. // }
  7759. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  7760. // }
  7761. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  7762. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  7763. if err != nil {
  7764. return err
  7765. }
  7766. for _, item := range feedpList {
  7767. // if item["ftid"].(string) != data["ftid"].(string) {
  7768. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  7769. if err != nil {
  7770. return err
  7771. }
  7772. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  7773. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  7774. if err != nil {
  7775. return err
  7776. }
  7777. // }
  7778. }
  7779. return nil
  7780. }
  7781. func PostPlanDatas(c *gin.Context) {
  7782. appG := app.Gin{C: c}
  7783. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7784. fsions := gofasion.NewFasion(string(dataByte))
  7785. logging.Info("PostRJSBDatas err: ", string(dataByte))
  7786. tx := restful.Engine.NewSession()
  7787. err := tx.Begin()
  7788. defer func() {
  7789. switch {
  7790. case err != nil:
  7791. if tx != nil {
  7792. tx.Rollback()
  7793. }
  7794. default:
  7795. if tx != nil {
  7796. err = tx.Commit()
  7797. }
  7798. }
  7799. if tx != nil {
  7800. tx.Close()
  7801. }
  7802. }()
  7803. pastureId := fsions.Get("pastureid").ValueStr()
  7804. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7805. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  7806. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  7807. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  7808. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7809. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7810. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7811. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7812. for _, parammaps := range fsions.Get("arrList").Array() {
  7813. fmt.Println(parammaps.Json())
  7814. if parammaps.Json() == "null" {
  7815. continue
  7816. }
  7817. // if !fsion.HasKey("arrList") {
  7818. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7819. // return
  7820. // continue
  7821. // }
  7822. // parammaps := fsion.Get("arrList")
  7823. s_params := make([]interface{}, 0)
  7824. // paramslist := strings.Split(p, ",")
  7825. // if len(paramslist) > 0 && p != "" {
  7826. // for _, value := range paramslist {
  7827. // if value == "pastureid" {
  7828. // s_params = append(s_params, pastureId)
  7829. // } else {
  7830. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7831. // }
  7832. // }
  7833. // }
  7834. // _, err = tx.SQL(sql, s_params...).Execute()
  7835. // if err != nil {
  7836. // logging.Error("PostRJSBData err: ", err)
  7837. // msg := geterrmsg(err.Error())
  7838. // appG.Response(http.StatusOK, e.ERROR, msg)
  7839. // return
  7840. // }
  7841. s_params = make([]interface{}, 0)
  7842. paramslist := strings.Split(p1, ",")
  7843. if len(paramslist) > 0 && p1 != "" {
  7844. for _, value := range paramslist {
  7845. // if value == "ID" {
  7846. // id := parammaps.Get("ID").ValueStr()
  7847. // pastureid := parammaps.Get("pastureid").ValueStr()
  7848. // 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
  7849. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7850. // if err != nil {
  7851. // logging.Error("PostRJSBData err: ", err)
  7852. // msg := geterrmsg(err.Error())
  7853. // appG.Response(http.StatusOK, e.ERROR, msg)
  7854. // return
  7855. // }
  7856. // for _, item := range datalist {
  7857. // id = item["id"]
  7858. // }
  7859. // s_params = append(s_params, id)
  7860. // } else {
  7861. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7862. // }
  7863. if value == "pastureid" {
  7864. s_params = append(s_params, pastureId)
  7865. } else {
  7866. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7867. }
  7868. }
  7869. }
  7870. _, err = tx.SQL(sql1, s_params...).Execute()
  7871. if err != nil {
  7872. logging.Error("PostRJSBData1 err: ", err)
  7873. msg := geterrmsg(err.Error())
  7874. appG.Response(http.StatusOK, e.ERROR, msg)
  7875. return
  7876. }
  7877. s_params = make([]interface{}, 0)
  7878. paramslist = strings.Split(p2, ",")
  7879. if len(paramslist) > 0 && p2 != "" {
  7880. for _, value := range paramslist {
  7881. if value == "ID" {
  7882. id := parammaps.Get("ID").ValueStr()
  7883. pastureid := parammaps.Get("pastureid").ValueStr()
  7884. 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
  7885. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7886. if err != nil {
  7887. logging.Error("PostRJSBData err: ", err)
  7888. msg := geterrmsg(err.Error())
  7889. appG.Response(http.StatusOK, e.ERROR, msg)
  7890. return
  7891. }
  7892. for _, item := range datalist {
  7893. id = item["id"]
  7894. }
  7895. s_params = append(s_params, id)
  7896. } else if value == "pastureid" {
  7897. s_params = append(s_params, pastureId)
  7898. } else {
  7899. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7900. }
  7901. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7902. }
  7903. }
  7904. _, err = tx.SQL(sql2, s_params...).Execute()
  7905. if err != nil {
  7906. logging.Error("PostRJSBData2 err: ", err)
  7907. msg := geterrmsg(err.Error())
  7908. appG.Response(http.StatusOK, e.ERROR, msg)
  7909. return
  7910. }
  7911. s_params = make([]interface{}, 0)
  7912. paramslist = strings.Split(p3, ",")
  7913. if len(paramslist) > 0 && p3 != "" {
  7914. for _, value := range paramslist {
  7915. if value == "pastureid" {
  7916. s_params = append(s_params, pastureId)
  7917. } else {
  7918. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7919. }
  7920. }
  7921. }
  7922. _, err = tx.SQL(sql3, s_params...).Execute()
  7923. if err != nil {
  7924. logging.Error("PostRJSBData3 err: ", err)
  7925. msg := geterrmsg(err.Error())
  7926. appG.Response(http.StatusOK, e.ERROR, msg)
  7927. return
  7928. }
  7929. }
  7930. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7931. }
  7932. func FpdBatchEdit(c *gin.Context) {
  7933. appG := app.Gin{C: c}
  7934. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7935. fsions := gofasion.NewFasion(string(dataByte))
  7936. barList := fsions.Get("barList").Array()
  7937. pastureid := fsions.Get("pastureId").ValueStr()
  7938. tx := restful.Engine.NewSession()
  7939. defer tx.Close()
  7940. 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
  7941. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7942. if err != nil {
  7943. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7944. return
  7945. }
  7946. for _, barFsions := range barList {
  7947. dataexcel := make(map[string]interface{}, 0)
  7948. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  7949. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  7950. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  7951. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  7952. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  7953. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  7954. continue
  7955. }
  7956. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  7957. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  7958. if err != nil {
  7959. logs.Error(err)
  7960. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7961. return
  7962. }
  7963. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  7964. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  7965. if err != nil {
  7966. logs.Error(err)
  7967. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7968. return
  7969. }
  7970. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  7971. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  7972. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  7973. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  7974. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  7975. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  7976. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  7977. if err != nil {
  7978. logs.Error(err)
  7979. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7980. return
  7981. }
  7982. if !ftexist {
  7983. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  7984. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7985. if err != nil {
  7986. logs.Error(err)
  7987. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7988. return
  7989. }
  7990. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7991. if err != nil {
  7992. logs.Error(err)
  7993. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7994. return
  7995. }
  7996. }
  7997. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  7998. if err != nil {
  7999. logs.Error(err)
  8000. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8001. return
  8002. }
  8003. if !exist {
  8004. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8005. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8006. if err != nil {
  8007. logs.Error(err)
  8008. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8009. return
  8010. }
  8011. }
  8012. var feedpargs []interface{}
  8013. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8014. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8015. if _, ok := dataexcel["ftname"]; ok {
  8016. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8017. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8018. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8019. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8020. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8021. } else {
  8022. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8023. }
  8024. if _, ok := dataexcel["ptsfname"]; ok {
  8025. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8026. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8027. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8028. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8029. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8030. } else {
  8031. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8032. }
  8033. upFeedpSql += " where barname = ? and pastureid = ? "
  8034. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8035. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8036. if err != nil {
  8037. logs.Error(err)
  8038. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8039. return
  8040. }
  8041. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8042. if err != nil {
  8043. logs.Error(err)
  8044. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8045. return
  8046. }
  8047. if !exist1 {
  8048. _, 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) `,
  8049. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8050. if err != nil {
  8051. logs.Error(err)
  8052. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8053. return
  8054. }
  8055. }
  8056. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8057. if err != nil {
  8058. logs.Error(err)
  8059. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8060. return
  8061. }
  8062. if !exist2 {
  8063. _, 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) `,
  8064. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8065. if err != nil {
  8066. logs.Error(err)
  8067. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8068. return
  8069. }
  8070. }
  8071. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8072. if err != nil {
  8073. logs.Error(err)
  8074. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8075. return
  8076. }
  8077. if !exist3 {
  8078. _, 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) `,
  8079. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8080. if err != nil {
  8081. logs.Error(err)
  8082. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8083. return
  8084. }
  8085. }
  8086. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8087. if err != nil {
  8088. logs.Error(err)
  8089. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8090. return
  8091. }
  8092. if !exist4 {
  8093. _, 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) `,
  8094. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8095. if err != nil {
  8096. logs.Error(err)
  8097. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8098. return
  8099. }
  8100. }
  8101. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8102. if err != nil {
  8103. logs.Error(err)
  8104. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8105. return
  8106. }
  8107. if !exist5 {
  8108. _, 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) `,
  8109. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8110. if err != nil {
  8111. logs.Error(err)
  8112. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8113. return
  8114. }
  8115. }
  8116. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8117. if err != nil {
  8118. logs.Error(err)
  8119. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8120. return
  8121. }
  8122. if !exist6 {
  8123. _, 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) `,
  8124. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8125. if err != nil {
  8126. logs.Error(err)
  8127. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8128. return
  8129. }
  8130. }
  8131. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8132. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8133. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8134. and pastureid = ? and times = ?`
  8135. var fpdargs1 []interface{}
  8136. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8137. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8138. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8139. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8140. if err != nil {
  8141. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8142. return
  8143. }
  8144. var fpdargs2 []interface{}
  8145. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8146. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8147. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8148. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8149. if err != nil {
  8150. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8151. return
  8152. }
  8153. var fpdargs3 []interface{}
  8154. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8155. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8156. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8157. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8158. if err != nil {
  8159. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8160. return
  8161. }
  8162. var fpdargs4 []interface{}
  8163. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8164. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8165. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8166. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8167. if err != nil {
  8168. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8169. return
  8170. }
  8171. var fpdargs5 []interface{}
  8172. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8173. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8174. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8175. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8176. if err != nil {
  8177. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8178. return
  8179. }
  8180. var fpdargs6 []interface{}
  8181. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8182. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8183. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8184. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8185. if err != nil {
  8186. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8187. return
  8188. }
  8189. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8190. 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()
  8191. if err != nil {
  8192. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8193. return
  8194. }
  8195. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8196. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8197. upFpdetailList := make([]*upFpdetail, 0)
  8198. for _, newfpd := range newList {
  8199. for _, oldfpd := range oldFpdList {
  8200. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8201. var oldweight, newweight float64
  8202. if oldfpd["weight"] != nil {
  8203. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8204. }
  8205. if newfpd["weight"] != nil {
  8206. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8207. }
  8208. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8209. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8210. Old: oldweight,
  8211. New: newweight,
  8212. Times: newfpd["times"].(int64),
  8213. Ptid: newfpd["ptid"].(int64),
  8214. Fweight: fweight,
  8215. Id: oldfpd["id"].(int64),
  8216. })
  8217. break
  8218. }
  8219. }
  8220. }
  8221. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8222. }
  8223. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8224. }
  8225. func UdBarSync(c *gin.Context) {
  8226. appG := app.Gin{C: c}
  8227. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8228. fsions := gofasion.NewFasion(string(dataByte))
  8229. pastureid := fsions.Get("pastureId").ValueStr()
  8230. tx := restful.Engine.NewSession()
  8231. defer tx.Close()
  8232. pastureinfo := new(udPastureInfo)
  8233. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8234. if err != nil {
  8235. logs.Error(err)
  8236. return
  8237. }
  8238. gm.UdBarSync(pastureid, pastureinfo.Werks)
  8239. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8240. }
  8241. func UdFeedSync(c *gin.Context) {
  8242. appG := app.Gin{C: c}
  8243. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8244. fsions := gofasion.NewFasion(string(dataByte))
  8245. pastureid := fsions.Get("pastureId").ValueStr()
  8246. tx := restful.Engine.NewSession()
  8247. defer tx.Close()
  8248. pastureinfo := new(udPastureInfo)
  8249. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8250. if err != nil {
  8251. logs.Error(err)
  8252. return
  8253. }
  8254. gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8255. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8256. }
  8257. func UdFeedtempletPush(c *gin.Context) {
  8258. appG := app.Gin{C: c}
  8259. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8260. fsions := gofasion.NewFasion(string(dataByte))
  8261. pastureid := fsions.Get("pastureId").ValueStr()
  8262. date := fsions.Get("date").ValueStr()
  8263. tx := restful.Engine.NewSession()
  8264. defer tx.Close()
  8265. pastureinfo := new(udPastureInfo)
  8266. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8267. if err != nil {
  8268. logs.Error(err)
  8269. return
  8270. }
  8271. gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8272. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8273. }
  8274. func UdUtirPush(c *gin.Context) {
  8275. appG := app.Gin{C: c}
  8276. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8277. fsions := gofasion.NewFasion(string(dataByte))
  8278. pastureid := fsions.Get("pastureId").ValueStr()
  8279. date := fsions.Get("date").ValueStr()
  8280. tx := restful.Engine.NewSession()
  8281. defer tx.Close()
  8282. pastureinfo := new(udPastureInfo)
  8283. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8284. if err != nil {
  8285. logs.Error(err)
  8286. return
  8287. }
  8288. gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8289. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8290. }
  8291. func UdBarFeedRemainPush(c *gin.Context) {
  8292. appG := app.Gin{C: c}
  8293. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8294. fsions := gofasion.NewFasion(string(dataByte))
  8295. pastureid := fsions.Get("pastureId").ValueStr()
  8296. date := fsions.Get("date").ValueStr()
  8297. tx := restful.Engine.NewSession()
  8298. defer tx.Close()
  8299. pastureinfo := new(udPastureInfo)
  8300. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8301. if err != nil {
  8302. logs.Error(err)
  8303. return
  8304. }
  8305. gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8306. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8307. }
  8308. func UdMaterialIssuePush(c *gin.Context) {
  8309. appG := app.Gin{C: c}
  8310. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8311. fsions := gofasion.NewFasion(string(dataByte))
  8312. pastureid := fsions.Get("pastureId").ValueStr()
  8313. date := fsions.Get("date").ValueStr()
  8314. tx := restful.Engine.NewSession()
  8315. defer tx.Close()
  8316. pastureinfo := new(udPastureInfo)
  8317. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8318. if err != nil {
  8319. logs.Error(err)
  8320. return
  8321. }
  8322. gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8323. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8324. }
  8325. func DelFeedTemplet(c *gin.Context) {
  8326. appG := app.Gin{C: c}
  8327. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8328. fsions := gofasion.NewFasion(string(dataByte))
  8329. ftId := fsions.Get("ftId").ValueStr()
  8330. // userId := fsions.Get("userId").ValueStr()
  8331. tx := restful.Engine.NewSession()
  8332. defer tx.Close()
  8333. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8334. if err != nil {
  8335. logs.Error(err)
  8336. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8337. return
  8338. }
  8339. // barIdList, err := tx.SQL(`select barid from feedp where ftid = ? `, ftId).QueryString()
  8340. // if err != nil {
  8341. // logs.Error(err)
  8342. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8343. // return
  8344. // }
  8345. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8346. if err != nil {
  8347. logs.Error(err)
  8348. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8349. return
  8350. }
  8351. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8352. if err != nil {
  8353. logs.Error(err)
  8354. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8355. return
  8356. }
  8357. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8358. if count > 0 {
  8359. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8360. if err != nil {
  8361. logs.Error(err)
  8362. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8363. return
  8364. }
  8365. }
  8366. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8367. if err != nil {
  8368. logs.Error(err)
  8369. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8370. return
  8371. }
  8372. // var barIdStr []string
  8373. // for _, bar := range barIdList {
  8374. // barIdStr = append(barIdStr, bar["barid"])
  8375. // }
  8376. // if len(barIdStr) > 0 {
  8377. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8378. // if err != nil {
  8379. // logs.Error(err)
  8380. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8381. // return
  8382. // }
  8383. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8384. // if err != nil {
  8385. // logs.Error(err)
  8386. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8387. // return
  8388. // }
  8389. // now := time.Now()
  8390. // for _, newFpd := range newFpdDataList {
  8391. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8392. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8393. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8394. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8395. // if err != nil {
  8396. // logs.Error(err)
  8397. // appG.Response(http.StatusOK, e.ERROR, false)
  8398. // return
  8399. // }
  8400. // }
  8401. // for _, newFeedp := range newFeedpList {
  8402. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8403. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8404. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8405. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8406. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8407. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8408. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8409. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8410. // if err != nil {
  8411. // logs.Error(err)
  8412. // appG.Response(http.StatusOK, e.ERROR, false)
  8413. // return
  8414. // }
  8415. // }
  8416. // }
  8417. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8418. }
  8419. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8420. data := fasion["parammaps"].(map[string]interface{})
  8421. plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(0,1,2) ").Count()
  8422. fmt.Println(err)
  8423. plancount1, err := tx.SQL(`SELECT
  8424. count( 1 )
  8425. FROM
  8426. (
  8427. SELECT
  8428. d.id
  8429. FROM
  8430. downloadedplan d
  8431. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  8432. JOIN downloadplandtl1_exec d1e ON d1e.pid = d.id
  8433. JOIN downloadplandtl2 d2 ON d2.pid = d.id
  8434. WHERE
  8435. d.mydate = ?
  8436. AND d.havebutton = 0
  8437. AND lpplantype IN ( 0, 1, 2 )
  8438. AND ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id and dd2.fname = d2.fname) =
  8439. ( 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 )
  8440. GROUP BY
  8441. d.id
  8442. ) d
  8443. `,
  8444. data["startTime"]).Count()
  8445. fmt.Println(err)
  8446. if plancount != plancount1 && number < 10 {
  8447. number++
  8448. ExecDataParam(fasion, CommonParamMap, ParamMap, nil, nil, tx)
  8449. checkPlan(tx, fasion, CommonParamMap, ParamMap, number)
  8450. }
  8451. }
  8452. func EditPlanSort(c *gin.Context) {
  8453. appG := app.Gin{C: c}
  8454. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8455. fsions := gofasion.NewFasion(string(dataByte))
  8456. planIdStr := fsions.Get("planId").ValueStr()
  8457. mydate := fsions.Get("mydate").ValueStr()
  8458. sort := fsions.Get("sort").ValueStr()
  8459. tx := restful.Engine.NewSession()
  8460. defer tx.Close()
  8461. tx.Begin()
  8462. type downloadedplan struct {
  8463. Id int64 `xorm:"id"`
  8464. Sort int `xorm:"sort"`
  8465. Pid int64 `xorm:"pid"`
  8466. }
  8467. planInfo := new(downloadedplan)
  8468. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  8469. if err != nil {
  8470. logs.Error(err)
  8471. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8472. tx.Rollback()
  8473. return
  8474. }
  8475. sort1, _ := strconv.Atoi(sort)
  8476. if sort1 == planInfo.Sort {
  8477. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  8478. tx.Rollback()
  8479. return
  8480. }
  8481. 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()
  8482. if err != nil {
  8483. logs.Error(err)
  8484. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8485. tx.Rollback()
  8486. return
  8487. }
  8488. if count1 == 0 {
  8489. tx.Rollback()
  8490. logs.Error(err)
  8491. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  8492. return
  8493. }
  8494. 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()
  8495. if err != nil {
  8496. logs.Error(err)
  8497. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8498. tx.Rollback()
  8499. return
  8500. }
  8501. if count > 0 {
  8502. tx.Rollback()
  8503. logs.Error(err)
  8504. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  8505. return
  8506. }
  8507. if planInfo.Sort > sort1 {
  8508. 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()
  8509. if err != nil {
  8510. logs.Error(err)
  8511. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8512. tx.Rollback()
  8513. return
  8514. }
  8515. var minSort, pidCount int
  8516. for _, sort := range minSortList {
  8517. minSort, _ = strconv.Atoi(sort["sort"])
  8518. }
  8519. planList := make([]*downloadedplan, 0)
  8520. 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)
  8521. if err != nil {
  8522. logs.Error(err)
  8523. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8524. tx.Rollback()
  8525. return
  8526. }
  8527. planPid := planInfo.Pid
  8528. planList1 := make([]*downloadedplan, 0)
  8529. planList2 := make([]*downloadedplan, 0)
  8530. for _, plan := range planList {
  8531. if plan.Pid == planPid {
  8532. pidCount++
  8533. planList1 = append(planList1, plan)
  8534. } else {
  8535. planList2 = append(planList2, plan)
  8536. }
  8537. }
  8538. planList1 = append(planList1, planList2...)
  8539. for i, plan := range planList1 {
  8540. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  8541. if err != nil {
  8542. logs.Error(err)
  8543. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8544. tx.Rollback()
  8545. return
  8546. }
  8547. }
  8548. } else {
  8549. 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()
  8550. if err != nil {
  8551. logs.Error(err)
  8552. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8553. tx.Rollback()
  8554. return
  8555. }
  8556. var maxSort int
  8557. for _, sort := range maxSortList {
  8558. maxSort, _ = strconv.Atoi(sort["sort"])
  8559. }
  8560. planList := make([]*downloadedplan, 0)
  8561. 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)
  8562. if err != nil {
  8563. logs.Error(err)
  8564. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8565. tx.Rollback()
  8566. return
  8567. }
  8568. planPid := planInfo.Pid
  8569. planList1 := make([]*downloadedplan, 0)
  8570. planList2 := make([]*downloadedplan, 0)
  8571. for _, plan := range planList {
  8572. if plan.Pid == planPid {
  8573. // pidCount++
  8574. planList1 = append(planList1, plan)
  8575. } else {
  8576. planList2 = append(planList2, plan)
  8577. }
  8578. }
  8579. planList2 = append(planList2, planList1...)
  8580. for i, plan := range planList2 {
  8581. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  8582. if err != nil {
  8583. logs.Error(err)
  8584. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8585. tx.Rollback()
  8586. return
  8587. }
  8588. }
  8589. }
  8590. err = tx.Commit()
  8591. if err != nil {
  8592. logs.Error(err)
  8593. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8594. tx.Rollback()
  8595. return
  8596. }
  8597. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8598. }
  8599. func EditDownloadedplanArtificial(c *gin.Context) {
  8600. appG := app.Gin{C: c}
  8601. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8602. fsions := gofasion.NewFasion(string(dataByte))
  8603. planIdStr := fsions.Get("planId").ValueStr()
  8604. tx := restful.Engine.NewSession()
  8605. defer tx.Close()
  8606. tx.Begin()
  8607. planIdList := strings.Split(planIdStr, ",")
  8608. for _, planId := range planIdList {
  8609. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? and havebutton != 1`, planId)
  8610. if err != nil {
  8611. logs.Error(err)
  8612. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8613. tx.Rollback()
  8614. return
  8615. }
  8616. }
  8617. err := tx.Commit()
  8618. if err != nil {
  8619. logs.Error(err)
  8620. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8621. tx.Rollback()
  8622. return
  8623. }
  8624. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8625. }
  8626. type PlanRFID struct {
  8627. RFID string `json:"RFID"`
  8628. Lweight string `json:"lweight"`
  8629. Gear string `json:"gear"`
  8630. Speed string `json:"speed"`
  8631. }
  8632. func GetPlanRFID(c *gin.Context) {
  8633. appG := app.Gin{C: c}
  8634. RFIDStr := c.Query("RFID")
  8635. planRFIDList := make([]*PlanRFID, 0)
  8636. planRFIDList = append(planRFIDList, &PlanRFID{
  8637. RFID: RFIDStr,
  8638. Lweight: "1411.1",
  8639. Gear: "1",
  8640. Speed: "10",
  8641. })
  8642. planRFIDList = append(planRFIDList, &PlanRFID{
  8643. RFID: RFIDStr,
  8644. Lweight: "1322.1",
  8645. Gear: "1",
  8646. Speed: "10",
  8647. })
  8648. planRFIDList = append(planRFIDList, &PlanRFID{
  8649. RFID: RFIDStr,
  8650. Lweight: "1904.1",
  8651. Gear: "1",
  8652. Speed: "10",
  8653. })
  8654. planRFIDList = append(planRFIDList, &PlanRFID{
  8655. RFID: RFIDStr,
  8656. Lweight: "1870.1",
  8657. Gear: "1",
  8658. Speed: "10",
  8659. })
  8660. planRFIDList = append(planRFIDList, &PlanRFID{
  8661. RFID: RFIDStr,
  8662. Lweight: "2041.1",
  8663. Gear: "1",
  8664. Speed: "10",
  8665. })
  8666. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  8667. }
  8668. type tmrEquipmentMuster struct {
  8669. A string
  8670. N string
  8671. }
  8672. func GetTmrEquipmentMuster(c *gin.Context) {
  8673. appG := app.Gin{C: c}
  8674. id := c.Query("id")
  8675. tx := restful.Engine.NewSession()
  8676. defer tx.Close()
  8677. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  8678. if err != nil {
  8679. logs.Error(err)
  8680. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8681. return
  8682. }
  8683. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  8684. for _, data := range dataList {
  8685. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  8686. for _, g := range tmrEquipmentMusterList {
  8687. a, _ := strconv.ParseFloat(g.A, 64)
  8688. n, _ := strconv.ParseFloat(g.N, 64)
  8689. a1, n1 := ddmmtoddd(a, n)
  8690. g.A = fmt.Sprintf("%f", n1)
  8691. g.N = fmt.Sprintf("%f", a1)
  8692. }
  8693. }
  8694. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  8695. }
  8696. func ddmmtoddd(lng, lat float64) (float64, float64) {
  8697. lngDegree := fmt.Sprintf("%f", lng/100)
  8698. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  8699. lngDegreeInt := int(lngDegreefloat * 1000000)
  8700. dd := lngDegreeInt / 100 * 100 / 60
  8701. fmt.Println(dd)
  8702. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  8703. latDegree := fmt.Sprintf("%f", lat/100)
  8704. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  8705. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  8706. latDegreeInt := int(latDegreefloat * 1000000)
  8707. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  8708. a, _ := strconv.ParseFloat(lngStr, 64)
  8709. b, _ := strconv.ParseFloat(latStr, 64)
  8710. return coordtransform.WGS84toGCJ02(b, a)
  8711. }
  8712. func EditDownloadedplanExecWeight(c *gin.Context) {
  8713. appG := app.Gin{C: c}
  8714. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8715. fsions := gofasion.NewFasion(string(dataByte))
  8716. pid := fsions.Get("pid").ValueStr()
  8717. sort := fsions.Get("sort").ValueStr()
  8718. weight := fsions.Get("weight").ValueStr()
  8719. tx := restful.Engine.NewSession()
  8720. defer tx.Close()
  8721. tx.Begin()
  8722. _, err := tx.Exec(` update downloadplandtl1_exec set actualweight = ? where pid = ? and sort = ? `, weight, pid, sort)
  8723. if err != nil {
  8724. logs.Error(err)
  8725. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8726. tx.Rollback()
  8727. return
  8728. }
  8729. _, 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)
  8730. if err != nil {
  8731. logs.Error(err)
  8732. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8733. tx.Rollback()
  8734. return
  8735. }
  8736. err = tx.Commit()
  8737. if err != nil {
  8738. logs.Error(err)
  8739. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8740. tx.Rollback()
  8741. return
  8742. }
  8743. appG.Response(http.StatusOK, e.SUCCESS, true)
  8744. }
  8745. func EditDownloadplandtl2Weight(c *gin.Context) {
  8746. appG := app.Gin{C: c}
  8747. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8748. fsions := gofasion.NewFasion(string(dataByte))
  8749. pid := fsions.Get("pid").ValueStr()
  8750. sort := fsions.Get("sort").ValueStr()
  8751. weight := fsions.Get("weight").ValueStr()
  8752. tx := restful.Engine.NewSession()
  8753. defer tx.Close()
  8754. tx.Begin()
  8755. _, err := tx.Exec(` update downloadplandtl2 set actualweight = ? where pid = ? and sort = ? `, weight, pid, sort)
  8756. if err != nil {
  8757. logs.Error(err)
  8758. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8759. tx.Rollback()
  8760. return
  8761. }
  8762. err = tx.Commit()
  8763. if err != nil {
  8764. logs.Error(err)
  8765. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8766. tx.Rollback()
  8767. return
  8768. }
  8769. appG.Response(http.StatusOK, e.SUCCESS, true)
  8770. }
  8771. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  8772. params := fasion.Get("parammaps")
  8773. surplus := params.Get("surplus").ValueStr()
  8774. surplusId := params.Get("surplusId").ValueStr()
  8775. tx := restful.Engine.NewSession()
  8776. defer tx.Close()
  8777. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  8778. if surplusId != "0" {
  8779. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  8780. if err != nil {
  8781. log.Println("PostDataByName-error-1: ", err)
  8782. return errors.New("配方修改失败!")
  8783. }
  8784. type ftdetail struct {
  8785. Id string
  8786. Fname string
  8787. Sort int64
  8788. }
  8789. ftList := make([]*ftdetail, 0)
  8790. for _, data := range dataList {
  8791. ft := new(ftdetail)
  8792. ft.Fname = data["fname"]
  8793. ft.Id = data["id"]
  8794. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  8795. if err != nil {
  8796. log.Println("PostDataByName-error-2: ", err)
  8797. return err
  8798. }
  8799. ft.Sort = sort
  8800. ftList = append(ftList, ft)
  8801. }
  8802. if surplus == "日粮" {
  8803. for _, ft := range ftList {
  8804. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  8805. }
  8806. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  8807. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  8808. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  8809. fmt.Println(err)
  8810. } else {
  8811. var sort int64
  8812. for _, ft := range ftList {
  8813. if ft.Fname == surplus {
  8814. sort = ft.Sort
  8815. break
  8816. }
  8817. }
  8818. if sort == 0 {
  8819. for _, ft := range ftList {
  8820. ft.Sort = ft.Sort + 1
  8821. }
  8822. } else {
  8823. for _, ft := range ftList {
  8824. if ft.Sort >= sort {
  8825. ft.Sort = ft.Sort + 1
  8826. }
  8827. }
  8828. }
  8829. for _, ft := range ftList {
  8830. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  8831. }
  8832. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  8833. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  8834. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  8835. if err != nil {
  8836. log.Println("PostDataByName-error-1: ", err)
  8837. fmt.Println(err)
  8838. return errors.New("配方修改失败!")
  8839. }
  8840. }
  8841. }
  8842. return nil
  8843. }
  8844. func FeedSurplus(fasion *gofasion.Fasion) {
  8845. tx := restful.Engine.NewSession()
  8846. defer tx.Close()
  8847. params := fasion.Get("parammaps")
  8848. feedId := params.Get("id").ValueStr()
  8849. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  8850. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  8851. }
  8852. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  8853. // params := fasion.Get("parammaps")
  8854. // surplus := params.Get("surplus").ValueStr()
  8855. // surplusId := params.Get("surplusId").ValueStr()
  8856. tx := restful.Engine.NewSession()
  8857. defer tx.Close()
  8858. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  8859. if surplusId != "0" {
  8860. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  8861. if err != nil {
  8862. log.Println("PostDataByName-error-1: ", err)
  8863. return errors.New("配方修改失败!")
  8864. }
  8865. type ftdetail struct {
  8866. Id string
  8867. Fname string
  8868. Sort int64
  8869. }
  8870. ftList := make([]*ftdetail, 0)
  8871. for _, data := range dataList {
  8872. ft := new(ftdetail)
  8873. ft.Fname = data["fname"]
  8874. ft.Id = data["id"]
  8875. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  8876. if err != nil {
  8877. log.Println("PostDataByName-error-2: ", err)
  8878. return err
  8879. }
  8880. ft.Sort = sort
  8881. ftList = append(ftList, ft)
  8882. }
  8883. if surplus == "日粮" {
  8884. for _, ft := range ftList {
  8885. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  8886. }
  8887. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  8888. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  8889. pastureId, id, surplusId, surplusId, surplusId)
  8890. fmt.Println(err)
  8891. } else {
  8892. var sort int64
  8893. for _, ft := range ftList {
  8894. if ft.Fname == surplus {
  8895. sort = ft.Sort
  8896. break
  8897. }
  8898. }
  8899. if sort == 0 {
  8900. for _, ft := range ftList {
  8901. ft.Sort = ft.Sort + 1
  8902. }
  8903. } else {
  8904. for _, ft := range ftList {
  8905. if ft.Sort >= sort {
  8906. ft.Sort = ft.Sort + 1
  8907. }
  8908. }
  8909. }
  8910. for _, ft := range ftList {
  8911. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  8912. }
  8913. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  8914. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  8915. id, surplusId, surplusId, sort, surplusId, pastureId)
  8916. if err != nil {
  8917. log.Println("PostDataByName-error-1: ", err)
  8918. fmt.Println(err)
  8919. return errors.New("配方修改失败!")
  8920. }
  8921. }
  8922. }
  8923. return nil
  8924. }
  8925. func GetLanguageStatus() string {
  8926. tx := restful.Engine.NewSession()
  8927. defer tx.Close()
  8928. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  8929. if err != nil {
  8930. log.Println(err)
  8931. return "0"
  8932. }
  8933. return dataList[0]["inforvalue"]
  8934. }
  8935. func EditLanguage(c *gin.Context) {
  8936. appG := app.Gin{C: c}
  8937. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8938. fsions := gofasion.NewFasion(string(dataByte))
  8939. language := fsions.Get("language").ValueStr()
  8940. tx := restful.Engine.NewSession()
  8941. defer tx.Close()
  8942. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  8943. if err != nil {
  8944. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8945. return
  8946. }
  8947. if language == "0" {
  8948. _, err := tx.Exec(`delete from dictlist `)
  8949. if err != nil {
  8950. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8951. return
  8952. }
  8953. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  8954. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  8955. if err != nil {
  8956. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8957. return
  8958. }
  8959. } else {
  8960. _, err := tx.Exec(`delete from dictlist `)
  8961. if err != nil {
  8962. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8963. return
  8964. }
  8965. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  8966. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  8967. if err != nil {
  8968. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8969. return
  8970. }
  8971. }
  8972. appG.Response(http.StatusOK, e.SUCCESS, true)
  8973. }