ops.go 403 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558
  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/models"
  23. "tmr-watch/module"
  24. "tmr-watch/pkg/app"
  25. "tmr-watch/pkg/e"
  26. "tmr-watch/pkg/logging"
  27. "github.com/360EntSecGroup-Skylar/excelize"
  28. "github.com/Anderson-Lu/gofasion/gofasion"
  29. "github.com/astaxie/beego/logs"
  30. "github.com/gin-gonic/gin"
  31. "github.com/qichengzx/coordtransform"
  32. "github.com/tealeg/xlsx"
  33. "github.com/xormplus/xorm"
  34. excelizexuri "github.com/xuri/excelize/v2"
  35. )
  36. // @Summary 根据SQL执行得到数据集
  37. // @Tags getData
  38. // @Accept json
  39. // @Produce json
  40. // @Param sql query string true "sql"
  41. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  42. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  43. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  44. // @Router /data/getdata [POST]
  45. func GetData(c *gin.Context) {
  46. appG := app.Gin{C: c}
  47. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  48. fsion := gofasion.NewFasion(string(dataByte))
  49. sqlstr := fsion.Get("sql").ValueStr()
  50. offset := fsion.Get("offset").ValueDefaultInt(0)
  51. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  52. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  53. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  54. if err != nil {
  55. appG.Response(http.StatusOK, e.ERROR, err.Error())
  56. } else {
  57. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  58. }
  59. }
  60. func Testpartitions(c *gin.Context) {
  61. appG := app.Gin{C: c}
  62. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  63. fsion := gofasion.NewFasion(string(dataByte))
  64. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  65. user := fsion.Get("user").ValueStr() //获取新数据库用户
  66. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  67. host := fsion.Get("host").ValueStr() //获取新数据库名称
  68. port := fsion.Get("port").ValueStr() //获取新数据库名称
  69. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  70. if sqls == nil || err1 != nil {
  71. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  72. }
  73. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  74. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  75. mydb, err := sql.Open("mysql", connecting) //连接新连接
  76. if err != nil {
  77. println("err1", err.Error())
  78. }
  79. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  80. if err != nil {
  81. println("err2", err.Error())
  82. }
  83. mydb.Close()
  84. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  85. mydb, err = sql.Open("mysql", connecting)
  86. if err != nil {
  87. println("err3", err.Error())
  88. }
  89. defer mydb.Close()
  90. if err == nil {
  91. mydb.SetMaxOpenConns(10)
  92. mydb.SetMaxIdleConns(10)
  93. }
  94. errmsg := ""
  95. if err == nil {
  96. //tx ,_ :=mydb.Begin()
  97. for _, sqlstr := range sqlstrs {
  98. //println("sqlstr---",sqlstr)
  99. if sqlstr == "" {
  100. continue
  101. }
  102. _, err = mydb.Exec(sqlstr)
  103. if err != nil {
  104. println("err4", err.Error())
  105. errmsg = err.Error()
  106. //err1 :=tx.Rollback()
  107. }
  108. }
  109. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  110. //err =tx.Commit()
  111. }
  112. if errmsg == "" {
  113. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  114. } else {
  115. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  116. }
  117. }
  118. func TestData(c *gin.Context) {
  119. appG := app.Gin{C: c}
  120. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  121. fsion := gofasion.NewFasion(string(dataByte))
  122. sqlstr := fsion.Get("sql").ValueStr()
  123. token := ""
  124. if tempv, exists := c.Get("jwt_username"); exists {
  125. token = tempv.(string)
  126. }
  127. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  128. }
  129. // @Summary 根据APISQL表中SQL执行得到数据集
  130. // @Tags GetDataByName
  131. // @Accept json
  132. // @Produce json
  133. // @Param sqlname body string true "sqlname"
  134. // @Param offset body int true "offset"
  135. // @Param pagecount body int true "pagecount"
  136. // @Param returntype body string true "returntype"
  137. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  138. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  139. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  140. // @Router /data/GetDataByName [POST]
  141. func GetDataByName(c *gin.Context) {
  142. appG := app.Gin{C: c}
  143. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  144. fsion := gofasion.NewFasion(string(dataByte))
  145. sqlnamestr := fsion.Get("name").ValueStr()
  146. offset := fsion.Get("offset").ValueDefaultInt(0)
  147. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  148. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  149. tx := restful.Engine.NewSession()
  150. err := tx.Begin()
  151. defer func() {
  152. switch {
  153. case err != nil:
  154. logging.Error("tx.Begin 事务启动失败__error:", err)
  155. if tx != nil {
  156. tx.Rollback()
  157. }
  158. default:
  159. if tx != nil {
  160. err = tx.Commit()
  161. }
  162. }
  163. if tx != nil {
  164. tx.Close()
  165. }
  166. }()
  167. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  168. if sql != "" {
  169. s_params := make([]interface{}, 0)
  170. if fsion.HasKey("parammaps") {
  171. parammaps := fsion.Get("parammaps")
  172. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  173. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  174. }
  175. paramslist := strings.Split(p, ",")
  176. if len(paramslist) > 0 && p != "" {
  177. for _, value := range paramslist {
  178. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  179. if tempv, exists := c.Get("jwt_username"); exists {
  180. s_params = append(s_params, tempv.(string))
  181. } else {
  182. s_params = append(s_params, "")
  183. }
  184. } else {
  185. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  186. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  187. // tmrNameList := []string{}
  188. // for _, tmr := range tmrArray {
  189. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  190. // }
  191. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  192. // } else {
  193. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  194. // }
  195. }
  196. }
  197. }
  198. } else if fsion.HasKey("params") {
  199. params := fsion.Get("params").Array()
  200. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  201. for _, v_params := range params {
  202. s_params = append(s_params, v_params.ValueStr())
  203. }
  204. }
  205. if returntype == "xlsx" {
  206. var xlsxfile *xlsx.File
  207. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  208. //c.File("c:/dd.xlsx")
  209. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  210. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  211. c.Header("Content-Transfer-Encoding", "binary")
  212. _ = xlsxfile.Write(c.Writer)
  213. } else {
  214. if sqlnamestr == "getHomepageStr" {
  215. parammaps := fsion.Get("parammaps")
  216. pastureid := parammaps.Get("pastureid").ValueStr()
  217. var montimeList []float64
  218. var montime float64
  219. var wg sync.WaitGroup
  220. now := time.Now()
  221. for i := 0; i < 30; i++ {
  222. wg.Add(1)
  223. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  224. go func(nowstr string) {
  225. defer wg.Done()
  226. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  227. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  228. if len(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})) > 0 {
  229. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  230. montimeList = append(montimeList, m)
  231. }
  232. }(nowstr)
  233. }
  234. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  235. if err != nil {
  236. logging.Error("GetDataByName err: ", err)
  237. msg := geterrmsg(err.Error())
  238. appG.Response(http.StatusOK, e.ERROR, msg)
  239. }
  240. wg.Wait()
  241. for _, m := range montimeList {
  242. montime += m
  243. }
  244. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  245. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  246. return
  247. }
  248. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  249. if err != nil {
  250. logging.Error("GetDataByName err: ", err)
  251. msg := geterrmsg(err.Error())
  252. appG.Response(http.StatusOK, e.ERROR, msg)
  253. } else {
  254. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  255. }
  256. }
  257. } else {
  258. appG.Response(http.StatusOK, e.SUCCESS, nil)
  259. }
  260. }
  261. // @Summary 根据APISQL表中SQL执行得到数据集
  262. // @Tags GetDataByName
  263. // @Accept json
  264. // @Produce json
  265. // @Param sqlname body string true "sqlname"
  266. // @Param offset body int true "offset"
  267. // @Param pagecount body int true "pagecount"
  268. // @Param returntype body string true "returntype"
  269. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  270. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  271. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  272. // @Router /data/GetDataByName [POST]
  273. func GetDataBySqlIN(c *gin.Context) {
  274. appG := app.Gin{C: c}
  275. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  276. fsion := gofasion.NewFasion(string(dataByte))
  277. sqlnamestr := fsion.Get("name").ValueStr()
  278. offset := fsion.Get("offset").ValueDefaultInt(0)
  279. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  280. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  281. tx := restful.Engine.NewSession()
  282. err := tx.Begin()
  283. defer func() {
  284. switch {
  285. case err != nil:
  286. logging.Error("tx.Begin 事务启动失败__error:", err)
  287. if tx != nil {
  288. tx.Rollback()
  289. }
  290. default:
  291. if tx != nil {
  292. err = tx.Commit()
  293. }
  294. }
  295. if tx != nil {
  296. tx.Close()
  297. }
  298. }()
  299. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  300. if sql != "" {
  301. s_params := make([]interface{}, 0)
  302. if fsion.HasKey("parammaps") {
  303. parammaps := fsion.Get("parammaps")
  304. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  305. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  306. }
  307. paramslist := strings.Split(p, ",")
  308. if len(paramslist) > 0 && p != "" {
  309. for _, value := range paramslist {
  310. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  311. if tempv, exists := c.Get("jwt_username"); exists {
  312. s_params = append(s_params, tempv.(string))
  313. } else {
  314. s_params = append(s_params, "")
  315. }
  316. } else {
  317. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  318. }
  319. }
  320. }
  321. } else if fsion.HasKey("params") {
  322. params := fsion.Get("params").Array()
  323. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  324. for _, v_params := range params {
  325. s_params = append(s_params, v_params.ValueStr())
  326. }
  327. }
  328. if returntype == "xlsx" {
  329. var xlsxfile *xlsx.File
  330. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  331. //c.File("c:/dd.xlsx")
  332. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  333. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  334. c.Header("Content-Transfer-Encoding", "binary")
  335. _ = xlsxfile.Write(c.Writer)
  336. } else {
  337. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  338. if err != nil {
  339. logging.Error("GetDataByName err: ", err)
  340. msg := geterrmsg(err.Error())
  341. appG.Response(http.StatusOK, e.ERROR, msg)
  342. } else {
  343. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  344. }
  345. }
  346. } else {
  347. appG.Response(http.StatusOK, e.SUCCESS, nil)
  348. }
  349. }
  350. // 错误处理
  351. // 将报错信息处理成汉字
  352. func geterrmsg(errstr string) (msgstr string) {
  353. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  354. rs := []rune(errstr)
  355. if hzRegexp.MatchString(string(rs[0])) {
  356. msgstr = errstr
  357. return
  358. }
  359. if strings.Contains(errstr, "Duplicate entry") {
  360. strs := strings.Split(errstr, ` key '`)
  361. if len(strs) > 1 {
  362. if len(strs[len(strs)-1]) > 1 {
  363. errstr = "Duplicate entry :" + strs[len(strs)-1]
  364. }
  365. }
  366. }
  367. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  368. if err != nil {
  369. msgstr = errstr
  370. return
  371. }
  372. if msg == nil || len(msg) == 0 {
  373. var param []interface{}
  374. param = append(param, errstr, errstr)
  375. go func() {
  376. tx := restful.Engine.NewSession()
  377. err := tx.Begin()
  378. defer func() {
  379. switch {
  380. case err != nil:
  381. logging.Error("tx.Begin 事务启动失败__error:", err)
  382. if tx != nil {
  383. tx.Rollback()
  384. }
  385. default:
  386. if tx != nil {
  387. err = tx.Commit()
  388. }
  389. }
  390. if tx != nil {
  391. tx.Close()
  392. }
  393. }()
  394. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  395. if err != nil {
  396. logging.Error("insert into err_msg(err,msg) err", err)
  397. }
  398. }()
  399. msgstr = errstr
  400. } else {
  401. msgstr = msg[0]["msg"]
  402. }
  403. return
  404. }
  405. // @Summary 根据APISQL表中SQL执行得到数据集
  406. // @Tags GetDataByNameForm
  407. // @Accept json
  408. // @Produce json
  409. // @Param sqlname body json true "sqlname"
  410. // @Param offset query int true "offset"
  411. // @Param pagecount query int true "pagecount"
  412. // @Param returntype query string true "returntype"
  413. // @Param s formData json true "ss"
  414. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  415. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  416. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  417. // @Router /data/GetDataByNameForm [POST]
  418. func GetDataByNameForm(c *gin.Context) {
  419. appG := app.Gin{C: c}
  420. //sqlnamestr := c.PostForm("measureNumber")
  421. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  422. //fsion := gofasion.NewFasion(string(dataByte))
  423. //sqlnamestr := fsion.Get("name").ValueStr()
  424. //offset := fsion.Get("offset").ValueInt()
  425. //pagecount := fsion.Get("pagecount").ValueInt()
  426. //returntype := fsion.Get("returntype").ValueStr()
  427. //params := fsion.Get("params").Array()
  428. c.Request.ParseForm()
  429. params := c.Request.Form
  430. offset := 0
  431. pageSize_ := 0
  432. returntype := params.Get("page")
  433. if returntype == "" {
  434. returntype = "0"
  435. }
  436. if tempv, exists := c.Get("jwt_username"); exists {
  437. params.Set("JwtUserName", tempv.(string))
  438. } else {
  439. params.Set("JwtUserName", "")
  440. }
  441. sqlnamestr := params.Get("name")
  442. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  443. s_params := make([]interface{}, 0)
  444. if returntype == "1" {
  445. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  446. if error != nil {
  447. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  448. }
  449. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  450. if error != nil {
  451. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  452. }
  453. pageSize_ = pageSize
  454. offset = pageNum
  455. }
  456. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  457. paramslist := strings.Split(p, ",")
  458. if len(paramslist) > 0 && p != "" {
  459. for _, value := range paramslist {
  460. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  461. }
  462. }
  463. if sql != "" {
  464. if returntype == "xlsx" {
  465. var xlsxfile *xlsx.File
  466. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  467. c.Header("Content-Type", "application/octet-stream")
  468. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  469. c.Header("Content-Transfer-Encoding", "binary")
  470. _ = xlsxfile.Write(c.Writer)
  471. } else {
  472. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  473. if err != nil {
  474. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  475. } else {
  476. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  477. }
  478. }
  479. } else {
  480. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  481. }
  482. }
  483. // @Summary 递归获取所有
  484. // @Tags menu
  485. // @Accept json
  486. // @Produce json
  487. // @Param Ton query string true "Ton"
  488. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  489. // @Router /authdata/GetRoleMenus [GET]
  490. func GetRecuDataByName(c *gin.Context) {
  491. appG := app.Gin{C: c}
  492. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  493. fsion := gofasion.NewFasion(string(dataByte))
  494. sqlnamestr := fsion.Get("name").ValueStr()
  495. parentidname := fsion.Get("idname").ValueStr()
  496. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  497. params := make(map[string]interface{})
  498. s_params := make([]interface{}, 0)
  499. if fsion.HasKey("params") {
  500. for _, v_params := range fsion.Get("params").Array() {
  501. s_params = append(s_params, v_params.ValueStr())
  502. }
  503. params["params"] = s_params
  504. } else {
  505. jparams := fsion.Get("parammaps")
  506. paramslist := strings.Split(p, ",")
  507. if len(paramslist) > 0 && p != "" {
  508. for _, value := range paramslist {
  509. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  510. if tempv, exists := c.Get("jwt_username"); exists {
  511. params[value] = tempv.(string)
  512. } else {
  513. params[value] = ""
  514. }
  515. } else {
  516. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  517. }
  518. }
  519. }
  520. }
  521. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  522. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  523. if err != nil {
  524. appG.Response(http.StatusOK, e.ERROR, err.Error())
  525. }
  526. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  527. }
  528. // @Summary 根据APISQL表中SQL执行得到数据集
  529. // @Tags GetDataByNames
  530. // @Accept json
  531. // @Produce json
  532. // @RequestBody sqlname query string true "sqlname"
  533. // @Param offset query int true "offset"
  534. // @Param pagecount query int true "pagecount"
  535. // @Param returntype query string true "returntype"
  536. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  537. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  538. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  539. // @Router /data/GetDataByNames [POST]
  540. func GetDataByNames(c *gin.Context) {
  541. appG := app.Gin{C: c}
  542. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  543. fsion := gofasion.NewFasion(string(dataByte))
  544. sqlParams := fsion.Array()
  545. queryData := make(map[string]interface{})
  546. for _, v := range sqlParams {
  547. fsion2 := gofasion.NewFasion(v.Json())
  548. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  549. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  550. if sql == "" {
  551. errorm := make(map[string]interface{})
  552. errorm["code"] = e.ERROR
  553. errorm["message"] = "sql没找到"
  554. queryData[fsion2.Get("name").ValueStr()] = errorm
  555. continue
  556. } else if sql != "" {
  557. offset := fsion2.Get("offset").ValueInt()
  558. pagecount := fsion2.Get("pagecount").ValueInt()
  559. returntype := fsion2.Get("returntype").ValueStr()
  560. s_params := make([]interface{}, 0)
  561. if fsion2.HasKey("parammaps") {
  562. parammaps := fsion2.Get("parammaps")
  563. paramslist := strings.Split(p, ",")
  564. if len(paramslist) > 0 && p != "" {
  565. for _, value := range paramslist {
  566. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  567. if tempv, exists := c.Get("jwt_username"); exists {
  568. s_params = append(s_params, tempv.(string))
  569. } else {
  570. s_params = append(s_params, "")
  571. }
  572. } else {
  573. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  574. }
  575. }
  576. }
  577. } else if fsion2.HasKey("params") {
  578. params := fsion2.Get("params").Array()
  579. for _, v_params := range params {
  580. s_params = append(s_params, v_params.ValueStr())
  581. }
  582. }
  583. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  584. if err != nil {
  585. errorm := make(map[string]interface{})
  586. errorm["code"] = e.ERROR
  587. errorm["message"] = err.Error()
  588. queryData[fsion2.Get("name").ValueStr()] = errorm
  589. logging.Error("GetDataByNames err: ", err)
  590. continue
  591. } else {
  592. queryData[fsion2.Get("name").ValueStr()] = queryData1
  593. }
  594. }
  595. }
  596. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  597. }
  598. // @Summary 根据APISQL表中SQL执行得到数据集
  599. // @Tags PostDataByNameForm
  600. // @Accept json
  601. // @Produce json
  602. // @Param sqlname query string true "sqlname"
  603. // @Param offset query int true "offset"
  604. // @Param pagecount query int true "pagecount"
  605. // @Param returntype query string true "returntype"
  606. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  607. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  608. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  609. // @Router /data/PostDataByNameForm [POST]
  610. func PostDataByNameForm(c *gin.Context) {
  611. appG := app.Gin{C: c}
  612. c.Request.ParseForm()
  613. params := c.Request.Form
  614. sqlnamestr := params.Get("name")
  615. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  616. s_params := make([]interface{}, 0)
  617. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  618. paramslist := strings.Split(p, ",")
  619. if len(paramslist) > 0 {
  620. for _, value := range paramslist {
  621. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  622. }
  623. }
  624. if sql != "" {
  625. queryData, err := execDataBySql(sql, s_params)
  626. if err != nil {
  627. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  628. } else {
  629. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  630. }
  631. } else {
  632. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  633. }
  634. }
  635. // GetReportform 将数据集转换格式
  636. // @Tags PostDataByNameForm
  637. // @Accept json
  638. // @Produce json
  639. // @Param sqlname query string true "sqlname"
  640. // @Param offset query int true "offset"
  641. // @Param pagecount query int true "pagecount"
  642. // @Param returntype query string true "returntype"
  643. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  644. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  645. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  646. func GetReportform(c *gin.Context) {
  647. appG := app.Gin{C: c}
  648. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  649. fsion := gofasion.NewFasion(string(dataByte))
  650. sqlnamestr := fsion.Get("name").ValueStr()
  651. checked := fsion.Get("checked").ValueStr()
  652. offset := fsion.Get("offset").ValueDefaultInt(0)
  653. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  654. parammaps := fsion.Get("parammaps")
  655. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  656. mode := parammaps.Get("mode").ValueDefaultInt(0)
  657. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  658. tx := restful.Engine.NewSession()
  659. err := tx.Begin()
  660. defer func() {
  661. switch {
  662. case err != nil:
  663. if tx != nil {
  664. tx.Rollback()
  665. }
  666. default:
  667. if tx != nil {
  668. err = tx.Commit()
  669. }
  670. }
  671. if tx != nil {
  672. tx.Close()
  673. }
  674. }()
  675. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  676. if err != nil {
  677. appG.Response(http.StatusOK, e.ERROR, err.Error())
  678. } else {
  679. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  680. }
  681. }
  682. // GetUpkeepPlan 保养计划
  683. func GetUpkeepPlan(c *gin.Context) {
  684. appG := app.Gin{C: c}
  685. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  686. fsion := gofasion.NewFasion(string(dataByte))
  687. sqlnamestr := fsion.Get("name").ValueStr()
  688. offset := fsion.Get("offset").ValueDefaultInt(0)
  689. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  690. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  691. month := fsion.Get("month").ValueDefaultStr("map")
  692. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  693. tx := restful.Engine.NewSession()
  694. err := tx.Begin()
  695. defer func() {
  696. switch {
  697. case err != nil:
  698. if tx != nil {
  699. tx.Rollback()
  700. }
  701. default:
  702. if tx != nil {
  703. err = tx.Commit()
  704. }
  705. }
  706. if tx != nil {
  707. tx.Close()
  708. }
  709. }()
  710. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  711. if sql != "" {
  712. s_params := make([]interface{}, 0)
  713. if fsion.HasKey("parammaps") {
  714. parammaps := fsion.Get("parammaps")
  715. paramslist := strings.Split(p, ",")
  716. if len(paramslist) > 0 && p != "" {
  717. for _, value := range paramslist {
  718. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  719. if tempv, exists := c.Get("jwt_username"); exists {
  720. s_params = append(s_params, tempv.(string))
  721. } else {
  722. s_params = append(s_params, "")
  723. }
  724. } else {
  725. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  726. }
  727. }
  728. }
  729. } else if fsion.HasKey("params") {
  730. params := fsion.Get("params").Array()
  731. for _, v_params := range params {
  732. s_params = append(s_params, v_params.ValueStr())
  733. }
  734. }
  735. if returntype == "xlsx" {
  736. var xlsxfile *xlsx.File
  737. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  738. //c.File("c:/dd.xlsx")
  739. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  740. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  741. c.Header("Content-Transfer-Encoding", "binary")
  742. _ = xlsxfile.Write(c.Writer)
  743. } else {
  744. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  745. if err != nil {
  746. appG.Response(http.StatusOK, e.ERROR, err.Error())
  747. } else {
  748. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  749. if v, ok := value["id"]; ok {
  750. //month = "2020-03"
  751. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  752. if seviceplans != nil {
  753. for _, va := range seviceplans { //根据保养计划获取保养单
  754. //day,_ :=strconv.Atoi(va["day"])
  755. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  756. //buk := make(map[string]map[string]string)
  757. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  758. jstr := ""
  759. if bu["plantime"][8:9] == "0" {
  760. jstr = "m" + bu["plantime"][9:]
  761. } else {
  762. jstr = "m" + bu["plantime"][8:]
  763. }
  764. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  765. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  766. } else {
  767. if bu["flowCompeleted"] >= "2" {
  768. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  769. } else {
  770. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  771. }
  772. }
  773. }
  774. }
  775. }
  776. }
  777. }
  778. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  779. }
  780. }
  781. } else {
  782. appG.Response(http.StatusOK, e.SUCCESS, nil)
  783. }
  784. }
  785. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  786. // todo 优化性能 children统一查询
  787. // @Tags PostDataByNameForm
  788. // @Accept json
  789. // @Produce json
  790. // @Param sqlname query string true "sqlname"
  791. // @Param offset query int true "offset"
  792. // @Param pagecount query int true "pagecount"
  793. // @Param returntype query string true "returntype"
  794. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  795. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  796. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  797. func GetArrList(c *gin.Context) {
  798. appG := app.Gin{C: c}
  799. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  800. fsion := gofasion.NewFasion(string(dataByte))
  801. sqlnamestr := fsion.Get("name").ValueStr()
  802. sqlnamestr1 := fsion.Get("name1").ValueStr()
  803. offset := fsion.Get("offset").ValueDefaultInt(0)
  804. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  805. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  806. month := fsion.Get("month").ValueDefaultStr("map")
  807. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  808. tx := restful.Engine.NewSession()
  809. err := tx.Begin()
  810. defer func() {
  811. switch {
  812. case err != nil:
  813. if tx != nil {
  814. tx.Rollback()
  815. }
  816. default:
  817. if tx != nil {
  818. err = tx.Commit()
  819. }
  820. }
  821. if tx != nil {
  822. tx.Close()
  823. }
  824. }()
  825. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  826. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  827. if sql != "" {
  828. s_params := make([]interface{}, 0)
  829. if fsion.HasKey("parammaps") {
  830. parammaps := fsion.Get("parammaps")
  831. paramslist := strings.Split(p, ",")
  832. if len(paramslist) > 0 && p != "" {
  833. for _, value := range paramslist {
  834. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  835. if tempv, exists := c.Get("jwt_username"); exists {
  836. s_params = append(s_params, tempv.(string))
  837. } else {
  838. s_params = append(s_params, "")
  839. }
  840. } else {
  841. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  842. }
  843. }
  844. }
  845. }
  846. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  847. if err != nil {
  848. appG.Response(http.StatusOK, e.ERROR, err.Error())
  849. } else {
  850. paramslist1 := strings.Split(p1, ",")
  851. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  852. s_params1 := make([]interface{}, 0)
  853. if len(paramslist1) > 0 && p1 != "" {
  854. for _, v := range paramslist1 {
  855. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  856. }
  857. }
  858. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  859. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  860. }
  861. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  862. }
  863. } else {
  864. appG.Response(http.StatusOK, e.SUCCESS, nil)
  865. }
  866. }
  867. func GetAccount(c *gin.Context) {
  868. appG := app.Gin{C: c}
  869. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  870. fsion := gofasion.NewFasion(string(dataByte))
  871. sqlnamestr := fsion.Get("name").ValueStr()
  872. offset := fsion.Get("offset").ValueDefaultInt(0)
  873. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  874. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  875. tx := restful.Engine.NewSession()
  876. err := tx.Begin()
  877. defer func() {
  878. switch {
  879. case err != nil:
  880. logging.Error("tx.Begin 事务启动失败__error:", err)
  881. if tx != nil {
  882. tx.Rollback()
  883. }
  884. default:
  885. if tx != nil {
  886. err = tx.Commit()
  887. }
  888. }
  889. if tx != nil {
  890. tx.Close()
  891. }
  892. }()
  893. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  894. if sql != "" {
  895. s_params := make([]interface{}, 0)
  896. if fsion.HasKey("parammaps") {
  897. parammaps := fsion.Get("parammaps")
  898. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  899. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  900. }
  901. paramslist := strings.Split(p, ",")
  902. if len(paramslist) > 0 && p != "" {
  903. for _, value := range paramslist {
  904. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  905. if tempv, exists := c.Get("jwt_username"); exists {
  906. s_params = append(s_params, tempv.(string))
  907. } else {
  908. s_params = append(s_params, "")
  909. }
  910. } else {
  911. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  912. }
  913. }
  914. }
  915. } else if fsion.HasKey("params") {
  916. params := fsion.Get("params").Array()
  917. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  918. for _, v_params := range params {
  919. s_params = append(s_params, v_params.ValueStr())
  920. }
  921. }
  922. if returntype == "xlsx" {
  923. var xlsxfile *xlsx.File
  924. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  925. //c.File("c:/dd.xlsx")
  926. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  927. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  928. c.Header("Content-Transfer-Encoding", "binary")
  929. _ = xlsxfile.Write(c.Writer)
  930. } else {
  931. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  932. if err != nil {
  933. logging.Error("GetDataByName err: ", err)
  934. msg := geterrmsg(err.Error())
  935. appG.Response(http.StatusOK, e.ERROR, msg)
  936. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  937. } else {
  938. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  939. }
  940. }
  941. } else {
  942. appG.Response(http.StatusOK, e.SUCCESS, nil)
  943. }
  944. }
  945. // PostDataByName 根据APISQL表中SQL执行得到数据集
  946. // @Accept json
  947. // @Produce json
  948. // @Param sqlname query string true "sqlname"
  949. // @Param offset query int true "offset"
  950. // @Param pagecount query int true "pagecount"
  951. // @Param returntype query string true "returntype"
  952. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  953. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  954. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  955. // @Router /data/PostDataByName [POST]
  956. func PostDataByName(c *gin.Context) {
  957. appG := app.Gin{C: c}
  958. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  959. fsion := gofasion.NewFasion(string(dataByte))
  960. var err error
  961. queryData, err := module.PostDataByName(c, fsion)
  962. if err != nil {
  963. appG.Response(http.StatusOK, e.ERROR, err.Error())
  964. return
  965. }
  966. var (
  967. keyWord string
  968. )
  969. switch fsion.Get("name").ValueStr() {
  970. case "insertFeedclass":
  971. keyWord = "feed"
  972. err = module.GroupCategorySync(keyWord, fsion)
  973. case "deleteFeedclass":
  974. keyWord = "feed_delete"
  975. err = module.GroupCategoryDelete(keyWord, fsion)
  976. case "insertCowclass":
  977. keyWord = "cow"
  978. err = module.GroupCategorySync(keyWord, fsion)
  979. case "deleteCowclass":
  980. keyWord = "cow_delete"
  981. err = module.GroupCategoryDelete(keyWord, fsion)
  982. // case "updateFT":
  983. // FtdetailSurplus(fsion)
  984. // case "updateFeed":
  985. // FeedSurplus(fsion)
  986. default:
  987. }
  988. if err != nil {
  989. logging.Error(keyWord, err)
  990. }
  991. if queryData != nil {
  992. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  993. return
  994. }
  995. appG.Response(http.StatusOK, e.SUCCESS, nil)
  996. }
  997. //人脸识别/格润富德接口
  998. func GetRJSBData(c *gin.Context) {
  999. appG := app.Gin{C: c}
  1000. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1001. fsion := gofasion.NewFasion(string(dataByte))
  1002. sqlnamestr := fsion.Get("name").ValueStr()
  1003. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1004. offset := fsion.Get("offset").ValueDefaultInt(0)
  1005. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1006. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1007. month := fsion.Get("month").ValueDefaultStr("map")
  1008. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1009. pagecount = 1
  1010. tx := restful.Engine.NewSession()
  1011. err := tx.Begin()
  1012. defer func() {
  1013. switch {
  1014. case err != nil:
  1015. if tx != nil {
  1016. tx.Rollback()
  1017. }
  1018. default:
  1019. if tx != nil {
  1020. err = tx.Commit()
  1021. }
  1022. }
  1023. if tx != nil {
  1024. tx.Close()
  1025. }
  1026. }()
  1027. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1028. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1029. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1030. if sql != "" {
  1031. s_params := make([]interface{}, 0)
  1032. if fsion.HasKey("parammaps") {
  1033. parammaps := fsion.Get("parammaps")
  1034. paramslist := strings.Split(p, ",")
  1035. if len(paramslist) > 0 && p != "" {
  1036. for _, value := range paramslist {
  1037. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1038. if tempv, exists := c.Get("jwt_username"); exists {
  1039. s_params = append(s_params, tempv.(string))
  1040. } else {
  1041. s_params = append(s_params, "")
  1042. }
  1043. } else {
  1044. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1045. }
  1046. }
  1047. }
  1048. }
  1049. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1050. if err != nil {
  1051. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1052. } else {
  1053. paramslist1 := strings.Split(p1, ",")
  1054. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1055. s_params1 := make([]interface{}, 0)
  1056. if len(paramslist1) > 0 && p1 != "" {
  1057. for _, v := range paramslist1 {
  1058. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1059. }
  1060. }
  1061. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1062. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1063. }
  1064. var wg sync.WaitGroup
  1065. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1066. wg.Add(1)
  1067. go func(value map[string]interface{}) {
  1068. defer wg.Done()
  1069. _, err = tx.SQL(`update downloadedplan set artificial = 2 ,havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1070. }(value)
  1071. }
  1072. wg.Wait()
  1073. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1074. }
  1075. } else {
  1076. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1077. }
  1078. }
  1079. func PostRJSBData(c *gin.Context) {
  1080. appG := app.Gin{C: c}
  1081. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1082. fsion := gofasion.NewFasion(string(dataByte))
  1083. logging.Info("PostRJSBData err: ", string(dataByte))
  1084. s_params := make([]interface{}, 0)
  1085. tx := restful.Engine.NewSession()
  1086. err := tx.Begin()
  1087. defer func() {
  1088. switch {
  1089. case err != nil:
  1090. if tx != nil {
  1091. tx.Rollback()
  1092. }
  1093. default:
  1094. if tx != nil {
  1095. err = tx.Commit()
  1096. }
  1097. }
  1098. if tx != nil {
  1099. tx.Close()
  1100. }
  1101. }()
  1102. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1103. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1104. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1105. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1106. if !fsion.HasKey("parammaps") {
  1107. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1108. return
  1109. }
  1110. parammaps := fsion.Get("parammaps")
  1111. paramslist := strings.Split(p, ",")
  1112. if len(paramslist) > 0 && p != "" {
  1113. for _, value := range paramslist {
  1114. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1115. }
  1116. }
  1117. projuctid := parammaps.Get("projuctid").ValueStr()
  1118. _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
  1119. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1120. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1121. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1122. and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1123. if err != nil {
  1124. logging.Error("PostRJSBData-0 err: ", err)
  1125. msg := geterrmsg(err.Error())
  1126. // appG.Response(http.StatusOK, e.ERROR, msg)
  1127. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1128. return
  1129. }
  1130. _, err = tx.SQL(sql, s_params...).Execute()
  1131. if err != nil {
  1132. logging.Error("PostRJSBData err: ", err)
  1133. msg := geterrmsg(err.Error())
  1134. // appG.Response(http.StatusOK, e.ERROR, msg)
  1135. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1136. return
  1137. }
  1138. s_params = make([]interface{}, 0)
  1139. paramslist = strings.Split(p1, ",")
  1140. if len(paramslist) > 0 && p1 != "" {
  1141. for _, value := range paramslist {
  1142. // if value == "ID" {
  1143. // id := parammaps.Get("ID").ValueStr()
  1144. // pastureid := parammaps.Get("pastureid").ValueStr()
  1145. // 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
  1146. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1147. // if err != nil {
  1148. // logging.Error("PostRJSBData err: ", err)
  1149. // msg := geterrmsg(err.Error())
  1150. // appG.Response(http.StatusOK, e.ERROR, msg)
  1151. // return
  1152. // }
  1153. // for _, item := range datalist {
  1154. // id = item["id"]
  1155. // }
  1156. // s_params = append(s_params, id)
  1157. // } else {
  1158. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1159. // }
  1160. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1161. }
  1162. }
  1163. _, err = tx.SQL(sql1, s_params...).Execute()
  1164. if err != nil {
  1165. logging.Error("PostRJSBData1 err: ", err)
  1166. msg := geterrmsg(err.Error())
  1167. appG.Response(http.StatusOK, e.ERROR, msg)
  1168. return
  1169. }
  1170. s_params = make([]interface{}, 0)
  1171. paramslist = strings.Split(p2, ",")
  1172. if len(paramslist) > 0 && p2 != "" {
  1173. for _, value := range paramslist {
  1174. if value == "ID" {
  1175. id := parammaps.Get("ID").ValueStr()
  1176. pastureid := parammaps.Get("pastureid").ValueStr()
  1177. 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
  1178. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1179. if err != nil {
  1180. logging.Error("PostRJSBData err: ", err)
  1181. msg := geterrmsg(err.Error())
  1182. appG.Response(http.StatusOK, e.ERROR, msg)
  1183. return
  1184. }
  1185. for _, item := range datalist {
  1186. id = item["id"]
  1187. }
  1188. s_params = append(s_params, id)
  1189. } else {
  1190. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1191. }
  1192. }
  1193. }
  1194. _, err = tx.SQL(sql2, s_params...).Execute()
  1195. if err != nil {
  1196. logging.Error("PostRJSBData2 err: ", err)
  1197. msg := geterrmsg(err.Error())
  1198. appG.Response(http.StatusOK, e.ERROR, msg)
  1199. return
  1200. }
  1201. s_params = make([]interface{}, 0)
  1202. paramslist = strings.Split(p3, ",")
  1203. if len(paramslist) > 0 && p3 != "" {
  1204. for _, value := range paramslist {
  1205. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1206. }
  1207. }
  1208. _, err = tx.SQL(sql3, s_params...).Execute()
  1209. if err != nil {
  1210. logging.Error("PostRJSBData3 err: ", err)
  1211. msg := geterrmsg(err.Error())
  1212. appG.Response(http.StatusOK, e.ERROR, msg)
  1213. return
  1214. }
  1215. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1216. }
  1217. func PostRJSBDatas(c *gin.Context) {
  1218. appG := app.Gin{C: c}
  1219. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1220. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1221. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1222. fmt.Println(string(dataByte))
  1223. tx := restful.Engine.NewSession()
  1224. err := tx.Begin()
  1225. defer func() {
  1226. switch {
  1227. case err != nil:
  1228. if tx != nil {
  1229. tx.Rollback()
  1230. }
  1231. default:
  1232. if tx != nil {
  1233. err = tx.Commit()
  1234. }
  1235. }
  1236. if tx != nil {
  1237. tx.Close()
  1238. }
  1239. }()
  1240. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1241. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1242. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1243. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1244. for _, fsion := range fsions {
  1245. if !fsion.HasKey("parammaps") {
  1246. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1247. return
  1248. }
  1249. parammaps := fsion.Get("parammaps")
  1250. ID := parammaps.Get("ID").ValueStr()
  1251. if ID == "" {
  1252. continue
  1253. }
  1254. s_params := make([]interface{}, 0)
  1255. paramslist := strings.Split(p, ",")
  1256. if len(paramslist) > 0 && p != "" {
  1257. for _, value := range paramslist {
  1258. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1259. }
  1260. }
  1261. // ALTER TABLE `tmr`
  1262. // ADD COLUMN `concentrate` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 未回传 1 已回传' AFTER `appoint`
  1263. projuctid := parammaps.Get("projuctid").ValueStr()
  1264. _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
  1265. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1266. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1267. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1268. and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1269. if err != nil {
  1270. logging.Error("PostRJSBData-0 err: ", err)
  1271. msg := geterrmsg(err.Error())
  1272. // appG.Response(http.StatusOK, e.ERROR, msg)
  1273. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1274. return
  1275. }
  1276. _, err = tx.SQL(sql, s_params...).Execute()
  1277. if err != nil {
  1278. logging.Error("PostRJSBData err: ", err)
  1279. msg := geterrmsg(err.Error())
  1280. // appG.Response(http.StatusOK, e.ERROR, msg)
  1281. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1282. return
  1283. }
  1284. s_params = make([]interface{}, 0)
  1285. paramslist = strings.Split(p1, ",")
  1286. if len(paramslist) > 0 && p1 != "" {
  1287. for _, value := range paramslist {
  1288. // if value == "ID" {
  1289. // id := parammaps.Get("ID").ValueStr()
  1290. // pastureid := parammaps.Get("pastureid").ValueStr()
  1291. // 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
  1292. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1293. // if err != nil {
  1294. // logging.Error("PostRJSBData err: ", err)
  1295. // msg := geterrmsg(err.Error())
  1296. // appG.Response(http.StatusOK, e.ERROR, msg)
  1297. // return
  1298. // }
  1299. // for _, item := range datalist {
  1300. // id = item["id"]
  1301. // }
  1302. // s_params = append(s_params, id)
  1303. // } else {
  1304. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1305. // }
  1306. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1307. }
  1308. }
  1309. _, err = tx.SQL(sql1, s_params...).Execute()
  1310. if err != nil {
  1311. logging.Error("PostRJSBData1 err: ", err)
  1312. msg := geterrmsg(err.Error())
  1313. appG.Response(http.StatusOK, e.ERROR, msg)
  1314. return
  1315. }
  1316. s_params = make([]interface{}, 0)
  1317. paramslist = strings.Split(p2, ",")
  1318. if len(paramslist) > 0 && p2 != "" {
  1319. for _, value := range paramslist {
  1320. if value == "ID" {
  1321. id := parammaps.Get("ID").ValueStr()
  1322. pastureid := parammaps.Get("pastureid").ValueStr()
  1323. 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
  1324. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1325. if err != nil {
  1326. logging.Error("PostRJSBData err: ", err)
  1327. msg := geterrmsg(err.Error())
  1328. appG.Response(http.StatusOK, e.ERROR, msg)
  1329. return
  1330. }
  1331. for _, item := range datalist {
  1332. id = item["id"]
  1333. }
  1334. s_params = append(s_params, id)
  1335. } else {
  1336. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1337. }
  1338. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1339. }
  1340. }
  1341. _, err = tx.SQL(sql2, s_params...).Execute()
  1342. if err != nil {
  1343. logging.Error("PostRJSBData2 err: ", err)
  1344. msg := geterrmsg(err.Error())
  1345. appG.Response(http.StatusOK, e.ERROR, msg)
  1346. return
  1347. }
  1348. s_params = make([]interface{}, 0)
  1349. paramslist = strings.Split(p3, ",")
  1350. if len(paramslist) > 0 && p3 != "" {
  1351. for _, value := range paramslist {
  1352. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1353. }
  1354. }
  1355. _, err = tx.SQL(sql3, s_params...).Execute()
  1356. if err != nil {
  1357. logging.Error("PostRJSBData3 err: ", err)
  1358. msg := geterrmsg(err.Error())
  1359. appG.Response(http.StatusOK, e.ERROR, msg)
  1360. return
  1361. }
  1362. }
  1363. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1364. }
  1365. // @Summary 根据APISQL表中SQL执行得到数据集
  1366. // @Tags ExecDataByConfig
  1367. // @Accept json
  1368. // @Produce json
  1369. // @Param sqlname query string true "sqlname"
  1370. // @Param offset query int true "offset"
  1371. // @Param pagecount query int true "pagecount"
  1372. // @Param returntype query string true "returntype"
  1373. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1374. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1375. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1376. // @Router /data/PostDataByName [POST]
  1377. func ExecDataByConfig(c *gin.Context) {
  1378. appG := app.Gin{C: c}
  1379. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1380. tempval_ := make(map[string]interface{})
  1381. tempCommon := make(map[string]interface{})
  1382. tempval := make([]map[string]interface{}, 0)
  1383. err := json.Unmarshal(dataByte, &tempval_)
  1384. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1385. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1386. if err != nil {
  1387. } else {
  1388. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1389. tempCommon = v
  1390. }
  1391. if v, ok := tempval_["data"].([]interface{}); ok {
  1392. for _, Tvalue := range v {
  1393. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1394. tempval = append(tempval, v1)
  1395. }
  1396. }
  1397. }
  1398. tx := restful.Engine.NewSession()
  1399. err := tx.Begin()
  1400. if err != nil {
  1401. logging.Error("tx.Begin 事务启动失败__error:", err)
  1402. }
  1403. defer func() {
  1404. switch {
  1405. case err != nil:
  1406. if tx != nil {
  1407. tx.Rollback()
  1408. }
  1409. default:
  1410. if tx != nil {
  1411. err = tx.Commit()
  1412. }
  1413. }
  1414. if tx != nil {
  1415. tx.Close()
  1416. }
  1417. }()
  1418. if err == nil {
  1419. if tempv, exists := c.Get("jwt_username"); exists {
  1420. tempCommon["jwt_username"] = tempv.(string)
  1421. }
  1422. for _, paramvalue := range tempval {
  1423. fmt.Println(paramvalue["name"])
  1424. if paramvalue["name"].(string) == "updateBigFP" {
  1425. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1426. if err != nil {
  1427. msg := geterrmsg(err.Error())
  1428. appG.Response(http.StatusOK, e.ERROR, msg)
  1429. return
  1430. }
  1431. }
  1432. }
  1433. for _, paramvalue := range tempval {
  1434. if _, ok := paramvalue["resultname"]; !ok {
  1435. paramvalue["resultname"] = paramvalue["name"]
  1436. }
  1437. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1438. if err != nil {
  1439. logging.Error("ExecDataParam error:", err)
  1440. break
  1441. }
  1442. // if paramvalue["name"].(string) == "createdownloadedplan" {
  1443. // checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1444. // }
  1445. }
  1446. if err == nil {
  1447. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1448. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1449. } else {
  1450. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1451. }
  1452. } else {
  1453. msg := geterrmsg(err.Error())
  1454. appG.Response(http.StatusOK, e.ERROR, msg)
  1455. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1456. }
  1457. }
  1458. }
  1459. if err != nil {
  1460. msg := geterrmsg(err.Error())
  1461. appG.Response(http.StatusOK, e.ERROR, msg)
  1462. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1463. }
  1464. }
  1465. func interfacetostring(val interface{}) string {
  1466. switch val.(type) {
  1467. case string:
  1468. ss := val.(string)
  1469. return ss
  1470. break
  1471. case int:
  1472. ss := val.(int)
  1473. return strconv.Itoa(ss)
  1474. break
  1475. case int64:
  1476. ss := val.(int64)
  1477. return strconv.FormatInt(ss, 10)
  1478. break
  1479. case float64:
  1480. ss := val.(float64)
  1481. return strconv.FormatFloat(ss, 'E', -1, 32)
  1482. break
  1483. }
  1484. return ""
  1485. }
  1486. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1487. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1488. tempstrb := strings.IndexAny(valuestring, "@")
  1489. tempstre := strings.IndexAny(valuestring, ".")
  1490. if tempstrb > -1 && tempstre > -1 {
  1491. for _, ParamMapList := range ParamMap {
  1492. if v, ok := ParamMapList["resultname"]; ok {
  1493. if v == valuestring[tempstrb+1:tempstre] {
  1494. if v1, ok := ParamMapList["resultmaps"]; ok {
  1495. if newA, ok := v1.([]map[string]interface{}); ok {
  1496. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1497. } else if newA, ok := v1.(map[string]interface{}); ok {
  1498. return interfacetostring(newA[valuestring[tempstre+1:]])
  1499. }
  1500. }
  1501. }
  1502. }
  1503. }
  1504. } else {
  1505. return valuestring
  1506. }
  1507. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1508. return fmt.Sprintf("%f", valuestring)
  1509. }
  1510. return ""
  1511. }
  1512. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1513. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1514. tempstrb := strings.IndexAny(valuestring, "@")
  1515. tempstre := strings.IndexAny(valuestring, ".")
  1516. if tempstrb > -1 && tempstre > -1 {
  1517. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1518. if s, ok := v.(string); ok {
  1519. return s
  1520. } else if s, ok := v.(float64); ok {
  1521. return strconv.FormatFloat(s, 'f', -1, 64)
  1522. // return strconv.FormatInt(int64(s), 10)
  1523. }
  1524. }
  1525. }
  1526. }
  1527. return ""
  1528. }
  1529. 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) {
  1530. sqlname := fasion["name"].(string)
  1531. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1532. if v, ok := fasion["type"]; ok {
  1533. sqltype = v.(string)
  1534. }
  1535. sql := ""
  1536. p := ""
  1537. s_params := make([]interface{}, 0)
  1538. if sqltype != "" {
  1539. sql, p = restful.GetSqlByName(sqlname, tx)
  1540. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1541. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1542. paramslist := strings.Split(p, ",")
  1543. if len(paramslist) > 0 && p != "" {
  1544. for _, value := range paramslist {
  1545. ss := ""
  1546. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1547. ids, err := setting.SnowIds.NextId()
  1548. if err != nil {
  1549. ids = time.Now().UnixNano()
  1550. logging.Info("create SnowIds err", err)
  1551. }
  1552. s_params = append(s_params, ids)
  1553. } else {
  1554. if ss == "" && CommonParamMap != nil {
  1555. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1556. ss = valuestring
  1557. tempstrb := strings.IndexAny(valuestring, "@")
  1558. tempstre := strings.IndexAny(valuestring, ".")
  1559. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1560. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1561. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1562. }
  1563. } else {
  1564. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1565. ss = ""
  1566. }
  1567. }
  1568. }
  1569. }
  1570. if ss == "" && ParentParamMap != nil {
  1571. ss = getParamValue_(v, value, ParentParamMap)
  1572. }
  1573. if ss == "" && sameParamMap != nil {
  1574. ss = getParamValue(v, value, sameParamMap)
  1575. }
  1576. if ss == "" && ParamMap != nil {
  1577. ss = getParamValue(v, value, ParamMap)
  1578. }
  1579. s_params = append(s_params, ss)
  1580. }
  1581. }
  1582. }
  1583. }
  1584. }
  1585. if sql == "" {
  1586. sqltype = ""
  1587. }
  1588. if sqltype == "s1" {
  1589. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1590. if v, ok := tempValParam.(map[string]interface{}); ok {
  1591. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1592. }
  1593. if err != nil {
  1594. return nil, err
  1595. }
  1596. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1597. if err != nil {
  1598. return nil, err
  1599. }
  1600. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1601. } else if sqltype == "sm" {
  1602. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1603. if v, ok := tempValParam.(map[string]interface{}); ok {
  1604. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1605. } else {
  1606. }
  1607. if err != nil {
  1608. return nil, err
  1609. }
  1610. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1611. if err != nil {
  1612. return nil, err
  1613. }
  1614. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1615. } else if sqltype == "v" {
  1616. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1617. if v, ok := tempValParam.(map[string]interface{}); ok {
  1618. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1619. } else {
  1620. }
  1621. if err != nil {
  1622. return nil, err
  1623. }
  1624. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1625. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1626. }
  1627. } else if sqltype == "e" {
  1628. tempVal_arrary := make([]map[string]interface{}, 0)
  1629. tempVal_map := make(map[string]interface{})
  1630. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1631. if err == nil {
  1632. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1633. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1634. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1635. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1636. return tempVal_arrary, err
  1637. }
  1638. return nil, err
  1639. } else {
  1640. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1641. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1642. if err != nil {
  1643. return nil, err
  1644. }
  1645. return nil, err
  1646. }
  1647. }
  1648. return nil, nil
  1649. }
  1650. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1651. var err error
  1652. subarray, ok := fasion["children"]
  1653. if ok {
  1654. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1655. tempVal_arrary := make([]map[string]interface{}, 0)
  1656. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1657. tempVal_ := make(map[string]interface{})
  1658. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1659. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1660. } else {
  1661. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1662. }
  1663. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1664. if err != nil {
  1665. return err
  1666. }
  1667. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1668. }
  1669. v.(map[string]interface{})["children"] = tempVal_arrary
  1670. }
  1671. }
  1672. return nil
  1673. }
  1674. // @Summary 删除图片
  1675. // @Tags RemovePicByName
  1676. // @Accept json
  1677. // @Produce json
  1678. // @Param sqlname query string true "sqlname"
  1679. // @Param offset query int true "offset"
  1680. // @Param pagecount query int true "pagecount"
  1681. // @Param returntype query string true "returntype"
  1682. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1683. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1684. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1685. // @Router /data/PostDataByName [POST]
  1686. func RemovePicByName(c *gin.Context) {
  1687. logging.Info("RemovePicByName ", c.Keys)
  1688. appG := app.Gin{C: c}
  1689. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1690. fsion := gofasion.NewFasion(string(dataByte))
  1691. sqlnamestr := fsion.Get("name").ValueStr()
  1692. picname := fsion.Get("picname").ValueStr()
  1693. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1694. params := fsion.Get("params").Array()
  1695. s_params := make([]interface{}, 0)
  1696. for _, v_params := range params {
  1697. s_params = append(s_params, v_params.ValueStr())
  1698. }
  1699. if sql != "" {
  1700. queryData, err := execDataBySql(sql, s_params)
  1701. if picname != "" {
  1702. // Destination
  1703. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1704. err := os.Remove(distPath) //删除文件test.txt
  1705. if err != nil {
  1706. //如果删除失败则输出 file remove Error!
  1707. fmt.Println("file remove Error!")
  1708. //输出错误详细信息
  1709. fmt.Printf("%s", err)
  1710. } else {
  1711. //如果删除成功则输出 file remove OK!
  1712. fmt.Print("file remove OK!")
  1713. }
  1714. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1715. err = os.Remove(distPath) //删除文件test.txt
  1716. if err != nil {
  1717. //如果删除失败则输出 file remove Error!
  1718. fmt.Println("file remove Error!")
  1719. //输出错误详细信息
  1720. fmt.Printf("%s", err)
  1721. } else {
  1722. //如果删除成功则输出 file remove OK!
  1723. fmt.Print("file remove OK!")
  1724. }
  1725. }
  1726. if err != nil {
  1727. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1728. } else {
  1729. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1730. }
  1731. } else {
  1732. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1733. }
  1734. }
  1735. // @Summary 删除文件
  1736. // @Tags RemoveFileByName
  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 RemoveFileByName(c *gin.Context) {
  1748. appG := app.Gin{C: c}
  1749. id := c.Param("id")
  1750. logging.Info("DownloadFile ", c.Keys, id)
  1751. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1752. if eqdoc == nil {
  1753. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1754. return
  1755. }
  1756. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1757. err = os.Remove(distPath) //删除文件test.txt
  1758. if err != nil {
  1759. //如果删除失败则输出 file remove Error!
  1760. fmt.Println("file remove Error!")
  1761. //输出错误详细信息
  1762. fmt.Printf("%s", err)
  1763. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1764. return
  1765. }
  1766. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1767. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1768. }
  1769. // @Summary 根据APISQL表中SQL执行得到数据集
  1770. // @Tags PostDataByName
  1771. // @Accept json
  1772. // @Produce json
  1773. // @Param sqlname query string true "sqlname"
  1774. // @Param offset query int true "offset"
  1775. // @Param pagecount query int true "pagecount"
  1776. // @Param returntype query string true "returntype"
  1777. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1778. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1779. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1780. // @Router /data/PostDataByName [POST]
  1781. func UpdateDataRelation(c *gin.Context) {
  1782. appG := app.Gin{C: c}
  1783. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1784. fsion := gofasion.NewFasion(string(dataByte))
  1785. tablename := fsion.Get("name").ValueStr()
  1786. dataname := fsion.Get("dataname").ValueStr()
  1787. datavalue := fsion.Get("datavalue").ValueStr()
  1788. valuename := fsion.Get("valuename").ValueStr()
  1789. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1790. values := fsion.Get("values").Array()
  1791. tx := restful.Engine.NewSession()
  1792. err := tx.Begin()
  1793. defer func() {
  1794. switch {
  1795. case err != nil:
  1796. if tx != nil {
  1797. tx.Rollback()
  1798. }
  1799. default:
  1800. if tx != nil {
  1801. err = tx.Commit()
  1802. }
  1803. }
  1804. if tx != nil {
  1805. tx.Close()
  1806. }
  1807. }()
  1808. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1809. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1810. d_params := make([]interface{}, 4)
  1811. d_params[0] = datavalue
  1812. s_params := ""
  1813. for _, v_values := range values {
  1814. d_params[1] = v_values.ValueStr()
  1815. if s_params == "" {
  1816. s_params = v_values.ValueStr()
  1817. } else {
  1818. s_params = s_params + "," + v_values.ValueStr()
  1819. }
  1820. d_params[2] = d_params[1]
  1821. d_params[3] = d_params[0]
  1822. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1823. if err != nil {
  1824. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1825. break
  1826. }
  1827. }
  1828. if s_params != "" {
  1829. deleteSqlstr := "delete from " + tablename + " " +
  1830. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1831. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1832. if err != nil {
  1833. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1834. } else if err == nil {
  1835. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1836. }
  1837. } else {
  1838. deleteSqlstr := "delete from " + tablename + " " +
  1839. " where " + dataname + " = " + datavalue
  1840. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1841. if err != nil {
  1842. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1843. } else if err == nil {
  1844. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1845. }
  1846. }
  1847. }
  1848. // @Summary 根据APISQL表中SQL执行得到数据集
  1849. // @Tags PostDatasByName
  1850. // @Accept json
  1851. // @Produce json
  1852. // @Param sqlname query string true "sqlname"
  1853. // @Param offset query int true "offset"
  1854. // @Param pagecount query int true "pagecount"
  1855. // @Param returntype query string true "returntype"
  1856. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1857. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1858. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1859. // @Router /data/PostDatasByName [POST]
  1860. func PostDataByNames(c *gin.Context) {
  1861. appG := app.Gin{C: c}
  1862. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1863. fsion := gofasion.NewFasion(string(dataByte))
  1864. sqlParams := fsion.Get("array").Array()
  1865. queryData := make(map[string]interface{})
  1866. for _, v := range sqlParams {
  1867. fsion2 := gofasion.NewFasion(v.Json())
  1868. ss := fsion2.Get("name")
  1869. aa := fsion2.Get("params")
  1870. fmt.Println(ss, aa)
  1871. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1872. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1873. if sql == "" {
  1874. errorm := make(map[string]interface{})
  1875. errorm["code"] = e.ERROR
  1876. errorm["message"] = "sql没有找到"
  1877. errorm["param"] = ""
  1878. queryData[fsion2.Get("name").ValueStr()] = errorm
  1879. continue
  1880. } else if sql != "" {
  1881. s_params := make([]interface{}, 0)
  1882. if fsion2.HasKey("parammaps") {
  1883. parammaps := fsion2.Get("parammaps")
  1884. paramslist := strings.Split(p, ",")
  1885. if len(paramslist) > 0 && p != "" {
  1886. for _, value := range paramslist {
  1887. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1888. if tempv, exists := c.Get("jwt_username"); exists {
  1889. s_params = append(s_params, tempv.(string))
  1890. } else {
  1891. s_params = append(s_params, "")
  1892. }
  1893. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1894. ids, err := setting.SnowIds.NextId()
  1895. if err != nil {
  1896. ids = time.Now().UnixNano()
  1897. logging.Info("create SnowIds err", err)
  1898. }
  1899. s_params = append(s_params, ids)
  1900. } else {
  1901. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1902. }
  1903. }
  1904. }
  1905. } else if fsion2.HasKey("params") {
  1906. params := fsion2.Get("params").Array()
  1907. //ids,err := setting.SnowIds.NextId()
  1908. //if err !=nil{
  1909. // ids = time.Now().UnixNano()
  1910. // logging.Info("create SnowIds err",err)
  1911. //}
  1912. //s_params = append(s_params, ids)
  1913. for _, v_params := range params {
  1914. s_params = append(s_params, v_params.ValueStr())
  1915. }
  1916. }
  1917. _, err := execDataBySql(sql, s_params)
  1918. if err != nil {
  1919. logging.Error("PostDataByName err: ", err)
  1920. errorm := make(map[string]interface{})
  1921. errorm["code"] = e.ERROR
  1922. errorm["message"] = err.Error()
  1923. errorm["param"] = s_params
  1924. queryData[fsion2.Get("name").ValueStr()] = errorm
  1925. continue
  1926. } else {
  1927. errorm := make(map[string]interface{})
  1928. errorm["code"] = e.SUCCESS
  1929. errorm["message"] = "success"
  1930. queryData[fsion2.Get("name").ValueStr()] = errorm
  1931. continue
  1932. }
  1933. } else {
  1934. errorm := make(map[string]interface{})
  1935. errorm["code"] = e.ERROR
  1936. errorm["message"] = "NO SQL"
  1937. errorm["param"] = ""
  1938. queryData[fsion2.Get("name").ValueStr()] = errorm
  1939. }
  1940. }
  1941. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1942. }
  1943. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1944. if offset > 0 {
  1945. offset = offset - 1
  1946. }
  1947. //if pagecount == 0 {
  1948. // pagecount = setting.AppSetting.PageSize
  1949. //}else if pagecount>setting.AppSetting.PageSize{
  1950. // pagecount = setting.AppSetting.PageSize
  1951. //}
  1952. if returntype == "list" {
  1953. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1954. return queryData, err
  1955. } else if returntype == "listlist" {
  1956. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1957. return queryData, err
  1958. } else {
  1959. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1960. return queryData, err
  1961. }
  1962. }
  1963. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1964. if offset > 0 {
  1965. offset = offset - 1
  1966. }
  1967. //if pagecount == 0 {
  1968. // pagecount = setting.AppSetting.PageSize
  1969. //}else if pagecount>setting.AppSetting.PageSize{
  1970. // pagecount = setting.AppSetting.PageSize
  1971. //}
  1972. if returntype == "list" {
  1973. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1974. return queryData, err
  1975. } else if returntype == "listlist" {
  1976. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1977. return queryData, err
  1978. } else {
  1979. fmt.Println(params)
  1980. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1981. return queryData, err
  1982. }
  1983. }
  1984. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1985. paramslist := strings.Split(Params, ",")
  1986. s_params := make([]interface{}, 0)
  1987. if isList {
  1988. for _, v_params := range thisParams["params"].([]interface{}) {
  1989. s_params = append(s_params, v_params)
  1990. }
  1991. } else {
  1992. paramslist := strings.Split(Params, ",")
  1993. if len(paramslist) > 0 && Params != "" {
  1994. for _, value := range paramslist {
  1995. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1996. }
  1997. }
  1998. }
  1999. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  2000. for _, queryData_ := range queryData {
  2001. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  2002. if isList {
  2003. if queryData_[idname] != nil {
  2004. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  2005. }
  2006. } else {
  2007. if queryData_[idname] != nil {
  2008. thisParams[idname] = queryData_[idname].(interface{})
  2009. }
  2010. if len(paramslist) > 0 && Params != "" {
  2011. s_params = make([]interface{}, 0)
  2012. for _, value := range paramslist {
  2013. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2014. }
  2015. }
  2016. }
  2017. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  2018. } else {
  2019. }
  2020. }
  2021. return queryData, err
  2022. }
  2023. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2024. queryData, err := restful.ExecQuery(sqlstr, params)
  2025. return queryData, err
  2026. }
  2027. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2028. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2029. return queryData, err
  2030. }
  2031. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2032. queryData, err := restful.ExecQuery(sqlstr, params)
  2033. return queryData, err
  2034. }
  2035. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2036. // @Tags ImportExcel
  2037. // @Accept json
  2038. // @Produce json
  2039. // @Param file query string true "文件名"
  2040. // @Param name header string true "执行sql的名字"
  2041. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2042. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2043. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2044. // @Router /data/ImportExcel [POST]
  2045. func ImportExcel(c *gin.Context) {
  2046. appG := app.Gin{C: c}
  2047. inputdata := ""
  2048. c.Request.ParseForm()
  2049. params := c.Request.Form
  2050. file, _, err := c.Request.FormFile("file")
  2051. if err != nil {
  2052. appG.Response(http.StatusOK, e.ERROR, err)
  2053. return
  2054. }
  2055. sqlnamestrs := params.Get("name")
  2056. sheetname := params.Get("sheetname")
  2057. pastureid := params.Get("pastureid")
  2058. //importParams := params.Get("importParams")
  2059. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2060. // 必输项参数 (字符串格式 "field1,field2,field3")
  2061. requiredParams := params.Get("requiredParams")
  2062. // 日期参数
  2063. dateParams := params.Get("dateParams")
  2064. // 数字参数
  2065. numParams := params.Get("numParams")
  2066. //将字符串分割开
  2067. dateParamslist := strings.Split(dateParams, ",")
  2068. requiredParamslist := strings.Split(requiredParams, ",")
  2069. numParamslist := strings.Split(numParams, ",")
  2070. queryData := make([]interface{}, 0)
  2071. sqlslist := strings.Split(sqlnamestrs, ",")
  2072. xlsx1, err := excelize.OpenReader(file)
  2073. if err != nil {
  2074. fmt.Println(err)
  2075. return
  2076. }
  2077. ok := 0
  2078. error := 0
  2079. isdone := true
  2080. rows := xlsx1.GetRows(sheetname)
  2081. // 限制10000条,多余的截取掉
  2082. if len(rows) > 10000 {
  2083. rows = rows[:10000]
  2084. }
  2085. for i, row := range rows {
  2086. if i > 0 {
  2087. entry := make(map[string]interface{})
  2088. outentry := make(map[string]interface{})
  2089. for j, colCell := range rows[0] {
  2090. for k, colCell1 := range row {
  2091. if j == k {
  2092. outentry[colCell] = colCell1
  2093. entry[colCell] = colCell1
  2094. }
  2095. }
  2096. }
  2097. inputdata = ""
  2098. a := ""
  2099. fmt.Println(outentry, entry)
  2100. //校验日期格式
  2101. for _, v := range dateParamslist {
  2102. if v == "" {
  2103. continue
  2104. }
  2105. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2106. dtime, err := TransfTime(d.(string))
  2107. if err != nil {
  2108. a = strings.Trim(v, " ")
  2109. break
  2110. }
  2111. outentry[strings.Trim(v, " ")] = dtime
  2112. }
  2113. }
  2114. if a != "" {
  2115. outentry["error_msg"] = a + " 格式错误"
  2116. error++
  2117. queryData = append(queryData, outentry)
  2118. continue
  2119. }
  2120. a = ""
  2121. //校验必填格式
  2122. for _, v := range requiredParamslist {
  2123. if v == "" {
  2124. continue
  2125. }
  2126. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2127. a = strings.Trim(v, " ")
  2128. break
  2129. }
  2130. }
  2131. if a != "" {
  2132. outentry["error_msg"] = a + " 未填或格式错误"
  2133. error++
  2134. queryData = append(queryData, outentry)
  2135. continue
  2136. }
  2137. a = ""
  2138. //校验数字格式
  2139. for _, v := range numParamslist {
  2140. if v == "" {
  2141. continue
  2142. }
  2143. d, ok := outentry[strings.Trim(v, " ")]
  2144. if !ok || d == "" {
  2145. outentry[strings.Trim(v, " ")] = 0
  2146. } else {
  2147. var fl float64
  2148. switch d.(type) {
  2149. case string:
  2150. fl, err = strconv.ParseFloat(d.(string), 64)
  2151. }
  2152. if err != nil || fl < 0 {
  2153. a = strings.Trim(v, " ")
  2154. break
  2155. }
  2156. }
  2157. }
  2158. if a != "" {
  2159. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2160. error++
  2161. queryData = append(queryData, outentry)
  2162. continue
  2163. }
  2164. tx := restful.Engine.NewSession()
  2165. err := tx.Begin()
  2166. for _, sqlnamestr := range sqlslist {
  2167. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2168. paramslist := strings.Split(paramslists, ",")
  2169. if len(paramslist) > 0 {
  2170. s_params := make([]interface{}, 0)
  2171. for _, value := range paramslist {
  2172. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2173. if tempv, exists := c.Get("jwt_username"); exists {
  2174. s_params = append(s_params, tempv.(string))
  2175. } else {
  2176. s_params = append(s_params, "")
  2177. }
  2178. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2179. s_params = append(s_params, pastureid)
  2180. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2181. ids, err := setting.SnowIds.NextId()
  2182. if err != nil {
  2183. ids = time.Now().UnixNano()
  2184. logging.Info("create SnowIds err", err)
  2185. }
  2186. s_params = append(s_params, ids)
  2187. } else {
  2188. if outentry[strings.Trim(value, " ")] == nil {
  2189. s_params = append(s_params, "")
  2190. } else {
  2191. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2192. }
  2193. }
  2194. }
  2195. outentry["input"] = inputdata
  2196. fmt.Println(sql, s_params)
  2197. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2198. if err != nil {
  2199. if tx != nil {
  2200. tx.Rollback()
  2201. }
  2202. if tx != nil {
  2203. tx.Close()
  2204. }
  2205. msg := geterrmsg(err.Error())
  2206. outentry["error_msg"] = msg
  2207. error++
  2208. queryData = append(queryData, outentry)
  2209. isdone = true
  2210. break
  2211. } else {
  2212. if len(returnmsgmap1) > 0 {
  2213. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2214. if tx != nil {
  2215. tx.Rollback()
  2216. }
  2217. if tx != nil {
  2218. tx.Close()
  2219. }
  2220. msg := geterrmsg(va.(string))
  2221. outentry["error_msg"] = msg
  2222. error++
  2223. queryData = append(queryData, outentry)
  2224. isdone = true
  2225. break
  2226. }
  2227. }
  2228. isdone = false
  2229. }
  2230. }
  2231. }
  2232. switch {
  2233. case err != nil:
  2234. if tx != nil {
  2235. tx.Rollback()
  2236. }
  2237. default:
  2238. if tx != nil {
  2239. err = tx.Commit()
  2240. }
  2241. }
  2242. if tx != nil {
  2243. tx.Close()
  2244. }
  2245. }
  2246. if !isdone {
  2247. ok++
  2248. isdone = true
  2249. }
  2250. }
  2251. data := make(map[string]interface{})
  2252. data["result"] = queryData
  2253. data["success"] = ok
  2254. data["err_count"] = error
  2255. appG.Response(http.StatusOK, e.SUCCESS, data)
  2256. }
  2257. func TransfTime(timestr string) (string, error) {
  2258. if timestr == "" {
  2259. return time.Now().Format("2006-01-02"), nil
  2260. }
  2261. days, err := strconv.Atoi(timestr)
  2262. if err != nil {
  2263. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2264. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2265. }
  2266. _, err := time.Parse("2006-01-02", timestr)
  2267. if err != nil {
  2268. t, err := time.Parse("2006/01/02", timestr)
  2269. if err != nil {
  2270. t, err := time.Parse("2006.01.02", timestr)
  2271. if err != nil {
  2272. return "", err
  2273. } else {
  2274. return t.Format("2006-01-02"), nil
  2275. }
  2276. } else {
  2277. return t.Format("2006-01-02"), nil
  2278. }
  2279. } else {
  2280. return timestr, nil
  2281. }
  2282. }
  2283. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2284. times = times.AddDate(0, 0, days)
  2285. return times.Format("2006-01-02"), nil
  2286. }
  2287. func Createchart(c *gin.Context) {
  2288. appG := app.Gin{C: c}
  2289. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2290. fsion := gofasion.NewFasion(string(dataByte))
  2291. chart_name := fsion.Get("chart_name").ValueStr()
  2292. desc := fsion.Get("desc").ValueStr()
  2293. pastureid := fsion.Get("pastureid").ValueStr()
  2294. source_id := fsion.Get("source_id").ValueStr()
  2295. emp := fsion.Get("emp").ValueStr()
  2296. content := fsion.Get("content").Json()
  2297. var mapResult map[string]interface{}
  2298. err1 := json.Unmarshal([]byte(content), &mapResult)
  2299. if err1 != nil {
  2300. fmt.Println("JsonToMapDemo err: ", err1)
  2301. }
  2302. tx := restful.Engine.NewSession()
  2303. err := tx.Begin()
  2304. defer func() {
  2305. switch {
  2306. case err != nil:
  2307. logging.Error("tx.Begin 事务启动失败__error:", err)
  2308. if tx != nil {
  2309. tx.Rollback()
  2310. }
  2311. default:
  2312. if tx != nil {
  2313. err = tx.Commit()
  2314. }
  2315. }
  2316. if tx != nil {
  2317. tx.Close()
  2318. }
  2319. }()
  2320. ids, err := setting.SnowIds.NextId()
  2321. if err != nil {
  2322. ids = time.Now().UnixNano()
  2323. logging.Info("create SnowIds err", err)
  2324. }
  2325. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2326. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2327. if err != nil {
  2328. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2329. } else {
  2330. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2331. }
  2332. }
  2333. func Updatedashboard(c *gin.Context) {
  2334. appG := app.Gin{C: c}
  2335. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2336. fsion := gofasion.NewFasion(string(dataByte))
  2337. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2338. pastureid := fsion.Get("pastureid").ValueStr()
  2339. content := fsion.Get("content").Json()
  2340. var mapResult map[string]interface{}
  2341. err1 := json.Unmarshal([]byte(content), &mapResult)
  2342. if err1 != nil {
  2343. fmt.Println("JsonToMapDemo err: ", err1)
  2344. }
  2345. layout := mapResult["layout"]
  2346. tx := restful.Engine.NewSession()
  2347. err := tx.Begin()
  2348. defer func() {
  2349. switch {
  2350. case err != nil:
  2351. logging.Error("tx.Begin 事务启动失败__error:", err)
  2352. if tx != nil {
  2353. tx.Rollback()
  2354. }
  2355. default:
  2356. if tx != nil {
  2357. err = tx.Commit()
  2358. }
  2359. }
  2360. if tx != nil {
  2361. tx.Close()
  2362. }
  2363. }()
  2364. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2365. if err != nil {
  2366. println("2", err.Error())
  2367. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2368. } else {
  2369. if exec != nil {
  2370. if exec[0]["content"] == nil {
  2371. mapR := make(map[string]interface{})
  2372. mapR["layout"] = layout
  2373. mjson, _ := json.Marshal(mapR)
  2374. mString := string(mjson)
  2375. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2376. if err3 != nil {
  2377. println("3", err3.Error())
  2378. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2379. } else {
  2380. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2381. }
  2382. } else {
  2383. var mapR map[string]interface{}
  2384. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2385. if err1 != nil {
  2386. fmt.Println("JsonToMapDemo err: ", err2)
  2387. }
  2388. mapR["layout"] = layout
  2389. mjson, _ := json.Marshal(mapR)
  2390. mString := string(mjson)
  2391. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2392. if err3 != nil {
  2393. println("3", err3.Error())
  2394. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2395. } else {
  2396. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2397. }
  2398. }
  2399. } else {
  2400. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2401. }
  2402. }
  2403. }
  2404. func ExecSQL(c *gin.Context) {
  2405. appG := app.Gin{C: c}
  2406. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2407. fsion := gofasion.NewFasion(string(dataByte))
  2408. content := fsion.Get("content").Json()
  2409. pastureid := fsion.Get("pastureid").ValueStr()
  2410. var mapResult map[string]interface{}
  2411. err1 := json.Unmarshal([]byte(content), &mapResult)
  2412. if err1 != nil {
  2413. fmt.Println("JsonToMapDemo err: ", err1)
  2414. }
  2415. sqlstr := "select "
  2416. groupstr := " GROUP BY "
  2417. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2418. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2419. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2420. }
  2421. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2422. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2423. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2424. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2425. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2426. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2427. sqlstr = sqlstr + tem + ","
  2428. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2429. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2430. sqlstr = sqlstr + tem + ","
  2431. } else {
  2432. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2433. sqlstr = sqlstr + tem + ","
  2434. }
  2435. }
  2436. if _, ok := mapResult["selectedCalcul2"]; ok {
  2437. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2438. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2439. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2440. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2441. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2442. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2443. sqlstr = sqlstr + tem + ","
  2444. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2445. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2446. sqlstr = sqlstr + tem + ","
  2447. } else {
  2448. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2449. sqlstr = sqlstr + tem + ","
  2450. }
  2451. }
  2452. }
  2453. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2454. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2455. sqlstr = sqlstr + " where pastureid=" + pastureid
  2456. if len(mapResult["filters"].([]interface{})) > 0 {
  2457. sqlstr = sqlstr + " and "
  2458. }
  2459. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2460. for _, value := range mapResult["filters"].([]interface{}) {
  2461. switch value.(map[string]interface{})["filterOperator"].(string) {
  2462. case ">", "=", "<", ">=", "<=", "!=", "like":
  2463. 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 "
  2464. case "IN":
  2465. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2466. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2467. sqlstr = sqlstr + value1.(string) + ","
  2468. }
  2469. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2470. sqlstr = sqlstr + ")" + " AND "
  2471. case "BETWEEN":
  2472. 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 "
  2473. }
  2474. }
  2475. if len(mapResult["filters"].([]interface{})) > 0 {
  2476. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2477. }
  2478. //
  2479. groupstr = groupstr[0 : len(groupstr)-1]
  2480. sqlstr = sqlstr + groupstr + " "
  2481. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2482. sqlstr = sqlstr + " order by "
  2483. }
  2484. //
  2485. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2486. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2487. sqlstr = sqlstr + value.(string) + " "
  2488. } else {
  2489. sqlstr = sqlstr + value.(string) + ","
  2490. }
  2491. }
  2492. //
  2493. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2494. tx := restful.Engine.NewSession()
  2495. err := tx.Begin()
  2496. defer func() {
  2497. switch {
  2498. case err != nil:
  2499. logging.Error("tx.Begin 事务启动失败__error:", err)
  2500. if tx != nil {
  2501. tx.Rollback()
  2502. }
  2503. default:
  2504. if tx != nil {
  2505. err = tx.Commit()
  2506. }
  2507. }
  2508. if tx != nil {
  2509. tx.Close()
  2510. }
  2511. }()
  2512. exec, err := tx.SQL(sqlstr).Query().List()
  2513. if err != nil {
  2514. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2515. } else {
  2516. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2517. }
  2518. }
  2519. func Dashboards(c *gin.Context) {
  2520. appG := app.Gin{C: c}
  2521. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2522. fsion := gofasion.NewFasion(string(dataByte))
  2523. sqlnamestr := fsion.Get("name").ValueStr()
  2524. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2525. offset := fsion.Get("offset").ValueDefaultInt(0)
  2526. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2527. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2528. month := fsion.Get("month").ValueDefaultStr("map")
  2529. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2530. tx := restful.Engine.NewSession()
  2531. err := tx.Begin()
  2532. defer func() {
  2533. switch {
  2534. case err != nil:
  2535. if tx != nil {
  2536. tx.Rollback()
  2537. }
  2538. default:
  2539. if tx != nil {
  2540. err = tx.Commit()
  2541. }
  2542. }
  2543. if tx != nil {
  2544. tx.Close()
  2545. }
  2546. }()
  2547. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2548. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2549. if sql != "" {
  2550. s_params := make([]interface{}, 0)
  2551. if fsion.HasKey("parammaps") {
  2552. parammaps := fsion.Get("parammaps")
  2553. paramslist := strings.Split(p, ",")
  2554. if len(paramslist) > 0 && p != "" {
  2555. for _, value := range paramslist {
  2556. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2557. if tempv, exists := c.Get("jwt_username"); exists {
  2558. s_params = append(s_params, tempv.(string))
  2559. } else {
  2560. s_params = append(s_params, "")
  2561. }
  2562. } else {
  2563. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2564. }
  2565. }
  2566. }
  2567. }
  2568. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2569. if err != nil {
  2570. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2571. } else {
  2572. //paramslist1 := strings.Split(p1, ",")
  2573. dids := make([]interface{}, 0)
  2574. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2575. var mapResult map[string]interface{}
  2576. dids = append(dids, value["dashboard_id"])
  2577. if value["content"] != nil {
  2578. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2579. if err1 != nil {
  2580. println("JsonToMapDemo1 err: ", err1)
  2581. }
  2582. temap := make(map[string]interface{})
  2583. tem := mapResult["layout"].([]interface{})
  2584. if v, ok := value["chartids"]; ok {
  2585. chartids := strings.Split(v.(string), ",")
  2586. for _, va := range chartids {
  2587. a := false
  2588. for _, v2 := range tem {
  2589. if v2.(map[string]interface{})["id"].(string) == va {
  2590. a = true
  2591. //println("va1======",va)
  2592. }
  2593. }
  2594. if !a {
  2595. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2596. va + "\",\"id\":\"" + va +
  2597. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2598. var mapTem map[string]interface{}
  2599. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2600. if err1 != nil {
  2601. println("JsonToMapDemo err: ", err1)
  2602. }
  2603. tem = append(tem, mapTem)
  2604. }
  2605. }
  2606. temap["layout"] = tem
  2607. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2608. }
  2609. } else {
  2610. temap := make(map[string]interface{})
  2611. tem := make([]interface{}, 0)
  2612. if v, ok := value["chartids"]; ok {
  2613. chartids := strings.Split(v.(string), ",")
  2614. for _, va := range chartids {
  2615. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2616. va + "\",\"id\":\"" + va +
  2617. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2618. var mapTem map[string]interface{}
  2619. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2620. if err1 != nil {
  2621. println("JsonToMapDemo err: ", err1)
  2622. }
  2623. tem = append(tem, mapTem)
  2624. }
  2625. temap["layout"] = tem
  2626. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2627. }
  2628. }
  2629. }
  2630. queryData.(map[string]interface{})["order"] = dids
  2631. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2632. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2633. }
  2634. } else {
  2635. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2636. }
  2637. }
  2638. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2639. fsion := gofasion.NewFasion(parammaps)
  2640. sqlnamestr := fsion.Get("name").ValueStr()
  2641. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2642. offset := fsion.Get("offset").ValueDefaultInt(0)
  2643. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2644. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2645. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2646. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2647. body := []byte("")
  2648. if sql != "" {
  2649. s_params := make([]interface{}, 0)
  2650. if fsion.HasKey("parammaps") {
  2651. parammaps := fsion.Get("parammaps")
  2652. paramslist := strings.Split(p, ",")
  2653. if len(paramslist) > 0 && p != "" {
  2654. for _, value := range paramslist {
  2655. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2656. }
  2657. }
  2658. }
  2659. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2660. if err != nil {
  2661. } else {
  2662. paramslist1 := strings.Split(p1, ",")
  2663. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2664. s_params1 := make([]interface{}, 0)
  2665. if len(paramslist1) > 0 && p1 != "" {
  2666. for _, v := range paramslist1 {
  2667. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2668. }
  2669. }
  2670. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2671. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2672. body, _ = json.Marshal(queryData)
  2673. }
  2674. }
  2675. }
  2676. bs := bytes.NewBuffer(body)
  2677. client := &http.Client{}
  2678. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2679. req, err := http.NewRequest(RequestMethod,
  2680. url,
  2681. bs,
  2682. )
  2683. if err != nil {
  2684. }
  2685. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2686. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2687. if err != nil {
  2688. // handle error
  2689. }
  2690. resp, err := client.Do(req)
  2691. if err != nil {
  2692. return ""
  2693. }
  2694. defer resp.Body.Close()
  2695. result_body, err := ioutil.ReadAll(resp.Body)
  2696. if err != nil {
  2697. return ""
  2698. }
  2699. fmt.Println(string(result_body))
  2700. return ""
  2701. }
  2702. func GetSummary(c *gin.Context) {
  2703. appG := app.Gin{C: c}
  2704. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2705. fsion := gofasion.NewFasion(string(dataByte))
  2706. offset := fsion.Get("offset").ValueDefaultInt(0)
  2707. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2708. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2709. parammaps := fsion.Get("parammaps")
  2710. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2711. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2712. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2713. tx := restful.Engine.NewSession()
  2714. defer tx.Close()
  2715. sqlnamestr := ""
  2716. if genre == "0" {
  2717. if status == "0" {
  2718. sqlnamestr = "getAccuracyJSY"
  2719. } else if status == "1" {
  2720. sqlnamestr = "getAccuracyHFT"
  2721. } else if status == "2" {
  2722. sqlnamestr = "getAccuracyHNS"
  2723. } else if status == "3" {
  2724. sqlnamestr = "getAccuracyHSC"
  2725. } else if status == "4" {
  2726. sqlnamestr = "getAccuracyHCC"
  2727. } else if status == "5" {
  2728. sqlnamestr = "getAccuracyMC"
  2729. } else if status == "6" {
  2730. sqlnamestr = "getAccuracyFeedHL"
  2731. } else if status == "7" {
  2732. sqlnamestr = "getAccuracyRT"
  2733. }
  2734. } else {
  2735. if status == "0" {
  2736. sqlnamestr = "getAccuracySCCJSY"
  2737. } else if status == "1" {
  2738. sqlnamestr = "getAccuracySFT"
  2739. } else if status == "2" {
  2740. sqlnamestr = "getAccuracySNS"
  2741. } else if status == "3" {
  2742. sqlnamestr = "getAccuracySSC"
  2743. } else if status == "4" {
  2744. sqlnamestr = "getAccuracySCC"
  2745. } else if status == "5" {
  2746. sqlnamestr = "getAccuracySLCL"
  2747. } else if status == "7" {
  2748. sqlnamestr = "getAccuracySCCRT"
  2749. }
  2750. }
  2751. if isDate == "1" {
  2752. sqlnamestr += "Date"
  2753. }
  2754. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2755. // fmt.Println(sqlnamestr, sql)
  2756. if sql != "" {
  2757. s_params := make([]interface{}, 0)
  2758. // if fsion.HasKey("parammaps") {
  2759. fmt.Println(s_params, "222", p)
  2760. paramslist := strings.Split(p, ",")
  2761. if len(paramslist) > 0 && p != "" {
  2762. for _, value := range paramslist {
  2763. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2764. if tempv, exists := c.Get("jwt_username"); exists {
  2765. s_params = append(s_params, tempv.(string))
  2766. } else {
  2767. s_params = append(s_params, "")
  2768. }
  2769. } else {
  2770. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2771. }
  2772. }
  2773. }
  2774. if returntype == "xlsx" {
  2775. var xlsxfile *xlsx.File
  2776. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2777. //c.File("c:/dd.xlsx")
  2778. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2779. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2780. c.Header("Content-Transfer-Encoding", "binary")
  2781. _ = xlsxfile.Write(c.Writer)
  2782. } else {
  2783. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2784. if err != nil {
  2785. logging.Error("GetDataByName err: ", err)
  2786. msg := geterrmsg(err.Error())
  2787. appG.Response(http.StatusOK, e.ERROR, msg)
  2788. } else {
  2789. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2790. }
  2791. }
  2792. } else {
  2793. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2794. }
  2795. }
  2796. // type lpplanStruct struct {
  2797. // Id int64 `xorm:"id"`
  2798. // Tmrname string `xorm:"tmrname"`
  2799. // Tmrid int64 `xorm:"tmrid"`
  2800. // Sort int64 `xorm:"sort"`
  2801. // Sel int64 `xorm:"sel"`
  2802. // Times int64 `xorm:"times"`
  2803. // Ftname string `xorm:"ftname"`
  2804. // Ftid int64 `xorm:"ftid"`
  2805. // Maxweight float64 `xorm:"maxweight"`
  2806. // Sumweight float64 `xorm:"sumweight"`
  2807. // Sumcowcount int64 `xorm:"sumcowcount"`
  2808. // Pastureid string `xorm:"pastureid"`
  2809. // Display string `xorm:"display"`
  2810. // Issplit int64 `xorm:"issplit"`
  2811. // BeginTime string `xorm:"begintime"`
  2812. // }
  2813. func UpdateFTdetail(c *gin.Context) {
  2814. appG := app.Gin{C: c}
  2815. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2816. tempval_ := make(map[string]interface{})
  2817. tempCommon := make(map[string]interface{})
  2818. tempval := make([]map[string]interface{}, 0)
  2819. fTChange := make(map[string]interface{}, 0)
  2820. fpdOldDataList := make([]map[string]interface{}, 0)
  2821. fpdDataList := make([]map[string]interface{}, 0)
  2822. fsion := gofasion.NewFasion(string(dataByte))
  2823. // parammaps := fsion.Get("parammaps")
  2824. createdate := time.Now().Format("2006-01-02 15:04:05")
  2825. err := json.Unmarshal(dataByte, &tempval_)
  2826. if err != nil {
  2827. appG.Response(http.StatusOK, e.ERROR, false)
  2828. return
  2829. }
  2830. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2831. tx := restful.Engine.NewSession()
  2832. if v, ok := tempval_["data"].([]interface{}); ok {
  2833. for _, Tvalue := range v {
  2834. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2835. if v1["name"] == "updateFPbyFTChange" {
  2836. fTChange = v1
  2837. continue
  2838. }
  2839. tempval = append(tempval, v1)
  2840. }
  2841. }
  2842. }
  2843. parammaps := fTChange["parammaps"].(map[string]interface{})
  2844. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2845. // if err != nil {
  2846. // logs.Error(err)
  2847. // appG.Response(http.StatusOK, e.ERROR, false)
  2848. // return
  2849. // }
  2850. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2851. // if err != nil {
  2852. // logs.Error(err)
  2853. // appG.Response(http.StatusOK, e.ERROR, false)
  2854. // return
  2855. // }
  2856. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2857. // if err != nil {
  2858. // logs.Error(err)
  2859. // appG.Response(http.StatusOK, e.ERROR, false)
  2860. // return
  2861. // }
  2862. err = tx.Begin()
  2863. if err != nil {
  2864. logging.Error("tx.Begin 事务启动失败__error:", err)
  2865. }
  2866. defer func() {
  2867. if err != nil {
  2868. if tx != nil {
  2869. tx.Rollback()
  2870. }
  2871. }
  2872. if tx != nil {
  2873. tx.Close()
  2874. }
  2875. }()
  2876. if err != nil {
  2877. } else {
  2878. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2879. tempCommon = v
  2880. }
  2881. 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 ,
  2882. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2883. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2884. UNION
  2885. 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 ,
  2886. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2887. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2888. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2889. if err == nil {
  2890. if tempv, exists := c.Get("jwt_username"); exists {
  2891. tempCommon["jwt_username"] = tempv.(string)
  2892. }
  2893. for _, paramvalue := range tempval {
  2894. if _, ok := paramvalue["resultname"]; !ok {
  2895. paramvalue["resultname"] = paramvalue["name"]
  2896. }
  2897. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2898. if err != nil {
  2899. logging.Error("ExecDataParam error:", err)
  2900. break
  2901. }
  2902. }
  2903. if err != nil {
  2904. msg := geterrmsg(err.Error())
  2905. appG.Response(http.StatusOK, e.ERROR, msg)
  2906. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2907. }
  2908. }
  2909. }
  2910. tx.Commit()
  2911. // go func() {
  2912. if fTChange != nil {
  2913. parammaps := fTChange["parammaps"].(map[string]interface{})
  2914. if parammaps["type"].(float64) == 1 {
  2915. _, err = tx.SQL(`UPDATE feedp fp
  2916. set
  2917. ccountratio = ccount *(ratio /100 ),
  2918. fp.ftweight= IFNULL(IF(
  2919. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2920. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2921. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2922. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2923. ),0),fp.feedweight = IFNULL(IF(
  2924. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2925. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2926. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2927. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2928. ),0) +ifnull(fp.supplyweight,0)
  2929. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2930. _, err = tx.SQL(`UPDATE fpdetail fpd
  2931. INNER JOIN feedp fp
  2932. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2933. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2934. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2935. } else {
  2936. _, err = tx.SQL(`UPDATE feedp fp
  2937. SET ccountratio = ccount *(ratio /100 ),
  2938. fp.supplyweight= IFNULL(IF(
  2939. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2940. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2941. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2942. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2943. ),0),fp.feedweight = IFNULL(IF(
  2944. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2945. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2946. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2947. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2948. ),0) +ifnull(fp.supplyweight,0)
  2949. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2950. _, err = tx.SQL(`UPDATE fpdetail fpd
  2951. INNER JOIN feedp fp
  2952. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2953. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2954. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2955. }
  2956. 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 ,
  2957. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2958. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2959. UNION
  2960. 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 ,
  2961. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2962. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2963. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2964. lpplanList := make([]*lpplanStruct, 0)
  2965. err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2966. if err != nil {
  2967. logs.Error(err, 1)
  2968. return
  2969. }
  2970. lppidlist := []string{}
  2971. for _, lpp := range lpplanList {
  2972. lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2973. }
  2974. if len(lppidlist) <= 0 {
  2975. appG.Response(http.StatusOK, e.SUCCESS, true)
  2976. return
  2977. }
  2978. lpplandtl1AllList := make([]*lpplandtl1, 0)
  2979. err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  2980. order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  2981. if err != nil {
  2982. // tx.Rollback()
  2983. logs.Error(err, 2, parammaps["pastureid"])
  2984. return
  2985. }
  2986. // for _, lpp := range lpplandtl1AllList {
  2987. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  2988. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  2989. // if err != nil {
  2990. // logs.Error(err)
  2991. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  2992. // return
  2993. // }
  2994. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  2995. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  2996. // if err != nil {
  2997. // logs.Error(err)
  2998. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  2999. // return
  3000. // }
  3001. // }
  3002. var wg sync.WaitGroup
  3003. for _, old := range fpdOldDataList {
  3004. for _, fpd := range fpdDataList {
  3005. wg.Add(1)
  3006. go func(old, fpd map[string]interface{}) {
  3007. updateLppandList := make([]*lpplandtl1, 0)
  3008. defer wg.Done()
  3009. if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3010. fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3011. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3012. oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3013. // if weight > oldweight {
  3014. // return
  3015. // }
  3016. var w float64
  3017. var status int
  3018. if weight < oldweight {
  3019. if weight >= 0 {
  3020. return
  3021. }
  3022. w = weight
  3023. status = 0
  3024. } else {
  3025. if oldweight > 0 {
  3026. return
  3027. }
  3028. w = weight
  3029. status = 1
  3030. }
  3031. // fweight = w
  3032. for _, lpp := range lpplanList {
  3033. var fweight float64
  3034. var lweight float64
  3035. lpplandtl1List := make([]*lpplandtl1, 0)
  3036. fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3037. for _, lppland := range lpplandtl1AllList {
  3038. if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3039. lpplandtl1List = append(lpplandtl1List, lppland)
  3040. }
  3041. }
  3042. if len(lpplandtl1List) == 0 {
  3043. continue
  3044. }
  3045. for _, lppland := range lpplandtl1List {
  3046. lweight += lppland.Lweight
  3047. }
  3048. if status == 0 {
  3049. if lweight <= 0 {
  3050. continue
  3051. }
  3052. } else {
  3053. if lpp.Maxweight <= lweight {
  3054. continue
  3055. }
  3056. }
  3057. for _, lppland := range lpplandtl1List {
  3058. if fpdid == lppland.Fpdid {
  3059. if status == 1 {
  3060. // if w <= lppland.Lweight {
  3061. if lpp.Maxweight <= lweight {
  3062. continue
  3063. }
  3064. if w+lweight <= lpp.Maxweight {
  3065. lppland.Lweight += w
  3066. lweight += w
  3067. fweight += w
  3068. w = 0
  3069. } else {
  3070. w = w - (lpp.Maxweight - lweight)
  3071. n := (lpp.Maxweight - lweight)
  3072. lppland.Lweight = lppland.Lweight + n
  3073. lweight += n
  3074. fweight += n
  3075. }
  3076. } else {
  3077. if lppland.Lweight == 0 {
  3078. continue
  3079. }
  3080. if w+lppland.Lweight >= 0 {
  3081. lppland.Lweight = lppland.Lweight + w
  3082. lweight = lweight + w
  3083. fweight = fweight + w
  3084. w = 0
  3085. } else {
  3086. w = w + lppland.Lweight
  3087. lweight = lweight - lppland.Lweight
  3088. fweight = fweight - lppland.Lweight
  3089. lppland.Lweight = 0
  3090. }
  3091. }
  3092. updateLppandList = append(updateLppandList, lppland)
  3093. break
  3094. }
  3095. }
  3096. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3097. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3098. WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3099. if err != nil {
  3100. // tx.Rollback()
  3101. logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3102. return
  3103. }
  3104. for _, lppland := range updateLppandList {
  3105. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3106. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3107. if err != nil {
  3108. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3109. // tx.Rollback()
  3110. logs.Error(err, 3)
  3111. return
  3112. }
  3113. // defer wg.Done()
  3114. }
  3115. updateLppandList = []*lpplandtl1{}
  3116. if w == 0 {
  3117. break
  3118. }
  3119. }
  3120. }
  3121. }(old, fpd)
  3122. }
  3123. }
  3124. wg.Wait()
  3125. }
  3126. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3127. if err != nil {
  3128. logs.Error(err)
  3129. appG.Response(http.StatusOK, e.ERROR, false)
  3130. return
  3131. }
  3132. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3133. if err != nil {
  3134. logs.Error(err)
  3135. appG.Response(http.StatusOK, e.ERROR, false)
  3136. return
  3137. }
  3138. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3139. if err != nil {
  3140. logs.Error(err)
  3141. appG.Response(http.StatusOK, e.ERROR, false)
  3142. return
  3143. }
  3144. now := createdate
  3145. // for _, oldFpd := range oldFpdDataList {
  3146. for _, newFpd := range newFpdDataList {
  3147. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3148. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3149. // go func() {
  3150. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3151. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3152. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3153. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3154. if err != nil {
  3155. logs.Error(err)
  3156. appG.Response(http.StatusOK, e.ERROR, false)
  3157. return
  3158. }
  3159. // }()
  3160. }
  3161. // break
  3162. // }
  3163. // }
  3164. // }
  3165. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3166. for _, newLpplandtl1 := range newLpplandtl1List {
  3167. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3168. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3169. // go func() {
  3170. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3171. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3172. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3173. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3174. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3175. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3176. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3177. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3178. if err != nil {
  3179. logs.Error(err)
  3180. appG.Response(http.StatusOK, e.ERROR, false)
  3181. return
  3182. }
  3183. // }()
  3184. // }
  3185. // break
  3186. // }
  3187. // }
  3188. }
  3189. // for _, oldFeedp := range oldFeedpList {
  3190. for _, newFeedp := range newFeedpList {
  3191. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3192. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3193. // go func() {
  3194. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3195. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3196. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3197. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3198. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3199. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3200. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3201. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3202. if err != nil {
  3203. logs.Error(err)
  3204. appG.Response(http.StatusOK, e.ERROR, false)
  3205. return
  3206. }
  3207. }
  3208. // ,,parammaps["ftid"])
  3209. // surplus, surplusId, id, pastureId string
  3210. // FtdetailSurplusFt(parammaps["ftid"].)
  3211. ftList1, err := tx.SQL(` SELECT
  3212. f.id,
  3213. f.surplus surplusId,
  3214. f.pastureid,
  3215. s.surplus
  3216. FROM
  3217. feedtemplet f
  3218. JOIN surplus s ON s.id = f.surplus
  3219. WHERE
  3220. f.id = ?`, parammaps["ftid"]).QueryString()
  3221. for _, ft := range ftList1 {
  3222. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3223. }
  3224. appG.Response(http.StatusOK, e.SUCCESS, true)
  3225. }
  3226. type lpplandtlInfo struct {
  3227. Id int64 `xorm:"id"`
  3228. Pastureid int64 `xorm:"pastureid"`
  3229. Lppid int64 `xorm:"lppid"`
  3230. Barid int64 `xorm:"barid"`
  3231. Barname string `xorm:"barname"`
  3232. Fpdid int64 `xorm:"fpdid"`
  3233. Fttype int64 `xorm:"fttype"`
  3234. Lweight float64 `xorm:"lweight"`
  3235. Sort int64 `xorm:"sort"`
  3236. Tmrid int64 `xorm:"tmrid"`
  3237. Tmrname string `xorm:"tmrname"`
  3238. Cowcount int64 `xorm:"cowcount"`
  3239. Ccountradio float64 `xorm:"ccountradio"`
  3240. Background string `xorm:"background"`
  3241. Lweighthis float64 `xorm:"lweighthis"`
  3242. Maxweight float64 `xorm:"maxweight"`
  3243. }
  3244. func UpdateFpdetailBar(c *gin.Context) {
  3245. appG := app.Gin{C: c}
  3246. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3247. fsion := gofasion.NewFasion(string(dataByte))
  3248. pastureid := fsion.Get("pastureid").ValueStr()
  3249. id := fsion.Get("id").ValueStr()
  3250. tx := restful.Engine.NewSession()
  3251. tx.Begin()
  3252. 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 `,
  3253. pastureid, id).Query().List()
  3254. if err != nil {
  3255. logs.Error(err)
  3256. }
  3257. for _, fpd := range fpdList {
  3258. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3259. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3260. pastureid, fpd["id"]).Query().List()
  3261. if err != nil {
  3262. tx.Rollback()
  3263. logs.Error(err)
  3264. appG.Response(http.StatusOK, e.ERROR, false)
  3265. return
  3266. }
  3267. var lweight float64
  3268. for _, lppland := range lpplandList {
  3269. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3270. lweight += lweight1
  3271. }
  3272. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3273. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3274. if fpdweight >= ptuse && lweight == ptuse {
  3275. continue
  3276. } else {
  3277. if lweight <= fpdweight {
  3278. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3279. if err != nil {
  3280. tx.Rollback()
  3281. logs.Error(err)
  3282. appG.Response(http.StatusOK, e.ERROR, false)
  3283. return
  3284. }
  3285. } else {
  3286. weight := fpdweight - lweight
  3287. for _, lppland := range lpplandList {
  3288. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3289. if weight >= lpplandlweight {
  3290. weight = weight - lpplandlweight
  3291. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3292. if err != nil {
  3293. tx.Rollback()
  3294. logs.Error(err)
  3295. appG.Response(http.StatusOK, e.ERROR, false)
  3296. return
  3297. }
  3298. } else {
  3299. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3300. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3301. // if err != nil {
  3302. // tx.Rollback()
  3303. // logs.Error(err)
  3304. // appG.Response(http.StatusOK, e.ERROR, false)
  3305. // return
  3306. // }
  3307. weight = 0
  3308. break
  3309. }
  3310. }
  3311. }
  3312. }
  3313. }
  3314. fsionData := fsion.Get("data").Array()
  3315. for _, list := range fsionData {
  3316. ftmap := make(map[string]interface{})
  3317. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3318. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3319. ftmap["times"] = list.Get("times").ValueInt64()
  3320. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3321. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3322. // fmt.Println(ftmap)
  3323. count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3324. and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3325. if count == 1 {
  3326. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3327. and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3328. if err != nil {
  3329. tx.Rollback()
  3330. logs.Error(err)
  3331. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3332. return
  3333. }
  3334. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3335. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3336. if err != nil {
  3337. tx.Rollback()
  3338. logs.Error(err)
  3339. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3340. return
  3341. }
  3342. }
  3343. fpdDataList, err := tx.SQL(`
  3344. 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 ,
  3345. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3346. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3347. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3348. if err != nil {
  3349. tx.Rollback()
  3350. logs.Error(err)
  3351. }
  3352. for _, fpd := range fpdDataList {
  3353. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3354. fttype := -1
  3355. if fpd["fttype"].(string) == "1" {
  3356. fttype = 1
  3357. }
  3358. var fweight float64
  3359. var lweight float64
  3360. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3361. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  3362. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3363. join tmr t on t.id = lpp.tmrid
  3364. where lppland.fpdid =?
  3365. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3366. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3367. if err != nil {
  3368. tx.Rollback()
  3369. logs.Error(err)
  3370. }
  3371. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3372. var w float64
  3373. var status int
  3374. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3375. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3376. if weight >= 0 {
  3377. continue
  3378. }
  3379. w = weight
  3380. status = 0
  3381. } else {
  3382. // continue
  3383. if weight <= 0 {
  3384. continue
  3385. }
  3386. w = weight
  3387. status = 1
  3388. }
  3389. // for _, lppland := range lpplandtl1List {
  3390. // lweight += lppland.Lweight
  3391. // }
  3392. for _, lppland := range lpplandtl1List {
  3393. lpplandInfo := new(lpplandtlInfo)
  3394. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3395. lweight = lpplandInfo.Lweight
  3396. if status == 1 {
  3397. // if w <= lppland.Lweight {
  3398. if lppland.Maxweight <= lweight {
  3399. continue
  3400. }
  3401. if w+lweight <= lppland.Maxweight {
  3402. lppland.Lweight += w
  3403. lweight += w
  3404. fweight += w
  3405. w = 0
  3406. } else {
  3407. w = w - (lppland.Maxweight - lweight)
  3408. n := (lppland.Maxweight - lweight)
  3409. lppland.Lweight = lppland.Lweight + n
  3410. lweight += n
  3411. fweight += n
  3412. }
  3413. } else {
  3414. if lppland.Lweight == 0 {
  3415. continue
  3416. }
  3417. if w+lppland.Lweight >= 0 {
  3418. lppland.Lweight = lppland.Lweight + w
  3419. lweight = lweight + w
  3420. fweight = fweight + w
  3421. w = 0
  3422. } else {
  3423. w = w + lppland.Lweight
  3424. lweight = lweight - lppland.Lweight
  3425. fweight = fweight - lppland.Lweight
  3426. lppland.Lweight = 0
  3427. }
  3428. }
  3429. if lppland.Lweight > 0 {
  3430. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3431. if err != nil {
  3432. tx.Rollback()
  3433. logs.Error(err)
  3434. return
  3435. }
  3436. } else {
  3437. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3438. if err != nil {
  3439. tx.Rollback()
  3440. logs.Error(err)
  3441. return
  3442. }
  3443. }
  3444. if w == 0 {
  3445. break
  3446. }
  3447. // break
  3448. }
  3449. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3450. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3451. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3452. if err != nil {
  3453. tx.Rollback()
  3454. logs.Error(err)
  3455. }
  3456. if w == 0 {
  3457. break
  3458. }
  3459. }
  3460. }
  3461. }
  3462. tx.Commit()
  3463. now := time.Now()
  3464. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3465. if err != nil {
  3466. logs.Error(err)
  3467. appG.Response(http.StatusOK, e.ERROR, false)
  3468. return
  3469. }
  3470. for _, newLpplandtl1 := range newLpplandtl1List {
  3471. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3472. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3473. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3474. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3475. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3476. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3477. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3478. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3479. if err != nil {
  3480. logs.Error(err)
  3481. appG.Response(http.StatusOK, e.ERROR, false)
  3482. return
  3483. }
  3484. }
  3485. appG.Response(http.StatusOK, e.SUCCESS, true)
  3486. }
  3487. func GetProcessAnalysis(c *gin.Context) {
  3488. appG := app.Gin{C: c}
  3489. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3490. fsion := gofasion.NewFasion(string(dataByte))
  3491. sqlnamestr := fsion.Get("name").ValueStr()
  3492. offset := fsion.Get("offset").ValueDefaultInt(0)
  3493. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3494. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3495. parammaps := fsion.Get("parammaps")
  3496. tx := restful.Engine.NewSession()
  3497. err := tx.Begin()
  3498. defer func() {
  3499. switch {
  3500. case err != nil:
  3501. logging.Error("tx.Begin 事务启动失败__error:", err)
  3502. if tx != nil {
  3503. tx.Rollback()
  3504. }
  3505. default:
  3506. if tx != nil {
  3507. err = tx.Commit()
  3508. }
  3509. }
  3510. if tx != nil {
  3511. tx.Close()
  3512. }
  3513. }()
  3514. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3515. s_params := make([]interface{}, 0)
  3516. paramslist := strings.Split(p, ",")
  3517. if len(paramslist) > 0 && p != "" {
  3518. for _, value := range paramslist {
  3519. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3520. if tempv, exists := c.Get("jwt_username"); exists {
  3521. s_params = append(s_params, tempv.(string))
  3522. } else {
  3523. s_params = append(s_params, "")
  3524. }
  3525. } else {
  3526. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3527. }
  3528. }
  3529. }
  3530. tmrtnameStr := ""
  3531. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3532. if len(tmrtnameStr) == 0 {
  3533. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3534. } else {
  3535. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3536. }
  3537. }
  3538. if len(tmrtnameStr) > 0 {
  3539. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3540. }
  3541. sql += " ORDER BY d.intime"
  3542. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3543. if err != nil {
  3544. logging.Error("GetDataByName err: ", err)
  3545. msg := geterrmsg(err.Error())
  3546. appG.Response(http.StatusOK, e.ERROR, msg)
  3547. } else {
  3548. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3549. }
  3550. }
  3551. func UpdateFeedtempletStatus(c *gin.Context) {
  3552. appG := app.Gin{C: c}
  3553. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3554. fsion := gofasion.NewFasion(string(dataByte))
  3555. parammaps := fsion.Get("parammaps")
  3556. tx := restful.Engine.NewSession()
  3557. tx.Begin()
  3558. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3559. if err != nil {
  3560. tx.Rollback()
  3561. logs.Error(err)
  3562. appG.Response(http.StatusOK, e.ERROR, err)
  3563. return
  3564. }
  3565. tx.Commit()
  3566. appG.Response(http.StatusOK, e.SUCCESS, true)
  3567. }
  3568. func AddFtdry(c *gin.Context) {
  3569. appG := app.Gin{C: c}
  3570. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3571. fsion := gofasion.NewFasion(string(dataByte))
  3572. sqlnamestr := fsion.Get("name").ValueStr()
  3573. s_params := make([]interface{}, 0)
  3574. tx := restful.Engine.NewSession()
  3575. err := tx.Begin()
  3576. defer func() {
  3577. switch {
  3578. case err != nil:
  3579. if tx != nil {
  3580. tx.Rollback()
  3581. }
  3582. default:
  3583. if tx != nil {
  3584. err = tx.Commit()
  3585. }
  3586. }
  3587. if tx != nil {
  3588. tx.Close()
  3589. }
  3590. }()
  3591. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3592. if sql != "" {
  3593. parammaps := fsion.Get("parammaps")
  3594. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3595. paramslist := strings.Split(p, ",")
  3596. if len(paramslist) > 0 && p != "" {
  3597. for _, value := range paramslist {
  3598. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3599. if tempv, exists := c.Get("jwt_username"); exists {
  3600. s_params = append(s_params, tempv.(string))
  3601. } else {
  3602. s_params = append(s_params, "")
  3603. }
  3604. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3605. ids, err := setting.SnowIds.NextId()
  3606. if err != nil {
  3607. ids = time.Now().UnixNano()
  3608. logging.Info("create SnowIds err", err)
  3609. }
  3610. s_params = append(s_params, ids)
  3611. } else {
  3612. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3613. }
  3614. }
  3615. }
  3616. var actweight float64
  3617. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3618. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3619. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3620. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3621. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3622. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3623. 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()
  3624. if err != nil {
  3625. logging.Error("AddFtdry err: ", err)
  3626. msg := geterrmsg(err.Error())
  3627. appG.Response(http.StatusOK, e.ERROR, msg)
  3628. }
  3629. if len(actweightList) > 0 {
  3630. for _, item := range actweightList {
  3631. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3632. if err != nil {
  3633. logging.Error("AddFtdry err: ", err)
  3634. msg := geterrmsg(err.Error())
  3635. appG.Response(http.StatusOK, e.ERROR, msg)
  3636. }
  3637. actweight = fl
  3638. }
  3639. } else {
  3640. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3641. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3642. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3643. if err != nil {
  3644. logging.Error("AddFtdry err: ", err)
  3645. msg := geterrmsg(err.Error())
  3646. appG.Response(http.StatusOK, e.ERROR, msg)
  3647. }
  3648. for _, item := range dryList {
  3649. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3650. if err != nil {
  3651. logging.Error("AddFtdry err: ", err)
  3652. msg := geterrmsg(err.Error())
  3653. appG.Response(http.StatusOK, e.ERROR, msg)
  3654. }
  3655. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3656. }
  3657. }
  3658. if sqlnamestr == "insertFtdry" {
  3659. s_params = append(s_params, actweight)
  3660. } else if sqlnamestr == "updateFtdry" {
  3661. sql = fmt.Sprintf(sql, actweight)
  3662. }
  3663. queryData, err := execDataBySqlT(sql, s_params, tx)
  3664. if err != nil {
  3665. logging.Error("AddFtdry err: ", err)
  3666. msg := geterrmsg(err.Error())
  3667. appG.Response(http.StatusOK, e.ERROR, msg)
  3668. } else {
  3669. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3670. }
  3671. } else {
  3672. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3673. }
  3674. }
  3675. func CheckDates(c *gin.Context) {
  3676. tx := restful.Engine.NewSession()
  3677. defer tx.Close()
  3678. appG := app.Gin{C: c}
  3679. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3680. tempval_ := make(map[string]interface{})
  3681. tempCommon := make(map[string]interface{})
  3682. tempval := make([]map[string]interface{}, 0)
  3683. err := json.Unmarshal(dataByte, &tempval_)
  3684. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3685. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3686. if err != nil {
  3687. } else {
  3688. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3689. tempCommon = v
  3690. }
  3691. if v, ok := tempval_["data"].([]interface{}); ok {
  3692. for _, Tvalue := range v {
  3693. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3694. tempval = append(tempval, v1)
  3695. }
  3696. }
  3697. }
  3698. if err == nil {
  3699. if tempv, exists := c.Get("jwt_username"); exists {
  3700. tempCommon["jwt_username"] = tempv.(string)
  3701. }
  3702. for _, paramvalue := range tempval {
  3703. if _, ok := paramvalue["resultname"]; !ok {
  3704. paramvalue["resultname"] = paramvalue["name"]
  3705. }
  3706. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3707. if err != nil {
  3708. logging.Error("ExecDataParam error:", err)
  3709. }
  3710. }
  3711. if err == nil {
  3712. vmsg := ""
  3713. for _, item := range tempval {
  3714. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3715. for _, childrenList := range list.([]interface{}) {
  3716. for k, children := range childrenList.(map[string]interface{}) {
  3717. if k != "children" {
  3718. continue
  3719. }
  3720. for _, v := range children.([]map[string]interface{}) {
  3721. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3722. if k1 == "list" {
  3723. for _, v2 := range v1.([]map[string]interface{}) {
  3724. if v2["vmsg"].(string) != "1" {
  3725. if len(vmsg) == 0 {
  3726. vmsg = v2["vmsg"].(string)
  3727. } else {
  3728. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3729. }
  3730. }
  3731. }
  3732. }
  3733. }
  3734. }
  3735. }
  3736. }
  3737. }
  3738. }
  3739. if len(vmsg) > 0 {
  3740. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3741. } else {
  3742. appG.Response(http.StatusOK, e.SUCCESS, true)
  3743. }
  3744. } else {
  3745. msg := geterrmsg(err.Error())
  3746. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3747. }
  3748. }
  3749. }
  3750. if err != nil {
  3751. msg := geterrmsg(err.Error())
  3752. appG.Response(http.StatusOK, e.ERROR, msg)
  3753. }
  3754. }
  3755. 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) {
  3756. sqlname := fasion["name"].(string)
  3757. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3758. if v, ok := fasion["type"]; ok {
  3759. sqltype = v.(string)
  3760. }
  3761. sql := ""
  3762. p := ""
  3763. s_params := make([]interface{}, 0)
  3764. if sqltype != "" {
  3765. sql, p = restful.GetSqlByName(sqlname, tx)
  3766. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3767. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3768. paramslist := strings.Split(p, ",")
  3769. if len(paramslist) > 0 && p != "" {
  3770. for _, value := range paramslist {
  3771. ss := ""
  3772. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3773. ids, err := setting.SnowIds.NextId()
  3774. if err != nil {
  3775. ids = time.Now().UnixNano()
  3776. logging.Info("create SnowIds err", err)
  3777. }
  3778. s_params = append(s_params, ids)
  3779. } else {
  3780. if ss == "" && CommonParamMap != nil {
  3781. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3782. ss = valuestring
  3783. tempstrb := strings.IndexAny(valuestring, "@")
  3784. tempstre := strings.IndexAny(valuestring, ".")
  3785. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3786. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3787. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3788. }
  3789. } else {
  3790. ss = ""
  3791. }
  3792. }
  3793. }
  3794. if ss == "" && ParentParamMap != nil {
  3795. ss = getParamValue_(v, value, ParentParamMap)
  3796. }
  3797. if ss == "" && sameParamMap != nil {
  3798. ss = getParamValue(v, value, sameParamMap)
  3799. }
  3800. if ss == "" && ParamMap != nil {
  3801. ss = getParamValue(v, value, ParamMap)
  3802. }
  3803. s_params = append(s_params, ss)
  3804. }
  3805. }
  3806. }
  3807. }
  3808. }
  3809. if sql == "" {
  3810. sqltype = ""
  3811. }
  3812. if sql != "" {
  3813. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3814. if err != nil {
  3815. return nil, err
  3816. }
  3817. // fmt.Println(tempValParam)
  3818. return tempValParam.(map[string]interface{}), nil
  3819. } else {
  3820. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3821. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3822. if err != nil {
  3823. return nil, err
  3824. }
  3825. return nil, err
  3826. }
  3827. }
  3828. return nil, nil
  3829. }
  3830. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3831. var err error
  3832. subarray, ok := fasion["children"]
  3833. if ok {
  3834. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3835. tempVal_arrary := make([]map[string]interface{}, 0)
  3836. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3837. tempVal_ := make(map[string]interface{})
  3838. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3839. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3840. } else {
  3841. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3842. }
  3843. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3844. if err != nil {
  3845. return err
  3846. }
  3847. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3848. }
  3849. v.(map[string]interface{})["children"] = tempVal_arrary
  3850. }
  3851. }
  3852. return nil
  3853. }
  3854. func FpdImportExcel(c *gin.Context) {
  3855. appG := app.Gin{C: c}
  3856. inputdata := ""
  3857. c.Request.ParseForm()
  3858. params := c.Request.Form
  3859. file, _, err := c.Request.FormFile("file")
  3860. if err != nil {
  3861. appG.Response(http.StatusOK, e.ERROR, err)
  3862. return
  3863. }
  3864. sqlnamestrs := params.Get("name")
  3865. sheetname := params.Get("sheetname")
  3866. pastureid := params.Get("pastureid")
  3867. // importParams := params.Get("importParams")
  3868. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3869. // 必输项参数 (字符串格式 "field1,field2,field3")
  3870. requiredParams := params.Get("requiredParams")
  3871. // 日期参数
  3872. dateParams := params.Get("dateParams")
  3873. // 数字参数
  3874. numParams := params.Get("numParams")
  3875. //将字符串分割开
  3876. dateParamslist := strings.Split(dateParams, ",")
  3877. requiredParamslist := strings.Split(requiredParams, ",")
  3878. numParamslist := strings.Split(numParams, ",")
  3879. queryData := make([]interface{}, 0)
  3880. sqlslist := strings.Split(sqlnamestrs, ",")
  3881. xlsx1, err := excelize.OpenReader(file)
  3882. if err != nil {
  3883. fmt.Println(err)
  3884. return
  3885. }
  3886. ok := 0
  3887. error := 0
  3888. isdone := true
  3889. tx := restful.Engine.NewSession()
  3890. defer tx.Close()
  3891. languageStatus := GetLanguageStatus()
  3892. if languageStatus == "0" {
  3893. 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
  3894. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3895. if err != nil {
  3896. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3897. return
  3898. }
  3899. rows := xlsx1.GetRows(sheetname)
  3900. // 限制10000条,多余的截取掉
  3901. if len(rows) > 10000 {
  3902. rows = rows[:10000]
  3903. }
  3904. dataList := make(map[string][]*upFpdetail, 0)
  3905. for i, row := range rows {
  3906. if i > 0 {
  3907. entry := make(map[string]interface{})
  3908. outentry := make(map[string]interface{})
  3909. for j, colCell := range rows[0] {
  3910. for k, colCell1 := range row {
  3911. if j == k {
  3912. outentry[colCell] = colCell1
  3913. entry[colCell] = colCell1
  3914. }
  3915. }
  3916. }
  3917. inputdata = ""
  3918. a := ""
  3919. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3920. //校验日期格式
  3921. for _, v := range dateParamslist {
  3922. if v == "" {
  3923. continue
  3924. }
  3925. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3926. dtime, err := TransfTime(d.(string))
  3927. if err != nil {
  3928. a = strings.Trim(v, " ")
  3929. break
  3930. }
  3931. outentry[strings.Trim(v, " ")] = dtime
  3932. }
  3933. }
  3934. if a != "" {
  3935. outentry["error_msg"] = a + " 格式错误"
  3936. error++
  3937. queryData = append(queryData, outentry)
  3938. continue
  3939. }
  3940. a = ""
  3941. //校验必填格式
  3942. for _, v := range requiredParamslist {
  3943. if v == "" {
  3944. continue
  3945. }
  3946. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3947. a = strings.Trim(v, " ")
  3948. break
  3949. }
  3950. }
  3951. if a != "" {
  3952. outentry["error_msg"] = a + " 未填或格式错误"
  3953. error++
  3954. queryData = append(queryData, outentry)
  3955. continue
  3956. }
  3957. a = ""
  3958. //校验数字格式
  3959. for _, v := range numParamslist {
  3960. if v == "" {
  3961. continue
  3962. }
  3963. d, ok := outentry[strings.Trim(v, " ")]
  3964. if !ok || d == "" {
  3965. outentry[strings.Trim(v, " ")] = 0
  3966. } else {
  3967. var fl float64
  3968. switch d.(type) {
  3969. case string:
  3970. fl, err = strconv.ParseFloat(d.(string), 64)
  3971. }
  3972. if err != nil || fl < 0 {
  3973. a = strings.Trim(v, " ")
  3974. break
  3975. }
  3976. }
  3977. }
  3978. if a != "" {
  3979. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3980. error++
  3981. queryData = append(queryData, outentry)
  3982. continue
  3983. }
  3984. errExist := false
  3985. for _, sqlnamestr := range sqlslist {
  3986. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3987. paramslist := strings.Split(paramslists, ",")
  3988. if len(paramslist) > 0 {
  3989. s_params := make([]interface{}, 0)
  3990. for _, value := range paramslist {
  3991. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3992. if tempv, exists := c.Get("jwt_username"); exists {
  3993. s_params = append(s_params, tempv.(string))
  3994. } else {
  3995. s_params = append(s_params, "")
  3996. }
  3997. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3998. s_params = append(s_params, pastureid)
  3999. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4000. ids, err := setting.SnowIds.NextId()
  4001. if err != nil {
  4002. ids = time.Now().UnixNano()
  4003. logging.Info("create SnowIds err", err)
  4004. }
  4005. s_params = append(s_params, ids)
  4006. } else {
  4007. if outentry[strings.Trim(value, " ")] == nil {
  4008. s_params = append(s_params, "")
  4009. } else {
  4010. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4011. }
  4012. }
  4013. }
  4014. outentry["input"] = inputdata
  4015. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4016. if err != nil {
  4017. errExist = true
  4018. // if tx != nil {
  4019. // tx.Rollback()
  4020. // }
  4021. // if tx != nil {
  4022. // tx.Close()
  4023. // }
  4024. msg := geterrmsg(err.Error())
  4025. outentry["error_msg"] = msg
  4026. error++
  4027. queryData = append(queryData, outentry)
  4028. isdone = true
  4029. break
  4030. } else {
  4031. if len(returnmsgmap1) > 0 {
  4032. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4033. // if tx != nil {
  4034. // tx.Rollback()
  4035. // }
  4036. // if tx != nil {
  4037. // tx.Close()
  4038. // }
  4039. msg := geterrmsg(va.(string))
  4040. outentry["error_msg"] = msg
  4041. error++
  4042. queryData = append(queryData, outentry)
  4043. isdone = true
  4044. break
  4045. }
  4046. }
  4047. isdone = false
  4048. }
  4049. }
  4050. }
  4051. if !errExist {
  4052. dataexcel := make(map[string]interface{}, 0)
  4053. if _, ok := outentry["栏舍名称"]; ok {
  4054. dataexcel["barname"] = outentry["栏舍名称"]
  4055. }
  4056. if _, ok := outentry["实际牛头数"]; ok {
  4057. dataexcel["ccount"] = outentry["实际牛头数"]
  4058. }
  4059. if _, ok := outentry["系数(%)"]; ok {
  4060. dataexcel["ratio"] = outentry["系数(%)"]
  4061. }
  4062. if _, ok := outentry["配方模板"]; ok {
  4063. dataexcel["ftname"] = outentry["配方模板"]
  4064. }
  4065. if _, ok := outentry["补料配方"]; ok {
  4066. dataexcel["ptsfname"] = outentry["补料配方"]
  4067. }
  4068. if _, ok := outentry["第一班比例(%)"]; ok {
  4069. dataexcel["1"] = outentry["第一班比例(%)"]
  4070. }
  4071. if _, ok := outentry["第二班比例(%)"]; ok {
  4072. dataexcel["2"] = outentry["第二班比例(%)"]
  4073. }
  4074. if _, ok := outentry["第三班比例(%)"]; ok {
  4075. dataexcel["3"] = outentry["第三班比例(%)"]
  4076. }
  4077. if _, ok := outentry["第四班比例(%)"]; ok {
  4078. dataexcel["4"] = outentry["第四班比例(%)"]
  4079. }
  4080. if _, ok := outentry["第五班比例(%)"]; ok {
  4081. dataexcel["5"] = outentry["第五班比例(%)"]
  4082. }
  4083. if _, ok := outentry["第六班比例(%)"]; ok {
  4084. dataexcel["6"] = outentry["第六班比例(%)"]
  4085. }
  4086. dataWeight := new(models.FpdetailEdit)
  4087. // dataWeightMap := make(map[string]interface{}, 0)
  4088. if _, ok := outentry["第一班重量"]; ok {
  4089. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4090. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4091. }
  4092. if _, ok := outentry["第二班重量"]; ok {
  4093. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4094. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4095. }
  4096. if _, ok := outentry["第三班重量"]; ok {
  4097. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4098. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4099. }
  4100. if _, ok := outentry["第四班重量"]; ok {
  4101. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4102. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4103. }
  4104. if _, ok := outentry["第五班重量"]; ok {
  4105. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4106. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4107. }
  4108. if _, ok := outentry["第六班重量"]; ok {
  4109. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4110. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4111. }
  4112. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4113. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4114. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4115. // fmt.Println(err)
  4116. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4117. if weight > 0 {
  4118. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4119. if err != nil {
  4120. logs.Error(err)
  4121. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4122. return
  4123. }
  4124. if !existbar {
  4125. continue
  4126. }
  4127. _, 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()
  4128. if err != nil {
  4129. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4130. return
  4131. }
  4132. _, 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()
  4133. if err != nil {
  4134. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4135. return
  4136. }
  4137. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4138. if err != nil {
  4139. logs.Error(err)
  4140. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4141. return
  4142. }
  4143. if !existft {
  4144. continue
  4145. }
  4146. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4147. if err != nil {
  4148. logs.Error(err)
  4149. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4150. return
  4151. }
  4152. if !ftexist {
  4153. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4154. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4155. if err != nil {
  4156. logs.Error(err)
  4157. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4158. return
  4159. }
  4160. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4161. if err != nil {
  4162. logs.Error(err)
  4163. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4164. return
  4165. }
  4166. }
  4167. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4168. if err != nil {
  4169. logs.Error(err)
  4170. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4171. return
  4172. }
  4173. if !exist {
  4174. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4175. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4176. if err != nil {
  4177. logs.Error(err)
  4178. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4179. return
  4180. }
  4181. }
  4182. var feedpargs []interface{}
  4183. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4184. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4185. if _, ok := dataexcel["ftname"]; ok {
  4186. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4187. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4188. // upFeedpSql += `,ftweight = ? `
  4189. // feedpargs = append(feedpargs, weight)
  4190. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4191. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4192. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4193. } else {
  4194. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4195. }
  4196. if _, ok := dataexcel["ptsfname"]; ok {
  4197. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4198. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4199. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4200. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4201. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4202. } else {
  4203. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4204. }
  4205. upFeedpSql += " where barname = ? and pastureid = ? "
  4206. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4207. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4208. if err != nil {
  4209. logs.Error(err)
  4210. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4211. return
  4212. }
  4213. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4214. if err != nil {
  4215. logs.Error(err)
  4216. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4217. return
  4218. }
  4219. if !exist1 {
  4220. _, 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) `,
  4221. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4222. if err != nil {
  4223. logs.Error(err)
  4224. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4225. return
  4226. }
  4227. }
  4228. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4229. if err != nil {
  4230. logs.Error(err)
  4231. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4232. return
  4233. }
  4234. if !exist2 {
  4235. _, 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) `,
  4236. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4237. if err != nil {
  4238. logs.Error(err)
  4239. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4240. return
  4241. }
  4242. }
  4243. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4244. if err != nil {
  4245. logs.Error(err)
  4246. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4247. return
  4248. }
  4249. if !exist3 {
  4250. _, 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) `,
  4251. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4252. if err != nil {
  4253. logs.Error(err)
  4254. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4255. return
  4256. }
  4257. }
  4258. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4259. if err != nil {
  4260. logs.Error(err)
  4261. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4262. return
  4263. }
  4264. if !exist4 {
  4265. _, 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) `,
  4266. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4267. if err != nil {
  4268. logs.Error(err)
  4269. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4270. return
  4271. }
  4272. }
  4273. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4274. if err != nil {
  4275. logs.Error(err)
  4276. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4277. return
  4278. }
  4279. if !exist5 {
  4280. _, 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) `,
  4281. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4282. if err != nil {
  4283. logs.Error(err)
  4284. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4285. return
  4286. }
  4287. }
  4288. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4289. if err != nil {
  4290. logs.Error(err)
  4291. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4292. return
  4293. }
  4294. if !exist6 {
  4295. _, 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) `,
  4296. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4297. if err != nil {
  4298. logs.Error(err)
  4299. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4300. return
  4301. }
  4302. }
  4303. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4304. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4305. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4306. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4307. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4308. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4309. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4310. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4311. and pastureid = ? and times = ?`
  4312. var fpdargs1 []interface{}
  4313. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4314. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4315. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4316. if err != nil {
  4317. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4318. return
  4319. }
  4320. var fpdargs2 []interface{}
  4321. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4322. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4323. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4324. if err != nil {
  4325. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4326. return
  4327. }
  4328. var fpdargs3 []interface{}
  4329. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4330. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4331. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4332. if err != nil {
  4333. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4334. return
  4335. }
  4336. var fpdargs4 []interface{}
  4337. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4338. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4339. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4340. if err != nil {
  4341. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4342. return
  4343. }
  4344. var fpdargs5 []interface{}
  4345. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4346. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4347. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4348. if err != nil {
  4349. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4350. return
  4351. }
  4352. var fpdargs6 []interface{}
  4353. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4354. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4355. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4356. if err != nil {
  4357. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4358. return
  4359. }
  4360. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4361. 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()
  4362. if err != nil {
  4363. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4364. return
  4365. }
  4366. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4367. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4368. upFpdetailList := make([]*upFpdetail, 0)
  4369. for _, newfpd := range newList {
  4370. for _, oldfpd := range oldFpdList {
  4371. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4372. var oldweight, newweight float64
  4373. if oldfpd["weight"] != nil {
  4374. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4375. }
  4376. if newfpd["weight"] != nil {
  4377. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4378. }
  4379. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4380. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4381. Old: oldweight,
  4382. New: newweight,
  4383. Times: newfpd["times"].(int64),
  4384. Ptid: newfpd["ptid"].(int64),
  4385. Fweight: fweight,
  4386. Id: oldfpd["id"].(int64),
  4387. })
  4388. break
  4389. }
  4390. }
  4391. }
  4392. // fmt.Println(dataexcel["barname"])
  4393. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4394. } else {
  4395. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4396. if err != nil {
  4397. logs.Error(err)
  4398. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4399. return
  4400. }
  4401. if !existbar {
  4402. continue
  4403. }
  4404. _, 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()
  4405. if err != nil {
  4406. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4407. return
  4408. }
  4409. _, 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()
  4410. if err != nil {
  4411. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4412. return
  4413. }
  4414. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4415. if err != nil {
  4416. logs.Error(err)
  4417. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4418. return
  4419. }
  4420. if !existft {
  4421. continue
  4422. }
  4423. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4424. if err != nil {
  4425. logs.Error(err)
  4426. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4427. return
  4428. }
  4429. if !ftexist {
  4430. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4431. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4432. if err != nil {
  4433. logs.Error(err)
  4434. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4435. return
  4436. }
  4437. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4438. if err != nil {
  4439. logs.Error(err)
  4440. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4441. return
  4442. }
  4443. }
  4444. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4445. if err != nil {
  4446. logs.Error(err)
  4447. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4448. return
  4449. }
  4450. if !exist {
  4451. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4452. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4453. if err != nil {
  4454. logs.Error(err)
  4455. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4456. return
  4457. }
  4458. }
  4459. var feedpargs []interface{}
  4460. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4461. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4462. if _, ok := dataexcel["ftname"]; ok {
  4463. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4464. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4465. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4466. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4467. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4468. } else {
  4469. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4470. }
  4471. if _, ok := dataexcel["ptsfname"]; ok {
  4472. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4473. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4474. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4475. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4476. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4477. } else {
  4478. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4479. }
  4480. upFeedpSql += " where barname = ? and pastureid = ? "
  4481. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4482. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4483. if err != nil {
  4484. logs.Error(err)
  4485. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4486. return
  4487. }
  4488. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4489. if err != nil {
  4490. logs.Error(err)
  4491. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4492. return
  4493. }
  4494. if !exist1 {
  4495. _, 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) `,
  4496. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4497. if err != nil {
  4498. logs.Error(err)
  4499. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4500. return
  4501. }
  4502. }
  4503. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4504. if err != nil {
  4505. logs.Error(err)
  4506. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4507. return
  4508. }
  4509. if !exist2 {
  4510. _, 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) `,
  4511. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4512. if err != nil {
  4513. logs.Error(err)
  4514. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4515. return
  4516. }
  4517. }
  4518. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4519. if err != nil {
  4520. logs.Error(err)
  4521. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4522. return
  4523. }
  4524. if !exist3 {
  4525. _, 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) `,
  4526. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4527. if err != nil {
  4528. logs.Error(err)
  4529. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4530. return
  4531. }
  4532. }
  4533. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4534. if err != nil {
  4535. logs.Error(err)
  4536. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4537. return
  4538. }
  4539. if !exist4 {
  4540. _, 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) `,
  4541. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4542. if err != nil {
  4543. logs.Error(err)
  4544. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4545. return
  4546. }
  4547. }
  4548. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4549. if err != nil {
  4550. logs.Error(err)
  4551. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4552. return
  4553. }
  4554. if !exist5 {
  4555. _, 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) `,
  4556. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4557. if err != nil {
  4558. logs.Error(err)
  4559. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4560. return
  4561. }
  4562. }
  4563. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4564. if err != nil {
  4565. logs.Error(err)
  4566. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4567. return
  4568. }
  4569. if !exist6 {
  4570. _, 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) `,
  4571. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4572. if err != nil {
  4573. logs.Error(err)
  4574. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4575. return
  4576. }
  4577. }
  4578. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4579. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4580. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4581. and pastureid = ? and times = ?`
  4582. var fpdargs1 []interface{}
  4583. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4584. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4585. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4586. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4587. if err != nil {
  4588. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4589. return
  4590. }
  4591. var fpdargs2 []interface{}
  4592. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4593. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4594. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4595. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4596. if err != nil {
  4597. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4598. return
  4599. }
  4600. var fpdargs3 []interface{}
  4601. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4602. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4603. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4604. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4605. if err != nil {
  4606. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4607. return
  4608. }
  4609. var fpdargs4 []interface{}
  4610. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4611. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4612. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4613. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4614. if err != nil {
  4615. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4616. return
  4617. }
  4618. var fpdargs5 []interface{}
  4619. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4620. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4621. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4622. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4623. if err != nil {
  4624. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4625. return
  4626. }
  4627. var fpdargs6 []interface{}
  4628. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4629. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4630. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4631. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4632. if err != nil {
  4633. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4634. return
  4635. }
  4636. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4637. 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()
  4638. if err != nil {
  4639. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4640. return
  4641. }
  4642. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4643. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4644. upFpdetailList := make([]*upFpdetail, 0)
  4645. for _, newfpd := range newList {
  4646. for _, oldfpd := range oldFpdList {
  4647. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4648. var oldweight, newweight float64
  4649. if oldfpd["weight"] != nil {
  4650. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4651. }
  4652. if newfpd["weight"] != nil {
  4653. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4654. }
  4655. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4656. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4657. Old: oldweight,
  4658. New: newweight,
  4659. Times: newfpd["times"].(int64),
  4660. Ptid: newfpd["ptid"].(int64),
  4661. Fweight: fweight,
  4662. Id: oldfpd["id"].(int64),
  4663. })
  4664. break
  4665. }
  4666. }
  4667. }
  4668. // fmt.Println(dataexcel["barname"])
  4669. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4670. }
  4671. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4672. }
  4673. }
  4674. if !isdone {
  4675. ok++
  4676. isdone = true
  4677. }
  4678. }
  4679. for barname, v := range dataList {
  4680. for _, v1 := range v {
  4681. count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4682. and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4683. if count == 1 {
  4684. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4685. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4686. if err != nil {
  4687. logs.Error(err)
  4688. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4689. return
  4690. }
  4691. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4692. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4693. if err != nil {
  4694. logs.Error(err)
  4695. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4696. return
  4697. }
  4698. }
  4699. }
  4700. updateFpdetailByBar(pastureid, barname, v)
  4701. }
  4702. } else {
  4703. 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
  4704. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4705. if err != nil {
  4706. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4707. return
  4708. }
  4709. rows := xlsx1.GetRows(sheetname)
  4710. // 限制10000条,多余的截取掉
  4711. if len(rows) > 10000 {
  4712. rows = rows[:10000]
  4713. }
  4714. dataList := make(map[string][]*upFpdetail, 0)
  4715. for i, row := range rows {
  4716. if i > 0 {
  4717. entry := make(map[string]interface{})
  4718. outentry := make(map[string]interface{})
  4719. for j, colCell := range rows[0] {
  4720. for k, colCell1 := range row {
  4721. if j == k {
  4722. outentry[colCell] = colCell1
  4723. entry[colCell] = colCell1
  4724. }
  4725. }
  4726. }
  4727. inputdata = ""
  4728. a := ""
  4729. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4730. //校验日期格式
  4731. for _, v := range dateParamslist {
  4732. if v == "" {
  4733. continue
  4734. }
  4735. if d, ok := outentry[v]; ok {
  4736. dtime, err := TransfTime(d.(string))
  4737. if err != nil {
  4738. a = v
  4739. break
  4740. }
  4741. outentry[v] = dtime
  4742. }
  4743. }
  4744. if a != "" {
  4745. outentry["error_msg"] = a + " format error"
  4746. error++
  4747. queryData = append(queryData, outentry)
  4748. continue
  4749. }
  4750. a = ""
  4751. //校验必填格式
  4752. for _, v := range requiredParamslist {
  4753. if v == "" {
  4754. continue
  4755. }
  4756. if d, ok := outentry[v]; !ok || d == "" {
  4757. a = v
  4758. break
  4759. }
  4760. }
  4761. if a != "" {
  4762. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4763. error++
  4764. queryData = append(queryData, outentry)
  4765. continue
  4766. }
  4767. a = ""
  4768. //校验数字格式
  4769. for _, v := range numParamslist {
  4770. if v == "" {
  4771. continue
  4772. }
  4773. d, ok := outentry[v]
  4774. if !ok || d == "" {
  4775. outentry[v] = 0
  4776. } else {
  4777. var fl float64
  4778. switch d.(type) {
  4779. case string:
  4780. fl, err = strconv.ParseFloat(d.(string), 64)
  4781. }
  4782. if err != nil || fl < 0 {
  4783. a = v
  4784. break
  4785. }
  4786. }
  4787. }
  4788. if a != "" {
  4789. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4790. error++
  4791. queryData = append(queryData, outentry)
  4792. continue
  4793. }
  4794. errExist := false
  4795. for _, sqlnamestr := range sqlslist {
  4796. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4797. paramslist := strings.Split(paramslists, ",")
  4798. if len(paramslist) > 0 {
  4799. s_params := make([]interface{}, 0)
  4800. for _, value := range paramslist {
  4801. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4802. if tempv, exists := c.Get("jwt_username"); exists {
  4803. s_params = append(s_params, tempv.(string))
  4804. } else {
  4805. s_params = append(s_params, "")
  4806. }
  4807. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4808. s_params = append(s_params, pastureid)
  4809. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4810. ids, err := setting.SnowIds.NextId()
  4811. if err != nil {
  4812. ids = time.Now().UnixNano()
  4813. logging.Info("create SnowIds err", err)
  4814. }
  4815. s_params = append(s_params, ids)
  4816. } else {
  4817. if outentry[strings.Trim(value, " ")] == nil {
  4818. s_params = append(s_params, "")
  4819. } else {
  4820. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4821. }
  4822. }
  4823. }
  4824. outentry["input"] = inputdata
  4825. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4826. if err != nil {
  4827. errExist = true
  4828. // if tx != nil {
  4829. // tx.Rollback()
  4830. // }
  4831. // if tx != nil {
  4832. // tx.Close()
  4833. // }
  4834. msg := geterrmsg(err.Error())
  4835. outentry["error_msg"] = msg
  4836. error++
  4837. queryData = append(queryData, outentry)
  4838. isdone = true
  4839. break
  4840. } else {
  4841. if len(returnmsgmap1) > 0 {
  4842. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4843. // if tx != nil {
  4844. // tx.Rollback()
  4845. // }
  4846. // if tx != nil {
  4847. // tx.Close()
  4848. // }
  4849. msg := geterrmsg(va.(string))
  4850. outentry["error_msg"] = msg
  4851. error++
  4852. queryData = append(queryData, outentry)
  4853. isdone = true
  4854. break
  4855. }
  4856. }
  4857. isdone = false
  4858. }
  4859. }
  4860. }
  4861. if !errExist {
  4862. dataexcel := make(map[string]interface{}, 0)
  4863. if _, ok := outentry["Pen Name"]; ok {
  4864. dataexcel["barname"] = outentry["Pen Name"]
  4865. }
  4866. if _, ok := outentry["Actual Cattle Number"]; ok {
  4867. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4868. }
  4869. if _, ok := outentry["Coefficient(%)"]; ok {
  4870. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4871. }
  4872. if _, ok := outentry["Formula Template"]; ok {
  4873. dataexcel["ftname"] = outentry["Formula Template"]
  4874. }
  4875. if _, ok := outentry["Supplement Formula"]; ok {
  4876. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4877. }
  4878. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4879. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4880. }
  4881. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4882. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4883. }
  4884. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4885. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4886. }
  4887. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4888. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4889. }
  4890. if _, ok := outentry["Fifth shift Ratio(%)"]; ok {
  4891. dataexcel["5"] = outentry["Fifth shift Ratio(%)"]
  4892. }
  4893. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4894. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4895. }
  4896. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4897. if err != nil {
  4898. logs.Error(err)
  4899. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4900. return
  4901. }
  4902. if !existbar {
  4903. continue
  4904. }
  4905. _, 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()
  4906. if err != nil {
  4907. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4908. return
  4909. }
  4910. _, 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()
  4911. if err != nil {
  4912. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4913. return
  4914. }
  4915. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4916. if err != nil {
  4917. logs.Error(err)
  4918. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  4919. return
  4920. }
  4921. if !existft {
  4922. continue
  4923. }
  4924. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4925. if err != nil {
  4926. logs.Error(err)
  4927. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4928. return
  4929. }
  4930. if !ftexist {
  4931. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4932. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4933. if err != nil {
  4934. logs.Error(err)
  4935. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4936. return
  4937. }
  4938. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4939. if err != nil {
  4940. logs.Error(err)
  4941. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4942. return
  4943. }
  4944. }
  4945. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4946. if err != nil {
  4947. logs.Error(err)
  4948. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4949. return
  4950. }
  4951. if !exist {
  4952. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4953. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4954. if err != nil {
  4955. logs.Error(err)
  4956. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4957. return
  4958. }
  4959. }
  4960. var feedpargs []interface{}
  4961. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4962. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4963. if _, ok := dataexcel["ftname"]; ok {
  4964. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4965. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4966. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4967. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4968. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4969. } else {
  4970. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4971. }
  4972. if _, ok := dataexcel["ptsfname"]; ok {
  4973. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4974. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4975. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4976. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4977. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4978. } else {
  4979. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4980. }
  4981. upFeedpSql += " where barname = ? and pastureid = ? "
  4982. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4983. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4984. if err != nil {
  4985. logs.Error(err)
  4986. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4987. return
  4988. }
  4989. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4990. if err != nil {
  4991. logs.Error(err)
  4992. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4993. return
  4994. }
  4995. if !exist1 {
  4996. _, 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) `,
  4997. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4998. if err != nil {
  4999. logs.Error(err)
  5000. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5001. return
  5002. }
  5003. }
  5004. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5005. if err != nil {
  5006. logs.Error(err)
  5007. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5008. return
  5009. }
  5010. if !exist2 {
  5011. _, 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) `,
  5012. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5013. if err != nil {
  5014. logs.Error(err)
  5015. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5016. return
  5017. }
  5018. }
  5019. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5020. if err != nil {
  5021. logs.Error(err)
  5022. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5023. return
  5024. }
  5025. if !exist3 {
  5026. _, 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) `,
  5027. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5028. if err != nil {
  5029. logs.Error(err)
  5030. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5031. return
  5032. }
  5033. }
  5034. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5035. if err != nil {
  5036. logs.Error(err)
  5037. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5038. return
  5039. }
  5040. if !exist4 {
  5041. _, 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) `,
  5042. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5043. if err != nil {
  5044. logs.Error(err)
  5045. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5046. return
  5047. }
  5048. }
  5049. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5050. if err != nil {
  5051. logs.Error(err)
  5052. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5053. return
  5054. }
  5055. if !exist5 {
  5056. _, 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) `,
  5057. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5058. if err != nil {
  5059. logs.Error(err)
  5060. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5061. return
  5062. }
  5063. }
  5064. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5065. if err != nil {
  5066. logs.Error(err)
  5067. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5068. return
  5069. }
  5070. if !exist6 {
  5071. _, 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) `,
  5072. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5073. if err != nil {
  5074. logs.Error(err)
  5075. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5076. return
  5077. }
  5078. }
  5079. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5080. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5081. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5082. and pastureid = ? and times = ?`
  5083. var fpdargs1 []interface{}
  5084. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5085. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5086. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5087. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5088. if err != nil {
  5089. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5090. return
  5091. }
  5092. var fpdargs2 []interface{}
  5093. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5094. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5095. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5096. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5097. if err != nil {
  5098. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5099. return
  5100. }
  5101. var fpdargs3 []interface{}
  5102. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5103. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5104. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5105. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5106. if err != nil {
  5107. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5108. return
  5109. }
  5110. var fpdargs4 []interface{}
  5111. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5112. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5113. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5114. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5115. if err != nil {
  5116. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5117. return
  5118. }
  5119. var fpdargs5 []interface{}
  5120. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5121. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5122. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5123. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5124. if err != nil {
  5125. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5126. return
  5127. }
  5128. var fpdargs6 []interface{}
  5129. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5130. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5131. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5132. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5133. if err != nil {
  5134. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5135. return
  5136. }
  5137. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5138. 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()
  5139. if err != nil {
  5140. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5141. return
  5142. }
  5143. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5144. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5145. upFpdetailList := make([]*upFpdetail, 0)
  5146. for _, newfpd := range newList {
  5147. for _, oldfpd := range oldFpdList {
  5148. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5149. var oldweight, newweight float64
  5150. if oldfpd["weight"] != nil {
  5151. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5152. }
  5153. if newfpd["weight"] != nil {
  5154. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5155. }
  5156. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5157. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5158. Old: oldweight,
  5159. New: newweight,
  5160. Times: newfpd["times"].(int64),
  5161. Ptid: newfpd["ptid"].(int64),
  5162. Fweight: fweight,
  5163. Id: oldfpd["id"].(int64),
  5164. })
  5165. break
  5166. }
  5167. }
  5168. }
  5169. // fmt.Println(dataexcel["barname"])
  5170. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5171. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5172. }
  5173. }
  5174. if !isdone {
  5175. ok++
  5176. isdone = true
  5177. }
  5178. }
  5179. for barname, v := range dataList {
  5180. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5181. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5182. if err != nil {
  5183. logs.Error(err)
  5184. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5185. return
  5186. }
  5187. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5188. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5189. if err != nil {
  5190. logs.Error(err)
  5191. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5192. return
  5193. }
  5194. updateFpdetailByBar(pastureid, barname, v)
  5195. }
  5196. }
  5197. data := make(map[string]interface{})
  5198. data["result"] = queryData
  5199. data["success"] = ok
  5200. data["err_count"] = error
  5201. appG.Response(http.StatusOK, e.SUCCESS, data)
  5202. }
  5203. type upFpdetail struct {
  5204. Old float64
  5205. New float64
  5206. Times int64
  5207. Ptid int64
  5208. Fweight float64
  5209. Id int64
  5210. // Ptsid string
  5211. }
  5212. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5213. tx := restful.Engine.NewSession()
  5214. defer tx.Close()
  5215. tx.Begin()
  5216. 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 `,
  5217. pastureid, barname).Query().List()
  5218. if err != nil {
  5219. logs.Error(err)
  5220. }
  5221. for _, fpd := range fpdList {
  5222. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5223. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5224. pastureid, fpd["id"], fpd["times"]).Query().List()
  5225. if err != nil {
  5226. tx.Rollback()
  5227. logs.Error(err)
  5228. return err
  5229. }
  5230. var lweight float64
  5231. for _, lppland := range lpplandList {
  5232. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5233. lweight += lweight1
  5234. }
  5235. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5236. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5237. if fpdweight >= ptuse && lweight == ptuse {
  5238. continue
  5239. } else {
  5240. if lweight <= fpdweight {
  5241. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5242. if err != nil {
  5243. tx.Rollback()
  5244. logs.Error(err)
  5245. return err
  5246. }
  5247. } else {
  5248. weight := lweight - fpdweight
  5249. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5250. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5251. if err != nil {
  5252. tx.Rollback()
  5253. logs.Error(err)
  5254. return err
  5255. }
  5256. for _, lppland := range lpplandList {
  5257. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5258. if weight >= lpplandlweight {
  5259. weight = weight - lpplandlweight
  5260. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5261. if err != nil {
  5262. tx.Rollback()
  5263. logs.Error(err)
  5264. return err
  5265. }
  5266. } else {
  5267. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5268. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5269. if err != nil {
  5270. tx.Rollback()
  5271. logs.Error(err)
  5272. return err
  5273. }
  5274. weight = 0
  5275. break
  5276. }
  5277. }
  5278. }
  5279. }
  5280. }
  5281. for _, list := range dataList {
  5282. ftmap := make(map[string]interface{})
  5283. ftmap["old"] = list.Old
  5284. ftmap["new"] = list.New
  5285. ftmap["times"] = list.Times
  5286. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5287. ftmap["ptsid"] = ""
  5288. // fmt.Println(ftmap)
  5289. // 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 ,
  5290. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5291. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5292. // UNION
  5293. fpdDataList, err := tx.SQL(`
  5294. 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 ,
  5295. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5296. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5297. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5298. if err != nil {
  5299. tx.Rollback()
  5300. logs.Error(err)
  5301. }
  5302. for _, fpd := range fpdDataList {
  5303. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5304. // fttype := -1
  5305. // if fpd["fttype"].(string) == "1" {
  5306. fttype := 1
  5307. // }
  5308. var fweight float64
  5309. var lweight float64
  5310. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5311. err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
  5312. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5313. join tmr t on t.id = lpp.tmrid
  5314. where lppland.fpdid =?
  5315. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5316. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5317. if err != nil {
  5318. tx.Rollback()
  5319. logs.Error(err)
  5320. }
  5321. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5322. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5323. // 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
  5324. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5325. var w float64
  5326. var status int
  5327. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5328. if weight >= 0 {
  5329. continue
  5330. }
  5331. w = weight
  5332. status = 0
  5333. } else {
  5334. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5335. // continue
  5336. // }
  5337. w = weight
  5338. status = 1
  5339. }
  5340. // for _, lppland := range lpplandtl1List {
  5341. // lweight += lppland.Lweight
  5342. // }
  5343. for _, lppland := range lpplandtl1List {
  5344. lpplandInfo := new(lpplandtlInfo)
  5345. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5346. lweight = lpplandInfo.Lweight
  5347. if status == 1 {
  5348. // if w <= lppland.Lweight {
  5349. if lppland.Maxweight <= lweight {
  5350. continue
  5351. }
  5352. if w+lweight <= lppland.Maxweight {
  5353. lppland.Lweight += w
  5354. lweight += w
  5355. fweight += w
  5356. w = 0
  5357. } else {
  5358. w = w - (lppland.Maxweight - lweight)
  5359. n := (lppland.Maxweight - lweight)
  5360. lppland.Lweight = lppland.Lweight + n
  5361. lweight += n
  5362. fweight += n
  5363. }
  5364. } else {
  5365. if lppland.Lweight == 0 {
  5366. continue
  5367. }
  5368. if w+lppland.Lweight >= 0 {
  5369. lppland.Lweight = lppland.Lweight + w
  5370. lweight = lweight + w
  5371. fweight = fweight + w
  5372. w = 0
  5373. } else {
  5374. w = w + lppland.Lweight
  5375. lweight = lweight - lppland.Lweight
  5376. fweight = fweight - lppland.Lweight
  5377. lppland.Lweight = 0
  5378. }
  5379. }
  5380. if lppland.Lweight > 0 {
  5381. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5382. if err != nil {
  5383. tx.Rollback()
  5384. logs.Error(err)
  5385. return err
  5386. }
  5387. } else {
  5388. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5389. if err != nil {
  5390. tx.Rollback()
  5391. logs.Error(err)
  5392. return err
  5393. }
  5394. }
  5395. if w == 0 {
  5396. break
  5397. }
  5398. }
  5399. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5400. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5401. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5402. if err != nil {
  5403. tx.Rollback()
  5404. logs.Error(err)
  5405. }
  5406. if w == 0 {
  5407. break
  5408. }
  5409. }
  5410. }
  5411. }
  5412. err = tx.Commit()
  5413. if err != nil {
  5414. logs.Error(err)
  5415. tx.Rollback()
  5416. return err
  5417. }
  5418. now := time.Now()
  5419. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5420. if err != nil {
  5421. logs.Error(err)
  5422. return nil
  5423. }
  5424. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5425. if err != nil {
  5426. logs.Error(err)
  5427. return nil
  5428. }
  5429. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5430. if err != nil {
  5431. logs.Error(err)
  5432. return nil
  5433. }
  5434. for _, newLpplandtl1 := range newLpplandtl1List {
  5435. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5436. background,cowcount,ccountradio,lweighthis,createdate)
  5437. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5438. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5439. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5440. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5441. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5442. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5443. if err != nil {
  5444. logs.Error(err)
  5445. // appG.Response(http.StatusOK, e.ERROR, false)
  5446. return err
  5447. }
  5448. }
  5449. for _, newFpd := range newFpdDataList {
  5450. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5451. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5452. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5453. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5454. if err != nil {
  5455. logs.Error(err)
  5456. // appG.Response(http.StatusOK, e.ERROR, false)
  5457. return err
  5458. }
  5459. }
  5460. for _, newFeedp := range newFeedpList {
  5461. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5462. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5463. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5464. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5465. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5466. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5467. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5468. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5469. if err != nil {
  5470. logs.Error(err)
  5471. // appG.Response(http.StatusOK, e.ERROR, false)
  5472. return err
  5473. }
  5474. }
  5475. return nil
  5476. }
  5477. func DeleteFTdetail(c *gin.Context) {
  5478. appG := app.Gin{C: c}
  5479. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5480. fsion := gofasion.NewFasion(string(dataByte))
  5481. parammaps := fsion.Get("parammaps")
  5482. pastureid := parammaps.Get("pastureid").ValueStr()
  5483. ftid := parammaps.Get("ftid").ValueStr()
  5484. tx := restful.Engine.NewSession()
  5485. defer tx.Close()
  5486. tx.Begin()
  5487. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5488. if err != nil {
  5489. tx.Rollback()
  5490. logs.Error(err)
  5491. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5492. return
  5493. }
  5494. if parammaps.Get("type").ValueStr() == "1" {
  5495. _, err := tx.SQL(`UPDATE feedp fp
  5496. set
  5497. fp.ftweight= IFNULL(IF(
  5498. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5499. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5500. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5501. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5502. ),0),fp.feedweight = IFNULL(IF(
  5503. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5504. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5505. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5506. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5507. ),0) +ifnull(fp.supplyweight,0)
  5508. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5509. if err != nil {
  5510. tx.Rollback()
  5511. logs.Error(err)
  5512. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5513. return
  5514. }
  5515. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5516. _, err = tx.SQL(`
  5517. UPDATE fpdetail fpd
  5518. INNER JOIN feedp fp
  5519. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5520. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5521. ptuse= 0
  5522. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5523. if err != nil {
  5524. tx.Rollback()
  5525. logs.Error(err)
  5526. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5527. return
  5528. }
  5529. } else {
  5530. _, err := tx.SQL(`UPDATE feedp fp
  5531. SET
  5532. fp.supplyweight= IFNULL(IF(
  5533. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5534. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5535. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5536. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5537. ),0),fp.feedweight = IFNULL(IF(
  5538. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5539. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5540. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5541. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5542. ),0) + ifnull(fp.supplyweight,0)
  5543. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5544. if err != nil {
  5545. tx.Rollback()
  5546. logs.Error(err)
  5547. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5548. return
  5549. }
  5550. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5551. _, err = tx.SQL(`
  5552. UPDATE fpdetail fpd
  5553. INNER JOIN feedp fp
  5554. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5555. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5556. ptsrate = 0
  5557. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5558. if err != nil {
  5559. tx.Rollback()
  5560. logs.Error(err)
  5561. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5562. return
  5563. }
  5564. }
  5565. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5566. if err != nil {
  5567. tx.Rollback()
  5568. logs.Error(err)
  5569. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5570. return
  5571. }
  5572. err = tx.Commit()
  5573. if err != nil {
  5574. tx.Rollback()
  5575. logs.Error(err)
  5576. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5577. return
  5578. }
  5579. appG.Response(http.StatusOK, e.SUCCESS, true)
  5580. }
  5581. func DeleteSpillageAll(c *gin.Context) {
  5582. appG := app.Gin{C: c}
  5583. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5584. fsion := gofasion.NewFasion(string(dataByte))
  5585. parammaps := fsion.Get("parammaps")
  5586. pastureid := parammaps.Get("pastureid").ValueStr()
  5587. times := parammaps.Get("times").ValueStr()
  5588. barid := parammaps.Get("barid").ValueStr()
  5589. tx := restful.Engine.NewSession()
  5590. defer tx.Close()
  5591. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5592. if err != nil {
  5593. logs.Error(err)
  5594. appG.Response(http.StatusOK, e.ERROR, false)
  5595. return
  5596. }
  5597. now := time.Now()
  5598. for _, item := range lpplandtl1List {
  5599. go func(item map[string]interface{}) {
  5600. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5601. background,cowcount,ccountradio,lweighthis,createdate)
  5602. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5603. item["pastureid"], item["lppid"], item["barid"],
  5604. item["barname"], item["fpdid"], item["fttype"],
  5605. item["lweight"], item["sort"], item["tmrid"],
  5606. item["tmrname"], item["background"], item["cowcount"],
  5607. item["ccountradio"], item["lweighthis"], now).Execute()
  5608. if err != nil {
  5609. logs.Error(err)
  5610. appG.Response(http.StatusOK, e.ERROR, false)
  5611. return
  5612. }
  5613. }(item)
  5614. }
  5615. tx.Begin()
  5616. _, 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()
  5617. if err != nil {
  5618. tx.Rollback()
  5619. logs.Error(err)
  5620. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5621. return
  5622. }
  5623. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5624. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5625. if err != nil {
  5626. tx.Rollback()
  5627. logs.Error(err)
  5628. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5629. return
  5630. }
  5631. err = tx.Commit()
  5632. if err != nil {
  5633. tx.Rollback()
  5634. logs.Error(err)
  5635. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5636. return
  5637. }
  5638. appG.Response(http.StatusOK, e.SUCCESS, true)
  5639. }
  5640. func GetTMRListEnableTypeAll(c *gin.Context) {
  5641. appG := app.Gin{C: c}
  5642. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5643. fsion := gofasion.NewFasion(string(dataByte))
  5644. parammaps := fsion.Get("parammaps")
  5645. pastureid := parammaps.Get("pastureid").ValueStr()
  5646. tx := restful.Engine.NewSession()
  5647. defer tx.Close()
  5648. dataList, err := tx.SQL(`SELECT
  5649. eqcode,
  5650. tname,
  5651. datacaptureno,
  5652. trim(tclassid) tclassid,
  5653. concat(tname,' / ',eqcode) tmrmix,
  5654. d.label tclassname,
  5655. maxstirfeed,
  5656. remark,
  5657. tmr.enable,
  5658. TRIM(tmr.id) id,
  5659. TRIM(tmr.pastureid)pastureid
  5660. FROM
  5661. tmr
  5662. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5663. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5664. ORDER BY id DESC`, pastureid).Query().List()
  5665. if err != nil {
  5666. logs.Error(err)
  5667. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5668. return
  5669. }
  5670. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5671. if err != nil {
  5672. logs.Error(err)
  5673. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5674. return
  5675. }
  5676. var carNum int64
  5677. for _, sysopt := range sysoptData {
  5678. if sysopt["inforvalue"] == nil {
  5679. carNum = 1
  5680. } else {
  5681. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5682. }
  5683. }
  5684. id := 200
  5685. n := 0
  5686. for i := carNum; i > 0; i-- {
  5687. id++
  5688. n++
  5689. data := make(map[string]interface{}, 0)
  5690. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5691. data["tname"] = fmt.Sprintf("任意车%d", n)
  5692. data["datacaptureno"] = -2
  5693. data["tclassid"] = -2
  5694. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5695. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5696. data["maxstirfeed"] = 100000
  5697. data["remark"] = fmt.Sprintf("任意车%d", n)
  5698. data["enable"] = 1
  5699. data["id"] = fmt.Sprintf("%d", id)
  5700. data["pastureid"] = pastureid
  5701. dataList = append(dataList, data)
  5702. }
  5703. // UNION ALL
  5704. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5705. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5706. }
  5707. func GetFeedpHistory(c *gin.Context) {
  5708. appG := app.Gin{C: c}
  5709. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5710. fsion := gofasion.NewFasion(string(dataByte))
  5711. // parammaps := fsion.Get("parammaps")
  5712. bar := fsion.Get("barname").ValueStr()
  5713. startDate := fsion.Get("startDate").ValueStr()
  5714. endDate := fsion.Get("endDate").ValueStr()
  5715. tx := restful.Engine.NewSession()
  5716. defer tx.Close()
  5717. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5718. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5719. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5720. if err != nil {
  5721. logs.Error(err)
  5722. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5723. return
  5724. }
  5725. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5726. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5727. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5728. if err != nil {
  5729. logs.Error(err)
  5730. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5731. return
  5732. }
  5733. for _, feedp := range feedpList {
  5734. // LastftList, err := tx.SQL(` select tname ,id
  5735. // from feedtemplethistory where id = ?
  5736. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5737. // if err != nil {
  5738. // logs.Error(err)
  5739. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5740. // return
  5741. // }
  5742. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5743. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5744. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5745. if err != nil {
  5746. logs.Error(err)
  5747. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5748. return
  5749. }
  5750. var ftname interface{}
  5751. ftnamestatus := 0
  5752. ftname = feedp["ftname"]
  5753. var lastftid int64
  5754. if len(nextfeedpList) > 0 {
  5755. for _, ft := range nextfeedpList {
  5756. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5757. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5758. lastftid = ft["ftid"].(int64)
  5759. ftnamestatus = 1
  5760. break
  5761. }
  5762. }
  5763. }
  5764. for i, fpd := range fpdList {
  5765. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5766. fpd["weightstatus"] = 0
  5767. fpd["tratiostatus"] = 0
  5768. fpd["ftnamestatus"] = ftnamestatus
  5769. for k, fpd2 := range fpdList {
  5770. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5771. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5772. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5773. fpd["weightstatus"] = 1
  5774. }
  5775. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5776. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5777. fpd["tratiostatus"] = 1
  5778. }
  5779. break
  5780. }
  5781. }
  5782. fpd["barid"] = feedp["barid"]
  5783. fpd["barname"] = feedp["barname"]
  5784. fpd["ccount"] = feedp["ccount"]
  5785. fpd["ratio"] = feedp["ratio"]
  5786. fpd["ccountratio"] = feedp["ccountratio"]
  5787. fpd["ftid"] = feedp["ftid"]
  5788. fpd["ftname"] = ftname
  5789. fpd["ccountstatus"] = 0
  5790. fpd["ccountratiostatus"] = 0
  5791. fpd["ratiostatus"] = 0
  5792. fpd["ftnamestatus"] = 0
  5793. fpd["lastftid"] = lastftid
  5794. for _, next := range nextfeedpList {
  5795. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5796. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5797. fpd["ccountstatus"] = 1
  5798. }
  5799. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5800. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5801. fpd["ccountratiostatus"] = 1
  5802. }
  5803. if next["ratio"].(string) != fpd["ratio"].(string) {
  5804. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5805. fpd["ratiostatus"] = 1
  5806. }
  5807. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5808. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5809. // fpd["ftnamestatus"] = 1
  5810. // }
  5811. }
  5812. }
  5813. }
  5814. }
  5815. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5816. }
  5817. // func GetLpplandtl1History(c *gin.Context) {
  5818. // appG := app.Gin{C: c}
  5819. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5820. // fsion := gofasion.NewFasion(string(dataByte))
  5821. // // parammaps := fsion.Get("parammaps")
  5822. // barid := fsion.Get("barid").ValueStr()
  5823. // startDate := fsion.Get("startDate").ValueStr()
  5824. // endDate := fsion.Get("endDate").ValueStr()
  5825. // tx := restful.Engine.NewSession()
  5826. // defer tx.Close()
  5827. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5828. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5829. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5830. // // if err != nil {
  5831. // // logs.Error(err)
  5832. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5833. // // return
  5834. // // }
  5835. // // for _, feedp := range feedpList {
  5836. // // fmt.Println(feedp)
  5837. // // for i, fpd := range fpdList {
  5838. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5839. // // for k, fpd2 := range fpdList {
  5840. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5841. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5842. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5843. // // }
  5844. // // break
  5845. // // }
  5846. // // }
  5847. // // fpd["barid"] = feedp["barid"]
  5848. // // fpd["barname"] = feedp["barname"]
  5849. // // fpd["ccount"] = feedp["ccount"]
  5850. // // fpd["ratio"] = feedp["ratio"]
  5851. // // fpd["ccountratio"] = feedp["ccountratio"]
  5852. // // fpd["ftid"] = feedp["ftid"]
  5853. // // fpd["ftname"] = feedp["ftname"]
  5854. // // }
  5855. // // }
  5856. // // }
  5857. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5858. // }
  5859. func GetRemind(c *gin.Context) {
  5860. appG := app.Gin{C: c}
  5861. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5862. fsion := gofasion.NewFasion(string(dataByte))
  5863. parammaps := fsion.Get("parammaps")
  5864. pastureid := parammaps.Get("pastureid").ValueStr()
  5865. tx := restful.Engine.NewSession()
  5866. defer tx.Close()
  5867. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5868. if err != nil {
  5869. logs.Error(err)
  5870. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5871. return
  5872. }
  5873. // pastureid = "3"
  5874. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5875. if err != nil {
  5876. logs.Error(err)
  5877. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5878. return
  5879. }
  5880. defer resp.Body.Close()
  5881. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5882. buf.ReadFrom(resp.Body)
  5883. fmt.Println(string(buf.Bytes()))
  5884. respMap := make(map[string]interface{}, 0)
  5885. err = json.Unmarshal(buf.Bytes(), &respMap)
  5886. if err != nil {
  5887. logs.Error(err)
  5888. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5889. return
  5890. }
  5891. for _, data := range dataList {
  5892. r := make(map[string]interface{}, 0)
  5893. r["sys_name"] = ""
  5894. r["service_id"] = ""
  5895. r["pasture_id"] = ""
  5896. r["type_name"] = ""
  5897. r["remind_type_id"] = ""
  5898. r["remind_type"] = ""
  5899. r["push_date"] = ""
  5900. r["push_time"] = ""
  5901. r["interval_time"] = ""
  5902. r["push_limit"] = ""
  5903. r["template_id"] = ""
  5904. r["roles_id"] = ""
  5905. r["users_id"] = ""
  5906. r["date_type"] = ""
  5907. r["cycle_type"] = ""
  5908. data["data"] = r
  5909. for _, resp := range respMap["data"].([]interface{}) {
  5910. resp1 := resp.(map[string]interface{})
  5911. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5912. if resp1["push_time"] == nil {
  5913. resp1["push_time"] = ""
  5914. }
  5915. data["data"] = resp1
  5916. break
  5917. }
  5918. }
  5919. }
  5920. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5921. }
  5922. type NoticeMsgtype struct {
  5923. SysName string `json:"sys_name"`
  5924. PastureId int64 `json:"pasture_id"`
  5925. ServiceId int64 `json:"service_id"`
  5926. TypeName string `json:"type_name"`
  5927. RemindType int64 `json:"remind_type"`
  5928. PushDate int64 `json:"push_date"`
  5929. PushTime string `json:"push_time"`
  5930. IntervalTime int64 `json:"interval_time"`
  5931. PushLimit int64 `json:"push_limit"`
  5932. TemplateId string `json:"template_id"`
  5933. UsersId string `json:"users_id"`
  5934. DateType int64 `json:"date_type"`
  5935. CycleType int64 `json:"cycle_type"`
  5936. DelayTime int64 `json:"delay_time"`
  5937. Status int64 `json:"status"`
  5938. }
  5939. func UpdateRemind(c *gin.Context) {
  5940. appG := app.Gin{C: c}
  5941. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5942. parammaps := gofasion.NewFasion(string(dataByte))
  5943. // parammaps := fsion.Get("parammaps")
  5944. // user := parammaps.Get("user").ValueStr()
  5945. id := parammaps.Get("id").ValueInt64()
  5946. noticeMsgtype := new(NoticeMsgtype)
  5947. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  5948. noticeMsgtype.ServiceId = id
  5949. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  5950. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  5951. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  5952. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  5953. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  5954. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  5955. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  5956. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  5957. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  5958. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  5959. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  5960. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  5961. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  5962. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  5963. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  5964. //TODO
  5965. noticeMsgtype.SysName = "tmrWatch"
  5966. userList := parammaps.Get("user").Array()
  5967. var userstr []string
  5968. for _, user := range userList {
  5969. userstr = append(userstr, user.ValueStr())
  5970. }
  5971. tx := restful.Engine.NewSession()
  5972. defer tx.Close()
  5973. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  5974. if err != nil {
  5975. logs.Error(err)
  5976. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5977. return
  5978. }
  5979. // var jsonStr = []byte(noticeMsgtype
  5980. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  5981. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  5982. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  5983. req.Header.Set("Content-Type", "application/json")
  5984. client := &http.Client{}
  5985. resp, err := client.Do(req)
  5986. if err != nil {
  5987. logs.Error(err)
  5988. }
  5989. defer resp.Body.Close()
  5990. body, _ := ioutil.ReadAll(resp.Body)
  5991. fmt.Println("response Body:", string(body))
  5992. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  5993. if err != nil {
  5994. logs.Error(err)
  5995. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5996. return
  5997. }
  5998. defer getresp.Body.Close()
  5999. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6000. buf.ReadFrom(getresp.Body)
  6001. // fmt.Println(string(buf.Bytes()))
  6002. respMap := make(map[string]interface{}, 0)
  6003. err = json.Unmarshal(buf.Bytes(), &respMap)
  6004. if err != nil {
  6005. logs.Error(err)
  6006. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6007. return
  6008. }
  6009. for _, resp := range respMap["data"].([]interface{}) {
  6010. resp1 := resp.(map[string]interface{})
  6011. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6012. if err != nil {
  6013. logs.Error(err)
  6014. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6015. return
  6016. }
  6017. }
  6018. appG.Response(http.StatusOK, e.SUCCESS, true)
  6019. }
  6020. func GetSpillageallHistory(c *gin.Context) {
  6021. appG := app.Gin{C: c}
  6022. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6023. parammaps := gofasion.NewFasion(string(dataByte))
  6024. barname := parammaps.Get("barname").ValueStr()
  6025. pastureid := parammaps.Get("pastureid").ValueStr()
  6026. startdate := parammaps.Get("startDate").ValueStr()
  6027. enddate := parammaps.Get("endDate").ValueStr()
  6028. tx := restful.Engine.NewSession()
  6029. defer tx.Close()
  6030. 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
  6031. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6032. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6033. if err != nil {
  6034. logs.Error(err)
  6035. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6036. return
  6037. }
  6038. respMap := make([]map[string]interface{}, 0)
  6039. data := make(map[interface{}]interface{})
  6040. for _, history := range historyList {
  6041. data[history["createdate"]] = history["createdate"]
  6042. }
  6043. createList := []string{}
  6044. for _, v := range data {
  6045. createList = append(createList, v.(string))
  6046. }
  6047. // sort.Sort()
  6048. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6049. sort.Slice(createList, func(i, j int) bool {
  6050. return createList[i] > createList[j]
  6051. })
  6052. for _, v := range createList {
  6053. a := make(map[string]interface{})
  6054. a["createdate"] = data[v]
  6055. // createList = append(createList, v.(string))
  6056. respMap = append(respMap, a)
  6057. }
  6058. number := 0
  6059. dataMap := make([]interface{}, 0)
  6060. for k, resp := range respMap {
  6061. createdate := resp["createdate"].(string)
  6062. var nextcreatedate string
  6063. if len(respMap) > k+1 {
  6064. nextcreatedate = respMap[k+1]["createdate"].(string)
  6065. }
  6066. // dataList := make(map[string][]interface{})
  6067. // list := make(map[string]interface{})
  6068. times := make(map[interface{}]int)
  6069. for _, history := range historyList {
  6070. // List := make(map[interface{}][]interface{})
  6071. i := 0
  6072. if history["createdate"].(string) == createdate {
  6073. times[history["times"]]++
  6074. data := make(map[string]interface{})
  6075. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6076. // exist := false
  6077. if nextcreatedate != "" {
  6078. for _, history1 := range historyList {
  6079. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6080. history1["times"].(int64) == history["times"].(int64) {
  6081. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6082. break
  6083. // exist = true
  6084. }
  6085. }
  6086. }
  6087. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6088. i++
  6089. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6090. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6091. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6092. // resp["times"] = history["times"]
  6093. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6094. data1 := make(map[string]interface{})
  6095. data1["times"] = history["times"]
  6096. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6097. data1["createdate"] = resp["createdate"]
  6098. // fmt.Println(dataList)
  6099. dataMap = append(dataMap, data1)
  6100. }
  6101. if i > number {
  6102. number = i
  6103. }
  6104. // respMap = append(respMap, dataList)
  6105. }
  6106. // for k, data := range dataList {
  6107. // resp[k] = data
  6108. // }
  6109. // resp["data"] = dataList
  6110. }
  6111. // resp := make(map[string]interface{})
  6112. // sort.Strings(createList)
  6113. //
  6114. // for _, create := range createList {
  6115. // for _, r := range respMap {
  6116. // if create == r["createdate"].(string) {
  6117. // resp[create] = r
  6118. // break
  6119. // }
  6120. // }
  6121. // }
  6122. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6123. var trainsList []interface{}
  6124. for i := 0; i < number; i++ {
  6125. trains := make(map[string]interface{})
  6126. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6127. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6128. trainsList = append(trainsList, trains)
  6129. }
  6130. respdata := make(map[string]interface{})
  6131. respdata["data"] = dataMap
  6132. respdata["trains"] = trainsList
  6133. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6134. }
  6135. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6136. appG := app.Gin{C: c}
  6137. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6138. parammaps := gofasion.NewFasion(string(dataByte))
  6139. ftid := parammaps.Get("ftid").ValueInt64()
  6140. lastftid := parammaps.Get("lastftid").ValueInt64()
  6141. pastureid := parammaps.Get("pastureid").ValueInt64()
  6142. // createdate := parammaps.Get("createdate").ValueStr()
  6143. tx := restful.Engine.NewSession()
  6144. defer tx.Close()
  6145. data := make(map[string]interface{})
  6146. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6147. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6148. if err != nil {
  6149. logs.Error(err)
  6150. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6151. return
  6152. }
  6153. feedtemplet := make(map[string]interface{})
  6154. for _, f := range feedtempletList {
  6155. feedtemplet = f
  6156. }
  6157. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  6158. if err != nil {
  6159. logs.Error(err)
  6160. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6161. return
  6162. }
  6163. feedtemplet["fit"] = fitList
  6164. data["current"] = feedtemplet
  6165. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6166. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6167. if err != nil {
  6168. logs.Error(err)
  6169. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6170. return
  6171. }
  6172. lastfeedtemplet := make(map[string]interface{})
  6173. for _, f := range lastfeedtempletList {
  6174. lastfeedtemplet = f
  6175. }
  6176. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  6177. if err != nil {
  6178. logs.Error(err)
  6179. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6180. return
  6181. }
  6182. lastfeedtemplet["fit"] = lastfitList
  6183. data["last"] = lastfeedtemplet
  6184. appG.Response(http.StatusOK, e.SUCCESS, data)
  6185. }
  6186. func GetFeedtempletHistory(c *gin.Context) {
  6187. appG := app.Gin{C: c}
  6188. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6189. parammaps := gofasion.NewFasion(string(dataByte))
  6190. ftid := parammaps.Get("ftid").ValueStr()
  6191. pastureid := parammaps.Get("pastureid").ValueInt64()
  6192. start := parammaps.Get("startdate").ValueStr()
  6193. end := parammaps.Get("enddate").ValueStr()
  6194. tx := restful.Engine.NewSession()
  6195. defer tx.Close()
  6196. 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 ?
  6197. and id = ? and pastureid = ? order by createdate desc `,
  6198. start, end, ftid, pastureid).Query().List()
  6199. if err != nil {
  6200. logs.Error(err)
  6201. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6202. return
  6203. }
  6204. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6205. ftid, pastureid).Query().List()
  6206. if err != nil {
  6207. logs.Error(err)
  6208. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6209. return
  6210. }
  6211. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6212. for i, ft := range ftList {
  6213. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6214. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6215. (select empname from user where id = fit.userId) empname,
  6216. 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
  6217. where fit.fitid = ?
  6218. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6219. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6220. if err != nil {
  6221. logs.Error(err)
  6222. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6223. return
  6224. }
  6225. ft["createdate"] = ft["createdate1"]
  6226. // data["tname"] = ft["tname"]
  6227. // data["tcode"] = ft["tcode"]
  6228. // data["tcolor"] = ft["tcolor"]
  6229. // data["fttype"] = ft["fttype"]
  6230. // data["ccname"] = ft["ccname"]
  6231. // data["source"] = ft["source"]
  6232. // data["version"] = ft["version"]
  6233. // data["remark"] = ft["remark"]
  6234. for n, ft2 := range ftList {
  6235. if i < n {
  6236. if ft["tname"].(string) != ft2["tname"].(string) {
  6237. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6238. }
  6239. if _, ok := ft["tcode"]; ok {
  6240. if _, ok := ft2["tcode"]; ok {
  6241. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6242. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6243. }
  6244. }
  6245. }
  6246. if _, ok := ft["tcolor"]; ok {
  6247. if _, ok := ft2["tcolor"]; ok {
  6248. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6249. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6250. }
  6251. }
  6252. }
  6253. if _, ok := ft["fttype"]; ok {
  6254. if _, ok := ft2["fttype"]; ok {
  6255. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6256. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6257. }
  6258. }
  6259. }
  6260. if _, ok := ft["ccname"]; ok {
  6261. if _, ok := ft2["ccname"]; ok {
  6262. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6263. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6264. }
  6265. }
  6266. }
  6267. if _, ok := ft["source"]; ok {
  6268. if _, ok := ft2["source"]; ok {
  6269. if ft["source"].(string) != ft2["source"].(string) {
  6270. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6271. }
  6272. }
  6273. }
  6274. if _, ok := ft["version"]; ok {
  6275. if _, ok := ft2["version"]; ok {
  6276. if ft["version"].(int64) != ft2["version"].(int64) {
  6277. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6278. }
  6279. }
  6280. }
  6281. if _, ok := ft["remark"]; ok {
  6282. if _, ok := ft2["remark"]; ok {
  6283. if ft["remark"].(string) != ft2["remark"].(string) {
  6284. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6285. }
  6286. }
  6287. }
  6288. break
  6289. }
  6290. }
  6291. dataList := make([]map[string]interface{}, 0)
  6292. if len(fithisList) > 0 {
  6293. for _, fit := range fithisList {
  6294. data := make(map[string]interface{})
  6295. data["feedgroup"] = fit["feedgroup"]
  6296. data["fname"] = fit["fname"]
  6297. data["empname"] = fit["empname"]
  6298. if fit["Eweight"] != nil {
  6299. if fit["Eweight"].(string) != fit["weight"].(string) {
  6300. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6301. } else {
  6302. data["fweight"] = fit["Eweight"]
  6303. }
  6304. data["fweightstatus"] = 1
  6305. } else {
  6306. data["fweight"] = fit["weight"]
  6307. data["fweightstatus"] = 0
  6308. }
  6309. data["autosecond"] = fit["autosecond"]
  6310. // data["tname"] = ft["tname"]
  6311. // data["tcode"] = ft["tcode"]
  6312. // data["tcolor"] = ft["tcolor"]
  6313. // data["fttype"] = ft["fttype"]
  6314. // data["ccname"] = ft["ccname"]
  6315. // data["source"] = ft["source"]
  6316. // data["version"] = ft["version"]
  6317. // data["remark"] = ft["remark"]
  6318. // data["createdate"] = ft["createdate1"]
  6319. // ft["fit"] = data
  6320. dataList = append(dataList, data)
  6321. }
  6322. } else {
  6323. for _, fit := range ftdetailList {
  6324. data := make(map[string]interface{})
  6325. data["feedgroup"] = fit["feedgroup"]
  6326. data["fname"] = fit["fname"]
  6327. // if fit["Eweight"] != nil {
  6328. // data["weight"] = fit["Eweight"]
  6329. // } else {
  6330. data["fweight"] = fit["fweight"]
  6331. // }
  6332. data["autosecond"] = fit["autosecond"]
  6333. // ft["fit"] = data
  6334. dataList = append(dataList, data)
  6335. }
  6336. }
  6337. ft["fit"] = dataList
  6338. }
  6339. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6340. }
  6341. func UpdateMaterialTMR(c *gin.Context) {
  6342. appG := app.Gin{C: c}
  6343. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6344. parammaps := gofasion.NewFasion(string(dataByte))
  6345. tmrid := parammaps.Get("tmrid").ValueStr()
  6346. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6347. lppid := parammaps.Get("lppid").ValueStr()
  6348. times := parammaps.Get("times").ValueStr()
  6349. pastureid := parammaps.Get("pastureid").ValueStr()
  6350. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6351. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6352. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6353. tx := restful.Engine.NewSession()
  6354. defer tx.Close()
  6355. tx.Begin()
  6356. if tmrid != "1000" {
  6357. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6358. if err != nil {
  6359. logs.Error(err)
  6360. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6361. return
  6362. }
  6363. var maxstirfeed float64
  6364. for _, tmr := range tmrList {
  6365. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6366. }
  6367. if status == 0 {
  6368. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6369. if err != nil {
  6370. tx.Rollback()
  6371. logs.Error(err)
  6372. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6373. return
  6374. }
  6375. var lweight float64
  6376. for _, item := range lpplandtl1List {
  6377. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6378. lweight += fl
  6379. }
  6380. if lweight > maxstirfeed {
  6381. lweight = lweight - maxstirfeed
  6382. } else {
  6383. lweight = 0
  6384. }
  6385. if lweight > 0 {
  6386. lweight1 := lweight / float64(len(lpplandtl1List))
  6387. number := 0
  6388. for _, item := range lpplandtl1List {
  6389. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6390. if lweight1 >= fl {
  6391. number++
  6392. }
  6393. }
  6394. lweight := lweight / float64((len(lpplandtl1List) - number))
  6395. for _, item := range lpplandtl1List {
  6396. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6397. if lweight1 >= fl {
  6398. continue
  6399. }
  6400. if tmrtype == "1" {
  6401. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6402. if err != nil {
  6403. tx.Rollback()
  6404. logs.Error(err)
  6405. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6406. return
  6407. }
  6408. } else if tmrtype == "2" {
  6409. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6410. if err != nil {
  6411. tx.Rollback()
  6412. logs.Error(err)
  6413. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6414. return
  6415. }
  6416. }
  6417. if item["fttype"].(int64) == 0 {
  6418. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6419. if err != nil {
  6420. tx.Rollback()
  6421. logs.Error(err)
  6422. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6423. return
  6424. }
  6425. } else {
  6426. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6427. if err != nil {
  6428. tx.Rollback()
  6429. logs.Error(err)
  6430. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6431. return
  6432. }
  6433. }
  6434. }
  6435. } else {
  6436. for _, item := range lpplandtl1List {
  6437. // 自走式
  6438. if tmrtype == "1" {
  6439. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6440. if err != nil {
  6441. logs.Error(err)
  6442. tx.Rollback()
  6443. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6444. return
  6445. }
  6446. } else if tmrtype == "2" {
  6447. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6448. if err != nil {
  6449. logs.Error(err)
  6450. tx.Rollback()
  6451. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6452. return
  6453. }
  6454. }
  6455. }
  6456. }
  6457. } else if status == 1 {
  6458. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6459. if err != nil {
  6460. logs.Error(err)
  6461. tx.Rollback()
  6462. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6463. return
  6464. }
  6465. var lweight float64
  6466. for _, item := range lpplandtl1List {
  6467. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6468. lweight += fl
  6469. }
  6470. if lweight > maxstirfeed {
  6471. lweight = lweight - maxstirfeed
  6472. } else {
  6473. lweight = 0
  6474. }
  6475. for _, item := range lpplandtl1List {
  6476. if lweight > 0 {
  6477. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6478. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6479. if fl >= lweight {
  6480. item["lweight"] = fl - lweight
  6481. lweight = 0
  6482. if tmrtype == "1" {
  6483. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6484. if err != nil {
  6485. logs.Error(err)
  6486. tx.Rollback()
  6487. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6488. return
  6489. }
  6490. } else if tmrtype == "2" {
  6491. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6492. if err != nil {
  6493. logs.Error(err)
  6494. tx.Rollback()
  6495. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6496. return
  6497. }
  6498. }
  6499. if item["fttype"].(int64) == 0 {
  6500. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6501. if err != nil {
  6502. logs.Error(err)
  6503. tx.Rollback()
  6504. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6505. return
  6506. }
  6507. } else {
  6508. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6509. if err != nil {
  6510. logs.Error(err)
  6511. tx.Rollback()
  6512. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6513. return
  6514. }
  6515. }
  6516. } else {
  6517. lweight = lweight - fl
  6518. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6519. if err != nil {
  6520. logs.Error(err)
  6521. tx.Rollback()
  6522. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6523. return
  6524. }
  6525. if item["fttype"].(int64) == 0 {
  6526. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6527. if err != nil {
  6528. logs.Error(err)
  6529. tx.Rollback()
  6530. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6531. return
  6532. }
  6533. } else {
  6534. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6535. if err != nil {
  6536. logs.Error(err)
  6537. tx.Rollback()
  6538. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6539. return
  6540. }
  6541. }
  6542. }
  6543. } else {
  6544. // 自走式
  6545. if tmrtype == "1" {
  6546. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6547. if err != nil {
  6548. logs.Error(err)
  6549. tx.Rollback()
  6550. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6551. return
  6552. }
  6553. } else if tmrtype == "2" {
  6554. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6555. if err != nil {
  6556. logs.Error(err)
  6557. tx.Rollback()
  6558. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6559. return
  6560. }
  6561. }
  6562. }
  6563. }
  6564. } else {
  6565. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6566. if err != nil {
  6567. logs.Error(err)
  6568. tx.Rollback()
  6569. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6570. return
  6571. }
  6572. for _, item := range lpplandtl1List {
  6573. if item["fttype"].(int64) == 0 {
  6574. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).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 fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).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. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6591. if err != nil {
  6592. logs.Error(err)
  6593. tx.Rollback()
  6594. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6595. return
  6596. }
  6597. }
  6598. }
  6599. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6600. if err != nil {
  6601. logs.Error(err)
  6602. tx.Rollback()
  6603. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6604. return
  6605. }
  6606. } else {
  6607. if status == 2 {
  6608. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6609. if err != nil {
  6610. logs.Error(err)
  6611. tx.Rollback()
  6612. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6613. return
  6614. }
  6615. for _, item := range lpplandtl1List {
  6616. if item["fttype"].(int64) == 0 {
  6617. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6618. if err != nil {
  6619. logs.Error(err)
  6620. tx.Rollback()
  6621. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6622. return
  6623. }
  6624. } else {
  6625. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6626. if err != nil {
  6627. logs.Error(err)
  6628. tx.Rollback()
  6629. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6630. return
  6631. }
  6632. }
  6633. }
  6634. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6635. if err != nil {
  6636. logs.Error(err)
  6637. tx.Rollback()
  6638. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6639. return
  6640. }
  6641. } else {
  6642. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6643. if err != nil {
  6644. logs.Error(err)
  6645. tx.Rollback()
  6646. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6647. return
  6648. }
  6649. }
  6650. }
  6651. err := tx.Commit()
  6652. if err != nil {
  6653. logs.Error(err)
  6654. tx.Rollback()
  6655. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6656. return
  6657. }
  6658. appG.Response(http.StatusOK, e.SUCCESS, true)
  6659. }
  6660. func UpdateMaterialTMRDate(c *gin.Context) {
  6661. appG := app.Gin{C: c}
  6662. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6663. parammaps := gofasion.NewFasion(string(dataByte))
  6664. tmrid := parammaps.Get("tmrid").ValueStr()
  6665. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6666. lppid := parammaps.Get("lppid").ValueStr()
  6667. times := parammaps.Get("times").ValueStr()
  6668. pastureid := parammaps.Get("pastureid").ValueStr()
  6669. date := parammaps.Get("date").ValueStr()
  6670. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6671. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6672. tx := restful.Engine.NewSession()
  6673. defer tx.Close()
  6674. tx.Begin()
  6675. if tmrid != "1000" {
  6676. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6677. if err != nil {
  6678. logs.Error(err)
  6679. tx.Rollback()
  6680. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6681. return
  6682. }
  6683. var maxstirfeed float64
  6684. for _, tmr := range tmrList {
  6685. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6686. }
  6687. if status == 0 {
  6688. 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()
  6689. if err != nil {
  6690. logs.Error(err)
  6691. tx.Rollback()
  6692. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6693. return
  6694. }
  6695. var lweight float64
  6696. for _, item := range lpplandtl1List {
  6697. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6698. lweight += fl
  6699. }
  6700. if lweight > maxstirfeed {
  6701. lweight = lweight - maxstirfeed
  6702. } else {
  6703. lweight = 0
  6704. }
  6705. if lweight > 0 {
  6706. lweight1 := lweight / float64(len(lpplandtl1List))
  6707. number := 0
  6708. for _, item := range lpplandtl1List {
  6709. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6710. if lweight1 >= fl {
  6711. number++
  6712. }
  6713. }
  6714. lweight := lweight / float64((len(lpplandtl1List) - number))
  6715. for _, item := range lpplandtl1List {
  6716. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6717. if lweight1 >= fl {
  6718. continue
  6719. }
  6720. if tmrtype == "1" {
  6721. _, 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()
  6722. if err != nil {
  6723. logs.Error(err)
  6724. tx.Rollback()
  6725. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6726. return
  6727. }
  6728. } else if tmrtype == "2" {
  6729. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6730. if err != nil {
  6731. logs.Error(err)
  6732. tx.Rollback()
  6733. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6734. return
  6735. }
  6736. }
  6737. if item["fttype"].(int64) == 0 {
  6738. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6739. if err != nil {
  6740. logs.Error(err)
  6741. tx.Rollback()
  6742. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6743. return
  6744. }
  6745. } else {
  6746. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6747. if err != nil {
  6748. logs.Error(err)
  6749. tx.Rollback()
  6750. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6751. return
  6752. }
  6753. }
  6754. }
  6755. } else {
  6756. for _, item := range lpplandtl1List {
  6757. // 自走式
  6758. if tmrtype == "1" {
  6759. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6760. if err != nil {
  6761. logs.Error(err)
  6762. tx.Rollback()
  6763. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6764. return
  6765. }
  6766. } else if tmrtype == "2" {
  6767. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6768. if err != nil {
  6769. logs.Error(err)
  6770. tx.Rollback()
  6771. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6772. return
  6773. }
  6774. }
  6775. }
  6776. }
  6777. } else if status == 1 {
  6778. 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()
  6779. if err != nil {
  6780. logs.Error(err)
  6781. tx.Rollback()
  6782. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6783. return
  6784. }
  6785. var lweight float64
  6786. for _, item := range lpplandtl1List {
  6787. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6788. lweight += fl
  6789. }
  6790. if lweight > maxstirfeed {
  6791. lweight = lweight - maxstirfeed
  6792. } else {
  6793. lweight = 0
  6794. }
  6795. for _, item := range lpplandtl1List {
  6796. if lweight > 0 {
  6797. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6798. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6799. if fl >= lweight {
  6800. item["lweight"] = fl - lweight
  6801. lweight = 0
  6802. if tmrtype == "1" {
  6803. _, 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()
  6804. if err != nil {
  6805. logs.Error(err)
  6806. tx.Rollback()
  6807. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6808. return
  6809. }
  6810. } else if tmrtype == "2" {
  6811. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6812. if err != nil {
  6813. logs.Error(err)
  6814. tx.Rollback()
  6815. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6816. return
  6817. }
  6818. }
  6819. if item["fttype"].(int64) == 0 {
  6820. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6821. if err != nil {
  6822. logs.Error(err)
  6823. tx.Rollback()
  6824. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6825. return
  6826. }
  6827. } else {
  6828. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6829. if err != nil {
  6830. logs.Error(err)
  6831. tx.Rollback()
  6832. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6833. return
  6834. }
  6835. }
  6836. } else {
  6837. lweight = lweight - fl
  6838. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6839. if err != nil {
  6840. logs.Error(err)
  6841. tx.Rollback()
  6842. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6843. return
  6844. }
  6845. if item["fttype"].(int64) == 0 {
  6846. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6847. if err != nil {
  6848. logs.Error(err)
  6849. tx.Rollback()
  6850. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6851. return
  6852. }
  6853. } else {
  6854. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6855. if err != nil {
  6856. logs.Error(err)
  6857. tx.Rollback()
  6858. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6859. return
  6860. }
  6861. }
  6862. }
  6863. } else {
  6864. // 自走式
  6865. if tmrtype == "1" {
  6866. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6867. if err != nil {
  6868. logs.Error(err)
  6869. tx.Rollback()
  6870. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6871. return
  6872. }
  6873. } else if tmrtype == "2" {
  6874. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6875. if err != nil {
  6876. logs.Error(err)
  6877. tx.Rollback()
  6878. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6879. return
  6880. }
  6881. }
  6882. }
  6883. }
  6884. } else {
  6885. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6886. if err != nil {
  6887. logs.Error(err)
  6888. tx.Rollback()
  6889. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6890. return
  6891. }
  6892. for _, item := range lpplandtl1List {
  6893. if item["fttype"].(int64) == 0 {
  6894. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6895. if err != nil {
  6896. logs.Error(err)
  6897. tx.Rollback()
  6898. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6899. return
  6900. }
  6901. } else {
  6902. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6903. if err != nil {
  6904. logs.Error(err)
  6905. tx.Rollback()
  6906. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6907. return
  6908. }
  6909. }
  6910. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6911. if err != nil {
  6912. logs.Error(err)
  6913. tx.Rollback()
  6914. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6915. return
  6916. }
  6917. }
  6918. }
  6919. _, 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()
  6920. if err != nil {
  6921. logs.Error(err)
  6922. tx.Rollback()
  6923. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6924. return
  6925. }
  6926. } else {
  6927. if status == 2 {
  6928. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  6929. if err != nil {
  6930. logs.Error(err)
  6931. tx.Rollback()
  6932. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6933. return
  6934. }
  6935. for _, item := range lpplandtl1List {
  6936. if item["fttype"].(int64) == 0 {
  6937. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6938. if err != nil {
  6939. logs.Error(err)
  6940. tx.Rollback()
  6941. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6942. return
  6943. }
  6944. } else {
  6945. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6946. if err != nil {
  6947. logs.Error(err)
  6948. tx.Rollback()
  6949. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6950. return
  6951. }
  6952. }
  6953. }
  6954. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  6955. if err != nil {
  6956. logs.Error(err)
  6957. tx.Rollback()
  6958. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6959. return
  6960. }
  6961. } else {
  6962. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  6963. if err != nil {
  6964. logs.Error(err)
  6965. tx.Rollback()
  6966. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6967. return
  6968. }
  6969. }
  6970. }
  6971. err := tx.Commit()
  6972. if err != nil {
  6973. logs.Error(err)
  6974. tx.Rollback()
  6975. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6976. return
  6977. }
  6978. appG.Response(http.StatusOK, e.SUCCESS, true)
  6979. }
  6980. func Decimal(value float64) float64 {
  6981. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  6982. return value
  6983. }
  6984. func UpdateDailyData(c *gin.Context) {
  6985. appG := app.Gin{C: c}
  6986. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6987. parammaps := gofasion.NewFasion(string(dataByte))
  6988. pid := parammaps.Get("pid").ValueDefaultStr("0")
  6989. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  6990. sort := parammaps.Get("sort").ValueDefaultStr("0")
  6991. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  6992. date := parammaps.Get("date").ValueStr()
  6993. tx := restful.Engine.NewSession()
  6994. defer tx.Close()
  6995. 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()
  6996. if err != nil {
  6997. logs.Error("UpdateDailyData-error-0:", err)
  6998. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  6999. return
  7000. }
  7001. if count > 0 {
  7002. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7003. return
  7004. }
  7005. tx.Begin()
  7006. if location == 0 {
  7007. fid := parammaps.Get("fid").ValueStr()
  7008. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  7009. if err != nil {
  7010. logs.Error("UpdateDailyData-error-1:", err)
  7011. tx.Rollback()
  7012. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7013. return
  7014. }
  7015. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7016. if err != nil {
  7017. logs.Error("UpdateDailyData-error-1:", err)
  7018. tx.Rollback()
  7019. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7020. return
  7021. }
  7022. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7023. if err != nil {
  7024. fmt.Println("Error:", err)
  7025. return
  7026. }
  7027. actualWeight := weight - num
  7028. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7029. if err != nil {
  7030. logs.Error("UpdateDailyData-error-2:", err)
  7031. tx.Rollback()
  7032. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7033. return
  7034. }
  7035. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7036. if err != nil {
  7037. logs.Error("UpdateDailyData-error-3:", err)
  7038. tx.Rollback()
  7039. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7040. return
  7041. }
  7042. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7043. if err != nil {
  7044. logs.Error("UpdateDailyData-error-4:", err)
  7045. tx.Rollback()
  7046. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7047. return
  7048. }
  7049. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7050. if err != nil {
  7051. logs.Error("UpdateDailyData-error-5:", err)
  7052. tx.Rollback()
  7053. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7054. return
  7055. }
  7056. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7057. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7058. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7059. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7060. if err != nil {
  7061. fmt.Println("Error:", err)
  7062. return
  7063. }
  7064. // actual := actualWeight / float64(len(downloadedplanList))
  7065. for _, item := range downloadedplanList {
  7066. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7067. if err != nil {
  7068. fmt.Println("Error:", err)
  7069. return
  7070. }
  7071. actual := itemLweight / lweight * actualWeight
  7072. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7073. if err != nil {
  7074. logs.Error("UpdateDailyData-error-6:", err)
  7075. tx.Rollback()
  7076. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7077. return
  7078. }
  7079. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7080. if err != nil {
  7081. logs.Error("UpdateDailyData-error-7:", err)
  7082. tx.Rollback()
  7083. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7084. return
  7085. }
  7086. _, 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()
  7087. if err != nil {
  7088. logs.Error("UpdateDailyData-error-8:", err)
  7089. tx.Rollback()
  7090. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7091. return
  7092. }
  7093. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7094. if err != nil {
  7095. logs.Error("UpdateDailyData-error-9:", err)
  7096. tx.Rollback()
  7097. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7098. return
  7099. }
  7100. }
  7101. } else {
  7102. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7103. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7104. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7105. // if err != nil {
  7106. // fmt.Println("Error:", err)
  7107. // return
  7108. // }
  7109. for _, item := range downloadedplanList {
  7110. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7111. if err != nil {
  7112. logs.Error("UpdateDailyData-error-6:", err)
  7113. tx.Rollback()
  7114. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7115. return
  7116. }
  7117. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7118. item["lweight"], actualWeight, item["id"]).Execute()
  7119. if err != nil {
  7120. logs.Error("UpdateDailyData-error-7:", err)
  7121. tx.Rollback()
  7122. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7123. return
  7124. }
  7125. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7126. where pid = ?`, item["id"]).Execute()
  7127. if err != nil {
  7128. logs.Error("UpdateDailyData-error-8:", err)
  7129. tx.Rollback()
  7130. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7131. return
  7132. }
  7133. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7134. if err != nil {
  7135. logs.Error("UpdateDailyData-error-9:", err)
  7136. tx.Rollback()
  7137. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7138. return
  7139. }
  7140. }
  7141. }
  7142. } else {
  7143. fbarid := parammaps.Get("fbarid").ValueStr()
  7144. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7145. if err != nil {
  7146. logs.Error("UpdateDailyData-error-10:", err)
  7147. tx.Rollback()
  7148. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7149. return
  7150. }
  7151. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7152. if err != nil {
  7153. logs.Error("UpdateDailyData-error-1:", err)
  7154. tx.Rollback()
  7155. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7156. return
  7157. }
  7158. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7159. if err != nil {
  7160. fmt.Println("Error:", err)
  7161. return
  7162. }
  7163. actualWeight := weight - num
  7164. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7165. if err != nil {
  7166. logs.Error("UpdateDailyData-error-11:", err)
  7167. tx.Rollback()
  7168. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7169. return
  7170. }
  7171. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  7172. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7173. if err != nil {
  7174. logs.Error("UpdateDailyData-error-12:", err)
  7175. tx.Rollback()
  7176. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7177. return
  7178. }
  7179. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7180. where pid = ? `, pid).Execute()
  7181. if err != nil {
  7182. logs.Error("UpdateDailyData-error-13:", err)
  7183. tx.Rollback()
  7184. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7185. return
  7186. }
  7187. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7188. if err != nil {
  7189. logs.Error("UpdateDailyData-error-14:", err)
  7190. tx.Rollback()
  7191. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7192. return
  7193. }
  7194. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7195. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7196. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7197. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7198. if err != nil {
  7199. fmt.Println("Error:", err)
  7200. return
  7201. }
  7202. for _, item := range downloadedplanList {
  7203. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7204. if err != nil {
  7205. fmt.Println("Error:", err)
  7206. return
  7207. }
  7208. actual := itemLweight / lweight * actualWeight
  7209. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7210. if err != nil {
  7211. logs.Error("UpdateDailyData-error-6:", err)
  7212. tx.Rollback()
  7213. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7214. return
  7215. }
  7216. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7217. if err != nil {
  7218. logs.Error("UpdateDailyData-error-7:", err)
  7219. tx.Rollback()
  7220. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7221. return
  7222. }
  7223. _, 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()
  7224. if err != nil {
  7225. logs.Error("UpdateDailyData-error-8:", err)
  7226. tx.Rollback()
  7227. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7228. return
  7229. }
  7230. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7231. if err != nil {
  7232. logs.Error("UpdateDailyData-error-9:", err)
  7233. tx.Rollback()
  7234. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7235. return
  7236. }
  7237. }
  7238. } else {
  7239. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7240. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7241. for _, item := range downloadedplanList {
  7242. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7243. // if err != nil {
  7244. // fmt.Println("Error:", err)
  7245. // return
  7246. // }
  7247. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7248. if err != nil {
  7249. logs.Error("UpdateDailyData-error-6:", err)
  7250. tx.Rollback()
  7251. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7252. return
  7253. }
  7254. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7255. item["lweight"], actualWeight, item["id"]).Execute()
  7256. if err != nil {
  7257. logs.Error("UpdateDailyData-error-7:", err)
  7258. tx.Rollback()
  7259. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7260. return
  7261. }
  7262. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7263. where pid = ?`, item["id"]).Execute()
  7264. if err != nil {
  7265. logs.Error("UpdateDailyData-error-8:", err)
  7266. tx.Rollback()
  7267. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7268. return
  7269. }
  7270. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7271. if err != nil {
  7272. logs.Error("UpdateDailyData-error-9:", err)
  7273. tx.Rollback()
  7274. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7275. return
  7276. }
  7277. }
  7278. }
  7279. }
  7280. err = tx.Commit()
  7281. if err != nil {
  7282. logs.Error("UpdateDailyData-error-20:", err)
  7283. tx.Rollback()
  7284. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7285. return
  7286. }
  7287. appG.Response(http.StatusOK, e.SUCCESS, true)
  7288. }
  7289. func GetFormulaStatistics(c *gin.Context) {
  7290. appG := app.Gin{C: c}
  7291. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7292. parammaps := gofasion.NewFasion(string(dataByte))
  7293. startTime := parammaps.Get("startTime").ValueStr()
  7294. endTime := parammaps.Get("endTime").ValueStr()
  7295. pastureId := parammaps.Get("pastureId").ValueStr()
  7296. tx := restful.Engine.NewSession()
  7297. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7298. if err != nil {
  7299. logs.Error("GetFormulaStatistics-error-1:", err)
  7300. tx.Rollback()
  7301. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7302. return
  7303. }
  7304. var feedtemplet, dateList []string
  7305. for _, f := range feedtempletList {
  7306. feedtemplet = append(feedtemplet, f["tname"].(string))
  7307. }
  7308. layout := "2006-01-02"
  7309. // s := "2023-05-01"
  7310. // e := "2023-05-23"
  7311. start, err := time.Parse(layout, startTime)
  7312. if err != nil {
  7313. fmt.Println(err)
  7314. return
  7315. }
  7316. end, err := time.Parse(layout, endTime)
  7317. if err != nil {
  7318. fmt.Println(err)
  7319. return
  7320. }
  7321. end = end.AddDate(0, 0, 1)
  7322. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7323. dateList = append(dateList, d.Format("2006-01-02"))
  7324. }
  7325. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7326. join feedtempletdate ft on ft.id = d.tempid and ft.date = d.mydate join feedtemplet ftd on ftd.id = ft.id where d.mydate between ? and ? and d.lpplantype in(0,1) and d.iscompleted = 1 and d.pastureId= ?
  7327. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7328. if err != nil {
  7329. logs.Error("GetFormulaStatistics-error-2:", err)
  7330. tx.Rollback()
  7331. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7332. return
  7333. }
  7334. var data2 [][]interface{}
  7335. for _, f := range feedtemplet {
  7336. var data1 []interface{}
  7337. for _, date := range dateList {
  7338. exist := false
  7339. for _, item := range downloadedplanList {
  7340. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7341. data1 = append(data1, item["total"])
  7342. exist = true
  7343. break
  7344. }
  7345. }
  7346. if !exist {
  7347. data1 = append(data1, 0)
  7348. }
  7349. }
  7350. data2 = append(data2, data1)
  7351. }
  7352. //前端让加的
  7353. feedtemplet = append(feedtemplet, "")
  7354. {
  7355. var data1 []interface{}
  7356. for _, f := range dateList {
  7357. // f = f + "\n"
  7358. fmt.Println(f)
  7359. data1 = append(data1, 0)
  7360. }
  7361. data2 = append(data2, data1)
  7362. }
  7363. resp := make(map[string]interface{}, 0)
  7364. resp["xdata"] = dateList
  7365. resp["data1"] = feedtemplet
  7366. resp["data2"] = data2
  7367. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7368. }
  7369. func GetPlanData(c *gin.Context) {
  7370. appG := app.Gin{C: c}
  7371. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7372. fsion := gofasion.NewFasion(string(dataByte))
  7373. sqlnamestr := fsion.Get("name").ValueStr()
  7374. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7375. offset := fsion.Get("offset").ValueDefaultInt(0)
  7376. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7377. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7378. month := fsion.Get("month").ValueDefaultStr("map")
  7379. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7380. tx := restful.Engine.NewSession()
  7381. err := tx.Begin()
  7382. defer func() {
  7383. switch {
  7384. case err != nil:
  7385. if tx != nil {
  7386. tx.Rollback()
  7387. }
  7388. default:
  7389. if tx != nil {
  7390. err = tx.Commit()
  7391. }
  7392. }
  7393. if tx != nil {
  7394. tx.Close()
  7395. }
  7396. }()
  7397. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7398. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7399. if sql != "" {
  7400. s_params := make([]interface{}, 0)
  7401. if fsion.HasKey("parammaps") {
  7402. parammaps := fsion.Get("parammaps")
  7403. paramslist := strings.Split(p, ",")
  7404. if len(paramslist) > 0 && p != "" {
  7405. for _, value := range paramslist {
  7406. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7407. if tempv, exists := c.Get("jwt_username"); exists {
  7408. s_params = append(s_params, tempv.(string))
  7409. } else {
  7410. s_params = append(s_params, "")
  7411. }
  7412. } else {
  7413. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7414. }
  7415. }
  7416. }
  7417. }
  7418. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7419. if err != nil {
  7420. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7421. } else {
  7422. paramslist1 := strings.Split(p1, ",")
  7423. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7424. s_params1 := make([]interface{}, 0)
  7425. if len(paramslist1) > 0 && p1 != "" {
  7426. for _, v := range paramslist1 {
  7427. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7428. }
  7429. }
  7430. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7431. for _, item := range arr {
  7432. trgaddressList := []string{}
  7433. if _, ok := item["trgaddress"]; ok {
  7434. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7435. for _, str := range trgaddressList1 {
  7436. if str != "" {
  7437. trgaddressList = append(trgaddressList, str)
  7438. }
  7439. }
  7440. }
  7441. item["trgaddressList"] = trgaddressList
  7442. }
  7443. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7444. }
  7445. // var wg sync.WaitGroup
  7446. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7447. // wg.Add(1)
  7448. // go func(value map[string]interface{}) {
  7449. // defer wg.Done()
  7450. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7451. // }(value)
  7452. // }
  7453. // wg.Wait()
  7454. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7455. }
  7456. } else {
  7457. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7458. }
  7459. }
  7460. func PostPlanData(c *gin.Context) {
  7461. appG := app.Gin{C: c}
  7462. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7463. fsion := gofasion.NewFasion(string(dataByte))
  7464. logging.Info("PostRJSBData err: ", string(dataByte))
  7465. s_params := make([]interface{}, 0)
  7466. tx := restful.Engine.NewSession()
  7467. err := tx.Begin()
  7468. defer func() {
  7469. switch {
  7470. case err != nil:
  7471. if tx != nil {
  7472. tx.Rollback()
  7473. }
  7474. default:
  7475. if tx != nil {
  7476. err = tx.Commit()
  7477. }
  7478. }
  7479. if tx != nil {
  7480. tx.Close()
  7481. }
  7482. }()
  7483. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7484. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7485. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7486. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7487. if !fsion.HasKey("parammaps") {
  7488. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7489. return
  7490. }
  7491. parammaps := fsion.Get("parammaps")
  7492. // paramslist := strings.Split(p, ",")
  7493. // if len(paramslist) > 0 && p != "" {
  7494. // for _, value := range paramslist {
  7495. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7496. // }
  7497. // }
  7498. // _, err = tx.SQL(sql, s_params...).Execute()
  7499. // if err != nil {
  7500. // logging.Error("PostRJSBData err: ", err)
  7501. // msg := geterrmsg(err.Error())
  7502. // appG.Response(http.StatusOK, e.ERROR, msg)
  7503. // return
  7504. // }
  7505. s_params = make([]interface{}, 0)
  7506. paramslist := strings.Split(p1, ",")
  7507. if len(paramslist) > 0 && p1 != "" {
  7508. for _, value := range paramslist {
  7509. // if value == "ID" {
  7510. // id := parammaps.Get("ID").ValueStr()
  7511. // pastureid := parammaps.Get("pastureid").ValueStr()
  7512. // 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
  7513. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7514. // if err != nil {
  7515. // logging.Error("PostRJSBData err: ", err)
  7516. // msg := geterrmsg(err.Error())
  7517. // appG.Response(http.StatusOK, e.ERROR, msg)
  7518. // return
  7519. // }
  7520. // for _, item := range datalist {
  7521. // id = item["id"]
  7522. // }
  7523. // s_params = append(s_params, id)
  7524. // } else {
  7525. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7526. // }
  7527. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7528. }
  7529. }
  7530. _, err = tx.SQL(sql1, s_params...).Execute()
  7531. if err != nil {
  7532. logging.Error("PostRJSBData1 err: ", err)
  7533. msg := geterrmsg(err.Error())
  7534. appG.Response(http.StatusOK, e.ERROR, msg)
  7535. return
  7536. }
  7537. s_params = make([]interface{}, 0)
  7538. paramslist = strings.Split(p2, ",")
  7539. if len(paramslist) > 0 && p2 != "" {
  7540. for _, value := range paramslist {
  7541. if value == "ID" {
  7542. id := parammaps.Get("ID").ValueStr()
  7543. pastureid := parammaps.Get("pastureid").ValueStr()
  7544. 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
  7545. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7546. if err != nil {
  7547. logging.Error("PostRJSBData err: ", err)
  7548. msg := geterrmsg(err.Error())
  7549. appG.Response(http.StatusOK, e.ERROR, msg)
  7550. return
  7551. }
  7552. for _, item := range datalist {
  7553. id = item["id"]
  7554. }
  7555. s_params = append(s_params, id)
  7556. } else {
  7557. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7558. }
  7559. }
  7560. }
  7561. _, err = tx.SQL(sql2, s_params...).Execute()
  7562. if err != nil {
  7563. logging.Error("PostRJSBData2 err: ", err)
  7564. msg := geterrmsg(err.Error())
  7565. appG.Response(http.StatusOK, e.ERROR, msg)
  7566. return
  7567. }
  7568. s_params = make([]interface{}, 0)
  7569. paramslist = strings.Split(p3, ",")
  7570. if len(paramslist) > 0 && p3 != "" {
  7571. for _, value := range paramslist {
  7572. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7573. }
  7574. }
  7575. _, err = tx.SQL(sql3, s_params...).Execute()
  7576. if err != nil {
  7577. logging.Error("PostRJSBData3 err: ", err)
  7578. msg := geterrmsg(err.Error())
  7579. appG.Response(http.StatusOK, e.ERROR, msg)
  7580. return
  7581. }
  7582. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7583. }
  7584. func CheckFeedTrgaddress(c *gin.Context) {
  7585. appG := app.Gin{C: c}
  7586. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7587. fsion := gofasion.NewFasion(string(dataByte))
  7588. fclassid := fsion.Get("fclassid").ValueStr()
  7589. feedId := fsion.Get("feedId").ValueStr()
  7590. backup1 := fsion.Get("backup1").ValueStr()
  7591. backup1List := strings.Split(backup1, ",")
  7592. tx := restful.Engine.NewSession()
  7593. defer tx.Close()
  7594. // if backup1 != "" {
  7595. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7596. for _, feed := range feedList {
  7597. if feed["backup1"] == "" {
  7598. continue
  7599. }
  7600. feedbackupList := strings.Split(feed["backup1"], ",")
  7601. for _, feedbackup := range feedbackupList {
  7602. for _, backup := range backup1List {
  7603. if feedbackup == backup {
  7604. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7605. return
  7606. }
  7607. }
  7608. }
  7609. }
  7610. // }
  7611. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7612. }
  7613. func ThiGetDataByName(c *gin.Context) {
  7614. appG := app.Gin{C: c}
  7615. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7616. fsion := gofasion.NewFasion(string(dataByte))
  7617. sqlnamestr := fsion.Get("name").ValueStr()
  7618. offset := fsion.Get("offset").ValueDefaultInt(0)
  7619. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7620. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7621. tx := restful.Engine.NewSession()
  7622. err := tx.Begin()
  7623. defer func() {
  7624. switch {
  7625. case err != nil:
  7626. logging.Error("tx.Begin 事务启动失败__error:", err)
  7627. if tx != nil {
  7628. tx.Rollback()
  7629. }
  7630. default:
  7631. if tx != nil {
  7632. err = tx.Commit()
  7633. }
  7634. }
  7635. if tx != nil {
  7636. tx.Close()
  7637. }
  7638. }()
  7639. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7640. if sql != "" {
  7641. s_params := make([]interface{}, 0)
  7642. if fsion.HasKey("parammaps") {
  7643. parammaps := fsion.Get("parammaps")
  7644. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7645. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7646. }
  7647. paramslist := strings.Split(p, ",")
  7648. if len(paramslist) > 0 && p != "" {
  7649. for _, value := range paramslist {
  7650. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7651. if tempv, exists := c.Get("jwt_username"); exists {
  7652. s_params = append(s_params, tempv.(string))
  7653. } else {
  7654. s_params = append(s_params, "")
  7655. }
  7656. } else {
  7657. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7658. }
  7659. }
  7660. }
  7661. } else if fsion.HasKey("params") {
  7662. params := fsion.Get("params").Array()
  7663. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7664. for _, v_params := range params {
  7665. s_params = append(s_params, v_params.ValueStr())
  7666. }
  7667. }
  7668. if returntype == "xlsx" {
  7669. var xlsxfile *xlsx.File
  7670. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7671. //c.File("c:/dd.xlsx")
  7672. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7673. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7674. c.Header("Content-Transfer-Encoding", "binary")
  7675. _ = xlsxfile.Write(c.Writer)
  7676. } else {
  7677. if sqlnamestr == "getHomepageStr" {
  7678. parammaps := fsion.Get("parammaps")
  7679. pastureid := parammaps.Get("pastureid").ValueStr()
  7680. var montimeList []float64
  7681. var montime float64
  7682. var wg sync.WaitGroup
  7683. now := time.Now()
  7684. for i := 0; i < 30; i++ {
  7685. wg.Add(1)
  7686. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7687. go func(nowstr string) {
  7688. defer wg.Done()
  7689. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7690. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7691. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7692. montimeList = append(montimeList, m)
  7693. }(nowstr)
  7694. }
  7695. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7696. if err != nil {
  7697. logging.Error("GetDataByName err: ", err)
  7698. msg := geterrmsg(err.Error())
  7699. appG.Response(http.StatusOK, e.ERROR, msg)
  7700. }
  7701. wg.Wait()
  7702. for _, m := range montimeList {
  7703. montime += m
  7704. }
  7705. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7706. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7707. return
  7708. }
  7709. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7710. if err != nil {
  7711. logging.Error("GetDataByName err: ", err)
  7712. msg := geterrmsg(err.Error())
  7713. appG.Response(http.StatusOK, e.ERROR, msg)
  7714. } else {
  7715. if sqlnamestr == "getFeedTrgaddressList" {
  7716. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7717. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7718. trgaddressList := []string{}
  7719. for _, str := range trgaddressList1 {
  7720. if str != "" {
  7721. trgaddressList = append(trgaddressList, str)
  7722. }
  7723. }
  7724. item["trgaddressList"] = trgaddressList
  7725. }
  7726. }
  7727. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7728. }
  7729. }
  7730. } else {
  7731. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7732. }
  7733. }
  7734. // func ToggleCcount(c *gin.Context) {
  7735. // appG := app.Gin{C: c}
  7736. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7737. // fsion := gofasion.NewFasion(string(dataByte))
  7738. // // 0 实际 1 软件
  7739. // status := fsion.Get("status").ValueDefaultInt64(0)
  7740. // pastureId := fsion.Get("pastureId").ValueStr()
  7741. // tx := restful.Engine.NewSession()
  7742. // err := tx.Begin()
  7743. // defer func() {
  7744. // switch {
  7745. // case err != nil:
  7746. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7747. // if tx != nil {
  7748. // tx.Rollback()
  7749. // }
  7750. // default:
  7751. // if tx != nil {
  7752. // err = tx.Commit()
  7753. // }
  7754. // }
  7755. // if tx != nil {
  7756. // tx.Close()
  7757. // }
  7758. // }()
  7759. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7760. // if err != nil {
  7761. // logs.Error(err)
  7762. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7763. // return
  7764. // }
  7765. // for _, bar := range barList {
  7766. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7767. // if err != nil {
  7768. // logs.Error(err)
  7769. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7770. // return
  7771. // }
  7772. // if !exist {
  7773. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7774. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7775. // if err != nil {
  7776. // logs.Error(err)
  7777. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7778. // return
  7779. // }
  7780. // }
  7781. // }
  7782. // if status == 0 {
  7783. // tx.Exec(`update feedp set ccount = actualcount `)
  7784. // }else{
  7785. // tx.Exec(`update feedp set ccount = softccount `)
  7786. // }
  7787. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7788. // if err != nil {
  7789. // logs.Error(err)
  7790. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7791. // return
  7792. // }
  7793. // for _, feedpData :=range feedpList{
  7794. // var feedpargs []interface{}
  7795. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7796. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7797. // if _, ok := feedpData["ftname"]; ok {
  7798. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7799. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7800. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7801. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7802. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7803. // } else {
  7804. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7805. // }
  7806. // if _, ok := feedpData["ptsfname"]; ok {
  7807. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7808. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7809. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7810. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7811. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7812. // } else {
  7813. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7814. // }
  7815. // upFeedpSql += " where barname = ? and pastureid = ? "
  7816. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7817. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7818. // if err != nil {
  7819. // logs.Error(err)
  7820. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7821. // return
  7822. // }
  7823. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7824. // if err != nil {
  7825. // logs.Error(err)
  7826. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7827. // return
  7828. // }
  7829. // if !exist1 {
  7830. // _, 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) `,
  7831. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7832. // if err != nil {
  7833. // logs.Error(err)
  7834. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7835. // return
  7836. // }
  7837. // }
  7838. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7839. // if err != nil {
  7840. // logs.Error(err)
  7841. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7842. // return
  7843. // }
  7844. // if !exist2 {
  7845. // _, 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) `,
  7846. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7847. // if err != nil {
  7848. // logs.Error(err)
  7849. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7850. // return
  7851. // }
  7852. // }
  7853. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7854. // if err != nil {
  7855. // logs.Error(err)
  7856. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7857. // return
  7858. // }
  7859. // if !exist3 {
  7860. // _, 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) `,
  7861. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7862. // if err != nil {
  7863. // logs.Error(err)
  7864. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7865. // return
  7866. // }
  7867. // }
  7868. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7869. // if err != nil {
  7870. // logs.Error(err)
  7871. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7872. // return
  7873. // }
  7874. // if !exist4 {
  7875. // _, 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) `,
  7876. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7877. // if err != nil {
  7878. // logs.Error(err)
  7879. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7880. // return
  7881. // }
  7882. // }
  7883. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7884. // if err != nil {
  7885. // logs.Error(err)
  7886. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7887. // return
  7888. // }
  7889. // if !exist5 {
  7890. // _, 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) `,
  7891. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7892. // if err != nil {
  7893. // logs.Error(err)
  7894. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7895. // return
  7896. // }
  7897. // }
  7898. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7899. // if err != nil {
  7900. // logs.Error(err)
  7901. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7902. // return
  7903. // }
  7904. // if !exist6 {
  7905. // _, 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) `,
  7906. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7907. // if err != nil {
  7908. // logs.Error(err)
  7909. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7910. // return
  7911. // }
  7912. // }
  7913. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7914. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7915. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7916. // and pastureid = ? and times = ?`
  7917. // var fpdargs1 []interface{}
  7918. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7919. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7920. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7921. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7922. // if err != nil {
  7923. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7924. // return
  7925. // }
  7926. // var fpdargs2 []interface{}
  7927. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7928. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7929. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7930. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7931. // if err != nil {
  7932. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7933. // return
  7934. // }
  7935. // var fpdargs3 []interface{}
  7936. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7937. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7938. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7939. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7940. // if err != nil {
  7941. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7942. // return
  7943. // }
  7944. // var fpdargs4 []interface{}
  7945. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7946. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7947. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7948. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7949. // if err != nil {
  7950. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7951. // return
  7952. // }
  7953. // var fpdargs5 []interface{}
  7954. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7955. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7956. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7957. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7958. // if err != nil {
  7959. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7960. // return
  7961. // }
  7962. // var fpdargs6 []interface{}
  7963. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7964. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7965. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7966. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7967. // if err != nil {
  7968. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7969. // return
  7970. // }
  7971. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7972. // 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()
  7973. // if err != nil {
  7974. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7975. // return
  7976. // }
  7977. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7978. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7979. // upFpdetailList := make([]*upFpdetail, 0)
  7980. // for _, newfpd := range newList {
  7981. // for _, oldfpd := range oldFpdList {
  7982. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7983. // var oldweight, newweight float64
  7984. // if oldfpd["weight"] != nil {
  7985. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7986. // }
  7987. // if newfpd["weight"] != nil {
  7988. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7989. // }
  7990. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7991. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  7992. // Old: oldweight,
  7993. // New: newweight,
  7994. // Times: newfpd["times"].(int64),
  7995. // Ptid: newfpd["ptid"].(int64),
  7996. // Fweight: fweight,
  7997. // Id: oldfpd["id"].(int64),
  7998. // })
  7999. // break
  8000. // }
  8001. // }
  8002. // }
  8003. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8004. // }
  8005. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8006. // }
  8007. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8008. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8009. if err != nil {
  8010. return err
  8011. }
  8012. for _, item := range feedpList {
  8013. // if item["ftid"].(string) != data["ftid"].(string) {
  8014. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8015. if err != nil {
  8016. return err
  8017. }
  8018. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8019. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8020. if err != nil {
  8021. return err
  8022. }
  8023. // }
  8024. }
  8025. return nil
  8026. }
  8027. func PostPlanDatas(c *gin.Context) {
  8028. appG := app.Gin{C: c}
  8029. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8030. fsions := gofasion.NewFasion(string(dataByte))
  8031. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8032. tx := restful.Engine.NewSession()
  8033. err := tx.Begin()
  8034. defer func() {
  8035. switch {
  8036. case err != nil:
  8037. if tx != nil {
  8038. tx.Rollback()
  8039. }
  8040. default:
  8041. if tx != nil {
  8042. err = tx.Commit()
  8043. }
  8044. }
  8045. if tx != nil {
  8046. tx.Close()
  8047. }
  8048. }()
  8049. pastureId := fsions.Get("pastureid").ValueStr()
  8050. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8051. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8052. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8053. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8054. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8055. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8056. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8057. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8058. for _, parammaps := range fsions.Get("arrList").Array() {
  8059. fmt.Println(parammaps.Json())
  8060. if parammaps.Json() == "null" {
  8061. continue
  8062. }
  8063. // if !fsion.HasKey("arrList") {
  8064. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8065. // return
  8066. // continue
  8067. // }
  8068. // parammaps := fsion.Get("arrList")
  8069. s_params := make([]interface{}, 0)
  8070. // paramslist := strings.Split(p, ",")
  8071. // if len(paramslist) > 0 && p != "" {
  8072. // for _, value := range paramslist {
  8073. // if value == "pastureid" {
  8074. // s_params = append(s_params, pastureId)
  8075. // } else {
  8076. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8077. // }
  8078. // }
  8079. // }
  8080. // _, err = tx.SQL(sql, s_params...).Execute()
  8081. // if err != nil {
  8082. // logging.Error("PostRJSBData err: ", err)
  8083. // msg := geterrmsg(err.Error())
  8084. // appG.Response(http.StatusOK, e.ERROR, msg)
  8085. // return
  8086. // }
  8087. s_params = make([]interface{}, 0)
  8088. paramslist := strings.Split(p1, ",")
  8089. if len(paramslist) > 0 && p1 != "" {
  8090. for _, value := range paramslist {
  8091. // if value == "ID" {
  8092. // id := parammaps.Get("ID").ValueStr()
  8093. // pastureid := parammaps.Get("pastureid").ValueStr()
  8094. // 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
  8095. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8096. // if err != nil {
  8097. // logging.Error("PostRJSBData err: ", err)
  8098. // msg := geterrmsg(err.Error())
  8099. // appG.Response(http.StatusOK, e.ERROR, msg)
  8100. // return
  8101. // }
  8102. // for _, item := range datalist {
  8103. // id = item["id"]
  8104. // }
  8105. // s_params = append(s_params, id)
  8106. // } else {
  8107. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8108. // }
  8109. if value == "pastureid" {
  8110. s_params = append(s_params, pastureId)
  8111. } else {
  8112. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8113. }
  8114. }
  8115. }
  8116. _, err = tx.SQL(sql1, s_params...).Execute()
  8117. if err != nil {
  8118. logging.Error("PostRJSBData1 err: ", err)
  8119. msg := geterrmsg(err.Error())
  8120. appG.Response(http.StatusOK, e.ERROR, msg)
  8121. return
  8122. }
  8123. s_params = make([]interface{}, 0)
  8124. paramslist = strings.Split(p2, ",")
  8125. if len(paramslist) > 0 && p2 != "" {
  8126. for _, value := range paramslist {
  8127. if value == "ID" {
  8128. id := parammaps.Get("ID").ValueStr()
  8129. pastureid := parammaps.Get("pastureid").ValueStr()
  8130. 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
  8131. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8132. if err != nil {
  8133. logging.Error("PostRJSBData err: ", err)
  8134. msg := geterrmsg(err.Error())
  8135. appG.Response(http.StatusOK, e.ERROR, msg)
  8136. return
  8137. }
  8138. for _, item := range datalist {
  8139. id = item["id"]
  8140. }
  8141. s_params = append(s_params, id)
  8142. } else if value == "pastureid" {
  8143. s_params = append(s_params, pastureId)
  8144. } else {
  8145. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8146. }
  8147. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8148. }
  8149. }
  8150. _, err = tx.SQL(sql2, s_params...).Execute()
  8151. if err != nil {
  8152. logging.Error("PostRJSBData2 err: ", err)
  8153. msg := geterrmsg(err.Error())
  8154. appG.Response(http.StatusOK, e.ERROR, msg)
  8155. return
  8156. }
  8157. s_params = make([]interface{}, 0)
  8158. paramslist = strings.Split(p3, ",")
  8159. if len(paramslist) > 0 && p3 != "" {
  8160. for _, value := range paramslist {
  8161. if value == "pastureid" {
  8162. s_params = append(s_params, pastureId)
  8163. } else {
  8164. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8165. }
  8166. }
  8167. }
  8168. _, err = tx.SQL(sql3, s_params...).Execute()
  8169. if err != nil {
  8170. logging.Error("PostRJSBData3 err: ", err)
  8171. msg := geterrmsg(err.Error())
  8172. appG.Response(http.StatusOK, e.ERROR, msg)
  8173. return
  8174. }
  8175. }
  8176. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8177. }
  8178. func FpdBatchEdit(c *gin.Context) {
  8179. appG := app.Gin{C: c}
  8180. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8181. fsions := gofasion.NewFasion(string(dataByte))
  8182. barList := fsions.Get("barList").Array()
  8183. pastureid := fsions.Get("pastureId").ValueStr()
  8184. tx := restful.Engine.NewSession()
  8185. defer tx.Close()
  8186. 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
  8187. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8188. if err != nil {
  8189. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8190. return
  8191. }
  8192. for _, barFsions := range barList {
  8193. dataexcel := make(map[string]interface{}, 0)
  8194. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8195. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8196. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8197. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8198. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8199. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8200. continue
  8201. }
  8202. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8203. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8204. if err != nil {
  8205. logs.Error(err)
  8206. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8207. return
  8208. }
  8209. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8210. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8211. if err != nil {
  8212. logs.Error(err)
  8213. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8214. return
  8215. }
  8216. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8217. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8218. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8219. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8220. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8221. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8222. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8223. if err != nil {
  8224. logs.Error(err)
  8225. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8226. return
  8227. }
  8228. if !ftexist {
  8229. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8230. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8231. if err != nil {
  8232. logs.Error(err)
  8233. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8234. return
  8235. }
  8236. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8237. if err != nil {
  8238. logs.Error(err)
  8239. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8240. return
  8241. }
  8242. }
  8243. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8244. if err != nil {
  8245. logs.Error(err)
  8246. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8247. return
  8248. }
  8249. if !exist {
  8250. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8251. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8252. if err != nil {
  8253. logs.Error(err)
  8254. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8255. return
  8256. }
  8257. }
  8258. var feedpargs []interface{}
  8259. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8260. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8261. if _, ok := dataexcel["ftname"]; ok {
  8262. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8263. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8264. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8265. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8266. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8267. } else {
  8268. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8269. }
  8270. if _, ok := dataexcel["ptsfname"]; ok {
  8271. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8272. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8273. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8274. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8275. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8276. } else {
  8277. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8278. }
  8279. upFeedpSql += " where barname = ? and pastureid = ? "
  8280. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8281. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8282. if err != nil {
  8283. logs.Error(err)
  8284. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8285. return
  8286. }
  8287. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8288. if err != nil {
  8289. logs.Error(err)
  8290. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8291. return
  8292. }
  8293. if !exist1 {
  8294. _, 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) `,
  8295. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8296. if err != nil {
  8297. logs.Error(err)
  8298. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8299. return
  8300. }
  8301. }
  8302. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8303. if err != nil {
  8304. logs.Error(err)
  8305. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8306. return
  8307. }
  8308. if !exist2 {
  8309. _, 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) `,
  8310. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8311. if err != nil {
  8312. logs.Error(err)
  8313. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8314. return
  8315. }
  8316. }
  8317. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8318. if err != nil {
  8319. logs.Error(err)
  8320. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8321. return
  8322. }
  8323. if !exist3 {
  8324. _, 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) `,
  8325. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8326. if err != nil {
  8327. logs.Error(err)
  8328. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8329. return
  8330. }
  8331. }
  8332. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8333. if err != nil {
  8334. logs.Error(err)
  8335. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8336. return
  8337. }
  8338. if !exist4 {
  8339. _, 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) `,
  8340. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8341. if err != nil {
  8342. logs.Error(err)
  8343. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8344. return
  8345. }
  8346. }
  8347. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8348. if err != nil {
  8349. logs.Error(err)
  8350. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8351. return
  8352. }
  8353. if !exist5 {
  8354. _, 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) `,
  8355. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8356. if err != nil {
  8357. logs.Error(err)
  8358. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8359. return
  8360. }
  8361. }
  8362. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8363. if err != nil {
  8364. logs.Error(err)
  8365. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8366. return
  8367. }
  8368. if !exist6 {
  8369. _, 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) `,
  8370. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8371. if err != nil {
  8372. logs.Error(err)
  8373. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8374. return
  8375. }
  8376. }
  8377. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8378. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8379. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8380. and pastureid = ? and times = ?`
  8381. var fpdargs1 []interface{}
  8382. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8383. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8384. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8385. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8386. if err != nil {
  8387. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8388. return
  8389. }
  8390. var fpdargs2 []interface{}
  8391. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8392. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8393. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8394. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8395. if err != nil {
  8396. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8397. return
  8398. }
  8399. var fpdargs3 []interface{}
  8400. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8401. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8402. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8403. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8404. if err != nil {
  8405. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8406. return
  8407. }
  8408. var fpdargs4 []interface{}
  8409. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8410. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8411. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8412. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8413. if err != nil {
  8414. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8415. return
  8416. }
  8417. var fpdargs5 []interface{}
  8418. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8419. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8420. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8421. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8422. if err != nil {
  8423. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8424. return
  8425. }
  8426. var fpdargs6 []interface{}
  8427. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8428. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8429. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8430. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8431. if err != nil {
  8432. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8433. return
  8434. }
  8435. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8436. 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()
  8437. if err != nil {
  8438. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8439. return
  8440. }
  8441. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8442. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8443. upFpdetailList := make([]*upFpdetail, 0)
  8444. for _, newfpd := range newList {
  8445. for _, oldfpd := range oldFpdList {
  8446. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8447. var oldweight, newweight float64
  8448. if oldfpd["weight"] != nil {
  8449. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8450. }
  8451. if newfpd["weight"] != nil {
  8452. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8453. }
  8454. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8455. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8456. Old: oldweight,
  8457. New: newweight,
  8458. Times: newfpd["times"].(int64),
  8459. Ptid: newfpd["ptid"].(int64),
  8460. Fweight: fweight,
  8461. Id: oldfpd["id"].(int64),
  8462. })
  8463. break
  8464. }
  8465. }
  8466. }
  8467. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8468. }
  8469. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8470. }
  8471. func UdBarSync(c *gin.Context) {
  8472. appG := app.Gin{C: c}
  8473. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8474. fsions := gofasion.NewFasion(string(dataByte))
  8475. pastureid := fsions.Get("pastureId").ValueStr()
  8476. tx := restful.Engine.NewSession()
  8477. defer tx.Close()
  8478. pastureinfo := new(udPastureInfo)
  8479. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8480. if err != nil {
  8481. logs.Error(err)
  8482. return
  8483. }
  8484. gm.UdBarSync(pastureid, pastureinfo.Werks)
  8485. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8486. }
  8487. func UdFeedSync(c *gin.Context) {
  8488. appG := app.Gin{C: c}
  8489. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8490. fsions := gofasion.NewFasion(string(dataByte))
  8491. pastureid := fsions.Get("pastureId").ValueStr()
  8492. tx := restful.Engine.NewSession()
  8493. defer tx.Close()
  8494. pastureinfo := new(udPastureInfo)
  8495. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8496. if err != nil {
  8497. logs.Error(err)
  8498. return
  8499. }
  8500. gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8501. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8502. }
  8503. func UdFeedtempletPush(c *gin.Context) {
  8504. appG := app.Gin{C: c}
  8505. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8506. fsions := gofasion.NewFasion(string(dataByte))
  8507. pastureid := fsions.Get("pastureId").ValueStr()
  8508. date := fsions.Get("date").ValueStr()
  8509. tx := restful.Engine.NewSession()
  8510. defer tx.Close()
  8511. pastureinfo := new(udPastureInfo)
  8512. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8513. if err != nil {
  8514. logs.Error(err)
  8515. return
  8516. }
  8517. gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8518. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8519. }
  8520. func UdUtirPush(c *gin.Context) {
  8521. appG := app.Gin{C: c}
  8522. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8523. fsions := gofasion.NewFasion(string(dataByte))
  8524. pastureid := fsions.Get("pastureId").ValueStr()
  8525. date := fsions.Get("date").ValueStr()
  8526. tx := restful.Engine.NewSession()
  8527. defer tx.Close()
  8528. pastureinfo := new(udPastureInfo)
  8529. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8530. if err != nil {
  8531. logs.Error(err)
  8532. return
  8533. }
  8534. gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8535. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8536. }
  8537. func UdBarFeedRemainPush(c *gin.Context) {
  8538. appG := app.Gin{C: c}
  8539. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8540. fsions := gofasion.NewFasion(string(dataByte))
  8541. pastureid := fsions.Get("pastureId").ValueStr()
  8542. date := fsions.Get("date").ValueStr()
  8543. tx := restful.Engine.NewSession()
  8544. defer tx.Close()
  8545. pastureinfo := new(udPastureInfo)
  8546. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8547. if err != nil {
  8548. logs.Error(err)
  8549. return
  8550. }
  8551. gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8552. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8553. }
  8554. func UdMaterialIssuePush(c *gin.Context) {
  8555. appG := app.Gin{C: c}
  8556. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8557. fsions := gofasion.NewFasion(string(dataByte))
  8558. pastureid := fsions.Get("pastureId").ValueStr()
  8559. date := fsions.Get("date").ValueStr()
  8560. tx := restful.Engine.NewSession()
  8561. defer tx.Close()
  8562. pastureinfo := new(udPastureInfo)
  8563. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8564. if err != nil {
  8565. logs.Error(err)
  8566. return
  8567. }
  8568. gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8569. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8570. }
  8571. func DelFeedTemplet(c *gin.Context) {
  8572. appG := app.Gin{C: c}
  8573. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8574. fsions := gofasion.NewFasion(string(dataByte))
  8575. ftId := fsions.Get("ftId").ValueStr()
  8576. // userId := fsions.Get("userId").ValueStr()
  8577. tx := restful.Engine.NewSession()
  8578. defer tx.Close()
  8579. _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
  8580. if err != nil {
  8581. logs.Error(err)
  8582. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8583. return
  8584. }
  8585. /*
  8586. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8587. if err != nil {
  8588. logs.Error(err)
  8589. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8590. return
  8591. }
  8592. */
  8593. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8594. if err != nil {
  8595. logs.Error(err)
  8596. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8597. return
  8598. }
  8599. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8600. if err != nil {
  8601. logs.Error(err)
  8602. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8603. return
  8604. }
  8605. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8606. if count > 0 {
  8607. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8608. if err != nil {
  8609. logs.Error(err)
  8610. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8611. return
  8612. }
  8613. }
  8614. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8615. if err != nil {
  8616. logs.Error(err)
  8617. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8618. return
  8619. }
  8620. // var barIdStr []string
  8621. // for _, bar := range barIdList {
  8622. // barIdStr = append(barIdStr, bar["barid"])
  8623. // }
  8624. // if len(barIdStr) > 0 {
  8625. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8626. // if err != nil {
  8627. // logs.Error(err)
  8628. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8629. // return
  8630. // }
  8631. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8632. // if err != nil {
  8633. // logs.Error(err)
  8634. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8635. // return
  8636. // }
  8637. // now := time.Now()
  8638. // for _, newFpd := range newFpdDataList {
  8639. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8640. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8641. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8642. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8643. // if err != nil {
  8644. // logs.Error(err)
  8645. // appG.Response(http.StatusOK, e.ERROR, false)
  8646. // return
  8647. // }
  8648. // }
  8649. // for _, newFeedp := range newFeedpList {
  8650. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8651. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8652. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8653. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8654. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8655. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8656. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8657. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8658. // if err != nil {
  8659. // logs.Error(err)
  8660. // appG.Response(http.StatusOK, e.ERROR, false)
  8661. // return
  8662. // }
  8663. // }
  8664. // }
  8665. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8666. }
  8667. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8668. data := fasion["parammaps"].(map[string]interface{})
  8669. plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(0,1,2) ").Count()
  8670. fmt.Println(err)
  8671. plancount1, err := tx.SQL(`SELECT
  8672. count( 1 )
  8673. FROM
  8674. (
  8675. SELECT
  8676. d.id
  8677. FROM
  8678. downloadedplan d
  8679. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  8680. JOIN downloadplandtl1_exec d1e ON d1e.pid = d.id
  8681. JOIN downloadplandtl2 d2 ON d2.pid = d.id
  8682. WHERE
  8683. d.mydate = ?
  8684. AND d.havebutton = 0
  8685. AND lpplantype IN ( 0, 1, 2 )
  8686. AND ( SELECT count( 1 ) FROM downloadplandtl2 dd2 WHERE dd2.pid = d.id and dd2.fname = d2.fname) =
  8687. ( 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 )
  8688. GROUP BY
  8689. d.id
  8690. ) d
  8691. `,
  8692. data["startTime"]).Count()
  8693. fmt.Println(err)
  8694. if plancount != plancount1 && number < 10 {
  8695. number++
  8696. ExecDataParam(fasion, CommonParamMap, ParamMap, nil, nil, tx)
  8697. checkPlan(tx, fasion, CommonParamMap, ParamMap, number)
  8698. }
  8699. }
  8700. func EditPlanSort(c *gin.Context) {
  8701. appG := app.Gin{C: c}
  8702. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8703. fsions := gofasion.NewFasion(string(dataByte))
  8704. planIdStr := fsions.Get("planId").ValueStr()
  8705. mydate := fsions.Get("mydate").ValueStr()
  8706. sort := fsions.Get("sort").ValueStr()
  8707. tx := restful.Engine.NewSession()
  8708. defer tx.Close()
  8709. tx.Begin()
  8710. type downloadedplan struct {
  8711. Id int64 `xorm:"id"`
  8712. Sort int `xorm:"sort"`
  8713. Pid int64 `xorm:"pid"`
  8714. }
  8715. planInfo := new(downloadedplan)
  8716. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  8717. if err != nil {
  8718. logs.Error(err)
  8719. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8720. tx.Rollback()
  8721. return
  8722. }
  8723. sort1, _ := strconv.Atoi(sort)
  8724. if sort1 == planInfo.Sort {
  8725. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  8726. tx.Rollback()
  8727. return
  8728. }
  8729. 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()
  8730. if err != nil {
  8731. logs.Error(err)
  8732. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8733. tx.Rollback()
  8734. return
  8735. }
  8736. if count1 == 0 {
  8737. tx.Rollback()
  8738. logs.Error(err)
  8739. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  8740. return
  8741. }
  8742. 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()
  8743. if err != nil {
  8744. logs.Error(err)
  8745. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8746. tx.Rollback()
  8747. return
  8748. }
  8749. if count > 0 {
  8750. tx.Rollback()
  8751. logs.Error(err)
  8752. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  8753. return
  8754. }
  8755. if planInfo.Sort > sort1 {
  8756. 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()
  8757. if err != nil {
  8758. logs.Error(err)
  8759. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8760. tx.Rollback()
  8761. return
  8762. }
  8763. var minSort, pidCount int
  8764. for _, sort := range minSortList {
  8765. minSort, _ = strconv.Atoi(sort["sort"])
  8766. }
  8767. planList := make([]*downloadedplan, 0)
  8768. 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)
  8769. if err != nil {
  8770. logs.Error(err)
  8771. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8772. tx.Rollback()
  8773. return
  8774. }
  8775. planPid := planInfo.Pid
  8776. planList1 := make([]*downloadedplan, 0)
  8777. planList2 := make([]*downloadedplan, 0)
  8778. for _, plan := range planList {
  8779. if plan.Pid == planPid {
  8780. pidCount++
  8781. planList1 = append(planList1, plan)
  8782. } else {
  8783. planList2 = append(planList2, plan)
  8784. }
  8785. }
  8786. planList1 = append(planList1, planList2...)
  8787. for i, plan := range planList1 {
  8788. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  8789. if err != nil {
  8790. logs.Error(err)
  8791. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8792. tx.Rollback()
  8793. return
  8794. }
  8795. }
  8796. } else {
  8797. 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()
  8798. if err != nil {
  8799. logs.Error(err)
  8800. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8801. tx.Rollback()
  8802. return
  8803. }
  8804. var maxSort int
  8805. for _, sort := range maxSortList {
  8806. maxSort, _ = strconv.Atoi(sort["sort"])
  8807. }
  8808. planList := make([]*downloadedplan, 0)
  8809. 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)
  8810. if err != nil {
  8811. logs.Error(err)
  8812. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  8813. tx.Rollback()
  8814. return
  8815. }
  8816. planPid := planInfo.Pid
  8817. planList1 := make([]*downloadedplan, 0)
  8818. planList2 := make([]*downloadedplan, 0)
  8819. for _, plan := range planList {
  8820. if plan.Pid == planPid {
  8821. // pidCount++
  8822. planList1 = append(planList1, plan)
  8823. } else {
  8824. planList2 = append(planList2, plan)
  8825. }
  8826. }
  8827. planList2 = append(planList2, planList1...)
  8828. for i, plan := range planList2 {
  8829. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  8830. if err != nil {
  8831. logs.Error(err)
  8832. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8833. tx.Rollback()
  8834. return
  8835. }
  8836. }
  8837. }
  8838. err = tx.Commit()
  8839. if err != nil {
  8840. logs.Error(err)
  8841. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  8842. tx.Rollback()
  8843. return
  8844. }
  8845. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8846. }
  8847. func EditDownloadedplanArtificial(c *gin.Context) {
  8848. appG := app.Gin{C: c}
  8849. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8850. fsions := gofasion.NewFasion(string(dataByte))
  8851. planIdStr := fsions.Get("planId").ValueStr()
  8852. tx := restful.Engine.NewSession()
  8853. defer tx.Close()
  8854. tx.Begin()
  8855. planIdList := strings.Split(planIdStr, ",")
  8856. for _, planId := range planIdList {
  8857. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? and havebutton != 1`, planId)
  8858. if err != nil {
  8859. logs.Error(err)
  8860. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8861. tx.Rollback()
  8862. return
  8863. }
  8864. }
  8865. err := tx.Commit()
  8866. if err != nil {
  8867. logs.Error(err)
  8868. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  8869. tx.Rollback()
  8870. return
  8871. }
  8872. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8873. }
  8874. type PlanRFID struct {
  8875. RFID string `json:"RFID"`
  8876. Lweight string `json:"lweight"`
  8877. Gear string `json:"gear"`
  8878. Speed string `json:"speed"`
  8879. }
  8880. func GetPlanRFID(c *gin.Context) {
  8881. appG := app.Gin{C: c}
  8882. RFIDStr := c.Query("RFID")
  8883. planRFIDList := make([]*PlanRFID, 0)
  8884. planRFIDList = append(planRFIDList, &PlanRFID{
  8885. RFID: RFIDStr,
  8886. Lweight: "1411.1",
  8887. Gear: "1",
  8888. Speed: "10",
  8889. })
  8890. planRFIDList = append(planRFIDList, &PlanRFID{
  8891. RFID: RFIDStr,
  8892. Lweight: "1322.1",
  8893. Gear: "1",
  8894. Speed: "10",
  8895. })
  8896. planRFIDList = append(planRFIDList, &PlanRFID{
  8897. RFID: RFIDStr,
  8898. Lweight: "1904.1",
  8899. Gear: "1",
  8900. Speed: "10",
  8901. })
  8902. planRFIDList = append(planRFIDList, &PlanRFID{
  8903. RFID: RFIDStr,
  8904. Lweight: "1870.1",
  8905. Gear: "1",
  8906. Speed: "10",
  8907. })
  8908. planRFIDList = append(planRFIDList, &PlanRFID{
  8909. RFID: RFIDStr,
  8910. Lweight: "2041.1",
  8911. Gear: "1",
  8912. Speed: "10",
  8913. })
  8914. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  8915. }
  8916. type tmrEquipmentMuster struct {
  8917. A string
  8918. N string
  8919. }
  8920. func GetTmrEquipmentMuster(c *gin.Context) {
  8921. appG := app.Gin{C: c}
  8922. id := c.Query("id")
  8923. tx := restful.Engine.NewSession()
  8924. defer tx.Close()
  8925. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  8926. if err != nil {
  8927. logs.Error(err)
  8928. appG.Response(http.StatusOK, e.ERROR, err.Error())
  8929. return
  8930. }
  8931. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  8932. for _, data := range dataList {
  8933. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  8934. for _, g := range tmrEquipmentMusterList {
  8935. a, _ := strconv.ParseFloat(g.A, 64)
  8936. n, _ := strconv.ParseFloat(g.N, 64)
  8937. a1, n1 := ddmmtoddd(a, n)
  8938. g.A = fmt.Sprintf("%f", n1)
  8939. g.N = fmt.Sprintf("%f", a1)
  8940. }
  8941. }
  8942. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  8943. }
  8944. func ddmmtoddd(lng, lat float64) (float64, float64) {
  8945. lngDegree := fmt.Sprintf("%f", lng/100)
  8946. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  8947. lngDegreeInt := int(lngDegreefloat * 1000000)
  8948. dd := lngDegreeInt / 100 * 100 / 60
  8949. fmt.Println(dd)
  8950. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  8951. latDegree := fmt.Sprintf("%f", lat/100)
  8952. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  8953. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  8954. latDegreeInt := int(latDegreefloat * 1000000)
  8955. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  8956. a, _ := strconv.ParseFloat(lngStr, 64)
  8957. b, _ := strconv.ParseFloat(latStr, 64)
  8958. return coordtransform.WGS84toGCJ02(b, a)
  8959. }
  8960. func EditDownloadedplanExecWeight(c *gin.Context) {
  8961. appG := app.Gin{C: c}
  8962. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8963. fsions := gofasion.NewFasion(string(dataByte))
  8964. pid := fsions.Get("pid").ValueStr()
  8965. sort := fsions.Get("sort").ValueStr()
  8966. weight := fsions.Get("weight").ValueStr()
  8967. userId := fsions.Get("userId").ValueStr()
  8968. tx := restful.Engine.NewSession()
  8969. defer tx.Close()
  8970. tx.Begin()
  8971. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  8972. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  8973. pid, sort, pid, sort, weight, userId)
  8974. if err != nil {
  8975. logs.Error(err)
  8976. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8977. tx.Rollback()
  8978. return
  8979. }
  8980. _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  8981. if err != nil {
  8982. logs.Error(err)
  8983. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8984. tx.Rollback()
  8985. return
  8986. }
  8987. _, err = tx.Exec(` update downloadplandtl1 set actualweightminus = lweight / (select sum(lweight) from downloadplandtl1 where pid = ? and sort = ? ) * ? where pid = ? and sort = ? `, pid, sort, weight, pid, sort)
  8988. if err != nil {
  8989. logs.Error(err)
  8990. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8991. tx.Rollback()
  8992. return
  8993. }
  8994. err = tx.Commit()
  8995. if err != nil {
  8996. logs.Error(err)
  8997. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  8998. tx.Rollback()
  8999. return
  9000. }
  9001. appG.Response(http.StatusOK, e.SUCCESS, true)
  9002. }
  9003. func EditDownloadplandtl2Weight(c *gin.Context) {
  9004. appG := app.Gin{C: c}
  9005. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9006. fsions := gofasion.NewFasion(string(dataByte))
  9007. pid := fsions.Get("pid").ValueStr()
  9008. sort := fsions.Get("sort").ValueStr()
  9009. weight := fsions.Get("weight").ValueStr()
  9010. userId := fsions.Get("userId").ValueStr()
  9011. tx := restful.Engine.NewSession()
  9012. defer tx.Close()
  9013. tx.Begin()
  9014. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9015. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9016. pid, sort, pid, sort, weight, userId)
  9017. if err != nil {
  9018. logs.Error(err)
  9019. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9020. tx.Rollback()
  9021. return
  9022. }
  9023. _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9024. if err != nil {
  9025. logs.Error(err)
  9026. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9027. tx.Rollback()
  9028. return
  9029. }
  9030. err = tx.Commit()
  9031. if err != nil {
  9032. logs.Error(err)
  9033. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9034. tx.Rollback()
  9035. return
  9036. }
  9037. appG.Response(http.StatusOK, e.SUCCESS, true)
  9038. }
  9039. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9040. params := fasion.Get("parammaps")
  9041. surplus := params.Get("surplus").ValueStr()
  9042. surplusId := params.Get("surplusId").ValueStr()
  9043. tx := restful.Engine.NewSession()
  9044. defer tx.Close()
  9045. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9046. if surplusId != "0" {
  9047. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9048. if err != nil {
  9049. log.Println("PostDataByName-error-1: ", err)
  9050. return errors.New("配方修改失败!")
  9051. }
  9052. type ftdetail struct {
  9053. Id string
  9054. Fname string
  9055. Sort int64
  9056. }
  9057. ftList := make([]*ftdetail, 0)
  9058. for _, data := range dataList {
  9059. ft := new(ftdetail)
  9060. ft.Fname = data["fname"]
  9061. ft.Id = data["id"]
  9062. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9063. if err != nil {
  9064. log.Println("PostDataByName-error-2: ", err)
  9065. return err
  9066. }
  9067. ft.Sort = sort
  9068. ftList = append(ftList, ft)
  9069. }
  9070. if surplus == "日粮" {
  9071. for _, ft := range ftList {
  9072. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9073. }
  9074. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9075. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9076. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9077. fmt.Println(err)
  9078. } else {
  9079. var sort int64
  9080. for _, ft := range ftList {
  9081. if ft.Fname == surplus {
  9082. sort = ft.Sort
  9083. break
  9084. }
  9085. }
  9086. if sort == 0 {
  9087. for _, ft := range ftList {
  9088. ft.Sort = ft.Sort + 1
  9089. }
  9090. } else {
  9091. for _, ft := range ftList {
  9092. if ft.Sort >= sort {
  9093. ft.Sort = ft.Sort + 1
  9094. }
  9095. }
  9096. }
  9097. for _, ft := range ftList {
  9098. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9099. }
  9100. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9101. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9102. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9103. if err != nil {
  9104. log.Println("PostDataByName-error-1: ", err)
  9105. fmt.Println(err)
  9106. return errors.New("配方修改失败!")
  9107. }
  9108. }
  9109. }
  9110. return nil
  9111. }
  9112. func FeedSurplus(fasion *gofasion.Fasion) {
  9113. tx := restful.Engine.NewSession()
  9114. defer tx.Close()
  9115. params := fasion.Get("parammaps")
  9116. feedId := params.Get("id").ValueStr()
  9117. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9118. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9119. }
  9120. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9121. // params := fasion.Get("parammaps")
  9122. // surplus := params.Get("surplus").ValueStr()
  9123. // surplusId := params.Get("surplusId").ValueStr()
  9124. tx := restful.Engine.NewSession()
  9125. defer tx.Close()
  9126. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9127. if surplusId != "0" {
  9128. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9129. if err != nil {
  9130. log.Println("PostDataByName-error-1: ", err)
  9131. return errors.New("配方修改失败!")
  9132. }
  9133. type ftdetail struct {
  9134. Id string
  9135. Fname string
  9136. Sort int64
  9137. }
  9138. ftList := make([]*ftdetail, 0)
  9139. for _, data := range dataList {
  9140. ft := new(ftdetail)
  9141. ft.Fname = data["fname"]
  9142. ft.Id = data["id"]
  9143. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9144. if err != nil {
  9145. log.Println("PostDataByName-error-2: ", err)
  9146. return err
  9147. }
  9148. ft.Sort = sort
  9149. ftList = append(ftList, ft)
  9150. }
  9151. if surplus == "日粮" {
  9152. for _, ft := range ftList {
  9153. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9154. }
  9155. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9156. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9157. pastureId, id, surplusId, surplusId, surplusId)
  9158. fmt.Println(err)
  9159. } else {
  9160. var sort int64
  9161. for _, ft := range ftList {
  9162. if ft.Fname == surplus {
  9163. sort = ft.Sort
  9164. break
  9165. }
  9166. }
  9167. if sort == 0 {
  9168. for _, ft := range ftList {
  9169. ft.Sort = ft.Sort + 1
  9170. }
  9171. } else {
  9172. for _, ft := range ftList {
  9173. if ft.Sort >= sort {
  9174. ft.Sort = ft.Sort + 1
  9175. }
  9176. }
  9177. }
  9178. for _, ft := range ftList {
  9179. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9180. }
  9181. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9182. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9183. id, surplusId, surplusId, sort, surplusId, pastureId)
  9184. if err != nil {
  9185. log.Println("PostDataByName-error-1: ", err)
  9186. fmt.Println(err)
  9187. return errors.New("配方修改失败!")
  9188. }
  9189. }
  9190. }
  9191. return nil
  9192. }
  9193. func GetLanguageStatus() string {
  9194. tx := restful.Engine.NewSession()
  9195. defer tx.Close()
  9196. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9197. if err != nil {
  9198. log.Println(err)
  9199. return "0"
  9200. }
  9201. return dataList[0]["inforvalue"]
  9202. }
  9203. func EditLanguage(c *gin.Context) {
  9204. appG := app.Gin{C: c}
  9205. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9206. fsions := gofasion.NewFasion(string(dataByte))
  9207. language := fsions.Get("language").ValueStr()
  9208. tx := restful.Engine.NewSession()
  9209. defer tx.Close()
  9210. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9211. if err != nil {
  9212. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9213. return
  9214. }
  9215. if language == "0" {
  9216. _, err := tx.Exec(`delete from dictlist `)
  9217. if err != nil {
  9218. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9219. return
  9220. }
  9221. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9222. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9223. if err != nil {
  9224. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9225. return
  9226. }
  9227. } else {
  9228. _, err := tx.Exec(`delete from dictlist `)
  9229. if err != nil {
  9230. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9231. return
  9232. }
  9233. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9234. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9235. if err != nil {
  9236. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9237. return
  9238. }
  9239. }
  9240. appG.Response(http.StatusOK, e.SUCCESS, true)
  9241. }
  9242. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9243. tx := restful.Engine.NewSession()
  9244. defer tx.Close()
  9245. oldFpdList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,fpd.id,fpd.barname,ifnull(fpd.weight,0)weight ,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9246. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9247. if err != nil {
  9248. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9249. return
  9250. }
  9251. for _, dataexcel := range barList {
  9252. // dataexcel := make(map[string]interface{}, 0)
  9253. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9254. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9255. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9256. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9257. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9258. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9259. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9260. // if err != nil {
  9261. // logs.Error(err)
  9262. // return
  9263. // }
  9264. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9265. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9266. // if err != nil {
  9267. // logs.Error(err)
  9268. // return
  9269. // }
  9270. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9271. continue
  9272. }
  9273. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9274. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9275. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9276. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9277. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9278. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9279. // /*
  9280. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  9281. if err != nil {
  9282. logs.Error(err)
  9283. return
  9284. }
  9285. if !ftexist {
  9286. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  9287. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9288. if err != nil {
  9289. logs.Error(err)
  9290. return
  9291. }
  9292. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9293. if err != nil {
  9294. logs.Error(err)
  9295. return
  9296. }
  9297. }
  9298. // */
  9299. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9300. if err != nil {
  9301. logs.Error(err)
  9302. return
  9303. }
  9304. if !exist {
  9305. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9306. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9307. if err != nil {
  9308. logs.Error(err)
  9309. return
  9310. }
  9311. }
  9312. var feedpargs []interface{}
  9313. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9314. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9315. if _, ok := dataexcel["ftname"]; ok {
  9316. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9317. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9318. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9319. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9320. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9321. } else {
  9322. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9323. }
  9324. if _, ok := dataexcel["ptsfname"]; ok {
  9325. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9326. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9327. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9328. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9329. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9330. } else {
  9331. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9332. }
  9333. upFeedpSql += " where barname = ? and pastureid = ? "
  9334. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9335. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9336. if err != nil {
  9337. logs.Error(err)
  9338. return
  9339. }
  9340. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9341. if err != nil {
  9342. logs.Error(err)
  9343. return
  9344. }
  9345. if !exist1 {
  9346. _, 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) `,
  9347. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9348. if err != nil {
  9349. logs.Error(err)
  9350. return
  9351. }
  9352. }
  9353. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9354. if err != nil {
  9355. logs.Error(err)
  9356. return
  9357. }
  9358. if !exist2 {
  9359. _, 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) `,
  9360. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9361. if err != nil {
  9362. logs.Error(err)
  9363. return
  9364. }
  9365. }
  9366. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9367. if err != nil {
  9368. logs.Error(err)
  9369. return
  9370. }
  9371. if !exist3 {
  9372. _, 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) `,
  9373. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9374. if err != nil {
  9375. logs.Error(err)
  9376. return
  9377. }
  9378. }
  9379. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9380. if err != nil {
  9381. logs.Error(err)
  9382. return
  9383. }
  9384. if !exist4 {
  9385. _, 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) `,
  9386. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9387. if err != nil {
  9388. logs.Error(err)
  9389. return
  9390. }
  9391. }
  9392. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9393. if err != nil {
  9394. logs.Error(err)
  9395. return
  9396. }
  9397. if !exist5 {
  9398. _, 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) `,
  9399. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9400. if err != nil {
  9401. logs.Error(err)
  9402. return
  9403. }
  9404. }
  9405. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9406. if err != nil {
  9407. logs.Error(err)
  9408. return
  9409. }
  9410. if !exist6 {
  9411. _, 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) `,
  9412. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9413. if err != nil {
  9414. logs.Error(err)
  9415. return
  9416. }
  9417. }
  9418. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9419. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9420. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9421. and pastureid = ? and times = ?`
  9422. var fpdargs1 []interface{}
  9423. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9424. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9425. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9426. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9427. if err != nil {
  9428. fmt.Println(err)
  9429. return
  9430. }
  9431. var fpdargs2 []interface{}
  9432. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9433. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9434. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9435. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9436. if err != nil {
  9437. fmt.Println(err)
  9438. return
  9439. }
  9440. var fpdargs3 []interface{}
  9441. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9442. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9443. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9444. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9445. if err != nil {
  9446. fmt.Println(err)
  9447. return
  9448. }
  9449. var fpdargs4 []interface{}
  9450. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9451. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9452. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9453. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9454. if err != nil {
  9455. fmt.Println(err)
  9456. return
  9457. }
  9458. var fpdargs5 []interface{}
  9459. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9460. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9461. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9462. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9463. if err != nil {
  9464. fmt.Println(err)
  9465. return
  9466. }
  9467. var fpdargs6 []interface{}
  9468. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  9469. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9470. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  9471. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  9472. if err != nil {
  9473. fmt.Println(err)
  9474. return
  9475. }
  9476. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  9477. newList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,id,ptid,ifnull(weight,0)weight,times from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Query().List()
  9478. if err != nil {
  9479. return
  9480. }
  9481. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9482. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9483. upFpdetailList := make([]*upFpdetail, 0)
  9484. for _, newfpd := range newList {
  9485. for _, oldfpd := range oldFpdList {
  9486. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  9487. var oldweight, newweight float64
  9488. if oldfpd["weight"] != nil {
  9489. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  9490. }
  9491. if newfpd["weight"] != nil {
  9492. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  9493. }
  9494. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  9495. upFpdetailList = append(upFpdetailList, &upFpdetail{
  9496. Old: oldweight,
  9497. New: newweight,
  9498. Times: newfpd["times"].(int64),
  9499. Ptid: newfpd["ptid"].(int64),
  9500. Fweight: fweight,
  9501. Id: oldfpd["id"].(int64),
  9502. })
  9503. break
  9504. }
  9505. }
  9506. }
  9507. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  9508. }
  9509. }
  9510. func AddXxwFtdetail(c *gin.Context) {
  9511. appG := app.Gin{C: c}
  9512. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  9513. c.Bind(&xxwFtdetailList)
  9514. tx := restful.Engine.NewSession()
  9515. defer tx.Close()
  9516. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  9517. if err != nil {
  9518. logs.Error(err)
  9519. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9520. }
  9521. _, err = tx.Insert(xxwFtdetailList)
  9522. if err != nil {
  9523. logs.Error(err)
  9524. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9525. }
  9526. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  9527. appG.Response(http.StatusOK, e.SUCCESS, true)
  9528. }
  9529. func AddXxwFeedtemplet(c *gin.Context) {
  9530. appG := app.Gin{C: c}
  9531. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  9532. c.Bind(&xxwFeedtempletList)
  9533. tx := restful.Engine.NewSession()
  9534. defer tx.Close()
  9535. pastureinfo := new(udPastureInfo)
  9536. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  9537. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  9538. if err != nil {
  9539. logs.Error(err)
  9540. return
  9541. }
  9542. for _, ft := range xxwFeedtempletList {
  9543. ids, err := setting.SnowIds.NextId()
  9544. if err != nil {
  9545. ids = time.Now().UnixNano()
  9546. logging.Info("create SnowIds err", err)
  9547. }
  9548. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  9549. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  9550. ft.RecipeobjName, ft.RecipeobjName)
  9551. if err != nil {
  9552. logs.Error(err)
  9553. return
  9554. }
  9555. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  9556. _, err = tx.Exec(` insert into feedtemplet(pastureid,tcode,tname,xxwTempletCode,ccid,ccname,owner,fttype,fttypeid,source,sort,xxwTempletCode)values(?,(concat(DATE_FORMAT(now(),'%Y%m%d'),'640247041')),
  9557. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  9558. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  9559. if err != nil {
  9560. logs.Error(err)
  9561. return
  9562. }
  9563. }
  9564. appG.Response(http.StatusOK, e.SUCCESS, true)
  9565. }
  9566. func ProcessExcel(c *gin.Context) {
  9567. appG := app.Gin{C: c}
  9568. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9569. fasion := gofasion.NewFasion(string(dataByte))
  9570. params := fasion.Get("parammaps")
  9571. pastureid := params.Get("pastureid").ValueStr()
  9572. startTime := params.Get("startTime").ValueStr()
  9573. stopTime := params.Get("stopTime").ValueStr()
  9574. iscompleted := params.Get("iscompleted").ValueStr()
  9575. lpplantype := params.Get("lpplantype").ValueStr()
  9576. error := params.Get("error").ValueStr()
  9577. hlwc1 := params.Get("hlwc1").ValueStr()
  9578. hlwc2 := params.Get("hlwc2").ValueStr()
  9579. slwc1 := params.Get("slwc1").ValueStr()
  9580. slwc2 := params.Get("slwc2").ValueStr()
  9581. hlzq1 := params.Get("hlzq1").ValueStr()
  9582. hlzq2 := params.Get("hlzq2").ValueStr()
  9583. slzq1 := params.Get("slzq1").ValueStr()
  9584. slzq2 := params.Get("slzq2").ValueStr()
  9585. fclassid := params.Get("fclassid").ValueStr()
  9586. minproesstime := params.Get("minproesstime").ValueStr()
  9587. maxproesstime := params.Get("maxproesstime").ValueStr()
  9588. tx := restful.Engine.NewSession()
  9589. defer tx.Close()
  9590. planList, err := tx.SQL(`SELECT
  9591. d.id,d.tmrtname,d.projname,date_format(d.mydate ,'%Y-%m-%d') mydate ,date_format(d.intime ,'%Y-%m-%d') intime,p.pasture_name pastureName
  9592. FROM downloadedplan d
  9593. join pasture p on p.pastureid = d.pastureid
  9594. WHERE d.pastureid= ? and d.intime IS NOT NULL
  9595. AND mydate >= ? AND mydate <= ?
  9596. AND (iscompleted=? or ?='')
  9597. AND (lpplantype = ? or ? = '')
  9598. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  9599. and ABS(d1.lweight- d1.actualweightminus) > d1.feedallowratio and d1.feedallowratio != 0 ) >0,"有误差","无误差") = ? or if((select count(1) from downloadplandtl2 d1 where d1.pid = d.id
  9600. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  9601. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  9602. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  9603. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  9604. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  9605. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  9606. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  9607. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  9608. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  9609. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  9610. join feed f on f.feedcode = d1.feedcode and f.pastureid = d1.pastureid where f.fclassid = ? and d1.pid = d.id) > 0) and (round(TIMESTAMPDIFF(SECOND,
  9611. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  9612. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  9613. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  9614. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9615. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  9616. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  9617. or (?= '' and ? = '' ))
  9618. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  9619. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  9620. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  9621. maxproesstime, minproesstime, maxproesstime).QueryString()
  9622. if err != nil {
  9623. logs.Error(err)
  9624. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9625. return
  9626. }
  9627. planExecList, err := tx.SQL(`SELECT
  9628. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9629. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  9630. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  9631. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  9632. ) proesstime,
  9633. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9634. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  9635. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  9636. sumproesstime, d1.pid,
  9637. d1.sort,
  9638. d1.fname,
  9639. d1.lweight,
  9640. d1.actualweightminus,
  9641. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  9642. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  9643. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  9644. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  9645. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  9646. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  9647. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  9648. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  9649. d1.begintime stoptime,
  9650. d1.lastactualweight,
  9651. d1.actualweight,
  9652. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  9653. case d1.buttontype
  9654. when 1 then '自动'
  9655. when 2 then '手动'
  9656. when 3 then '手动'
  9657. end,
  9658. case d1.buttontype
  9659. when 1 then 'Automatic'
  9660. when 2 then 'Manual'
  9661. when 3 then 'Manual'
  9662. end
  9663. ) buttontype
  9664. FROM
  9665. downloadplandtl1_exec d1
  9666. WHERE d1.date between ? and ?
  9667. ORDER BY sort
  9668. `, startTime, stopTime).QueryString()
  9669. if err != nil {
  9670. logs.Error(err)
  9671. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9672. return
  9673. }
  9674. planExec2, err := tx.SQL(`SELECT
  9675. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  9676. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  9677. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9678. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  9679. ) proesstime,
  9680. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  9681. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  9682. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  9683. d1.sort,
  9684. d1.fname,
  9685. d1.lweight,
  9686. d1.actualweightminus,
  9687. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  9688. ABS(d1.lweight- d1.actualweightminus) diff,
  9689. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,if(abs(d1.actualweightminus - d1.lweight) <=d1.allowratio , 100,if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - d1.allowratio)/d1.actualweightminus , 1-(abs(d1.actualweightminus - d1.lweight) - d1.allowratio)/d1.lweight )* 100) ,if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  9690. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  9691. d1.begintime stoptime,
  9692. d1.lastactualweight,
  9693. d1.actualweight,d1.pid
  9694. FROM
  9695. downloadplandtl2 d1
  9696. WHERE d1.date between ? and ?
  9697. ORDER BY sort`, startTime, stopTime).QueryString()
  9698. if err != nil {
  9699. logs.Error(err)
  9700. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9701. return
  9702. }
  9703. // 创建一个新的 Excel 文件
  9704. f := excelizexuri.NewFile()
  9705. // 创建工作表名称
  9706. sheetName := "Sheet1"
  9707. border := []excelizexuri.Border{
  9708. {Type: "left", Color: "000000", Style: 1},
  9709. {Type: "right", Color: "000000", Style: 1},
  9710. {Type: "top", Color: "000000", Style: 1},
  9711. {Type: "bottom", Color: "000000", Style: 1},
  9712. }
  9713. // 创建新的样式
  9714. style := &excelizexuri.Style{
  9715. // Border: border,
  9716. Alignment: &excelizexuri.Alignment{
  9717. Vertical: "center",
  9718. Horizontal: "center",
  9719. ShrinkToFit: true,
  9720. WrapText: true,
  9721. },
  9722. }
  9723. styleTitle := &excelizexuri.Style{
  9724. // Border: border,
  9725. Font: &excelizexuri.Font{
  9726. Bold: true, // 加粗
  9727. Size: 24, // 字体大小
  9728. // Name: "宋体", // 字体名称
  9729. // WrapText :true,
  9730. Color: "000000", // 字体颜色(黑色)
  9731. },
  9732. Alignment: &excelizexuri.Alignment{
  9733. Vertical: "center", // 垂直居中
  9734. Horizontal: "center", // 水平居中
  9735. ShrinkToFit: true,
  9736. WrapText: true,
  9737. },
  9738. }
  9739. // 创建样式 ID
  9740. styleTitleId, err := f.NewStyle(styleTitle)
  9741. if err != nil {
  9742. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  9743. return
  9744. }
  9745. // 创建样式 ID
  9746. styleID, err := f.NewStyle(style)
  9747. if err != nil {
  9748. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  9749. return
  9750. }
  9751. // 合并单元格并设置内容
  9752. f.MergeCell(sheetName, "A1", "K1")
  9753. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  9754. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  9755. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  9756. planExecMap := make(map[string][]map[string]string, 0)
  9757. for _, planExec := range planExecList {
  9758. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  9759. }
  9760. plan2Map := make(map[string][]map[string]string, 0)
  9761. for _, plan2 := range planExec2 {
  9762. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  9763. }
  9764. num := 2
  9765. var notBorder []int
  9766. for _, plan := range planList {
  9767. fmt.Println(plan)
  9768. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  9769. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  9770. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  9771. for i, header := range headers {
  9772. // 从 A2 开始
  9773. if header == "开始日期" {
  9774. cell := "%" + fmt.Sprintf("c%d", num)
  9775. cell = fmt.Sprintf(cell, 'A'+i+1)
  9776. f.SetCellValue(sheetName, cell, header)
  9777. f.SetCellStyle(sheetName, cell, cell, styleID)
  9778. continue
  9779. }
  9780. cell := "%" + fmt.Sprintf("c%d", num)
  9781. cell = fmt.Sprintf(cell, 'A'+i)
  9782. f.SetCellValue(sheetName, cell, header)
  9783. f.SetCellStyle(sheetName, cell, cell, styleID)
  9784. }
  9785. num += 1
  9786. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  9787. cell := "%" + fmt.Sprintf("c%d", num)
  9788. cell = fmt.Sprintf(cell, 'A'+0)
  9789. f.SetCellValue(sheetName, cell, plan["pastureName"])
  9790. f.SetCellStyle(sheetName, cell, cell, styleID)
  9791. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  9792. cell = "%" + fmt.Sprintf("c%d", num)
  9793. cell = fmt.Sprintf(cell, 'A'+1)
  9794. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  9795. f.SetCellStyle(sheetName, cell, cell, styleID)
  9796. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  9797. cell = "%" + fmt.Sprintf("c%d", num)
  9798. cell = fmt.Sprintf(cell, 'A'+2)
  9799. f.SetCellValue(sheetName, cell, plan["projname"])
  9800. f.SetCellStyle(sheetName, cell, cell, styleID)
  9801. cell = "%" + fmt.Sprintf("c%d", num)
  9802. cell = fmt.Sprintf(cell, 'A'+3)
  9803. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  9804. f.SetCellValue(sheetName, cell, plan["mydate"])
  9805. f.SetCellStyle(sheetName, cell, cell, styleID)
  9806. cell = "%" + fmt.Sprintf("c%d", num)
  9807. cell = fmt.Sprintf(cell, 'A'+6)
  9808. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  9809. f.SetCellValue(sheetName, cell, plan["intime"])
  9810. f.SetCellStyle(sheetName, cell, cell, styleID)
  9811. num += 1
  9812. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  9813. for i, header := range headers1 {
  9814. cell = "%" + fmt.Sprintf("c%d", num)
  9815. cell = fmt.Sprintf(cell, 'C'+i)
  9816. f.SetCellValue(sheetName, cell, header)
  9817. f.SetCellStyle(sheetName, cell, cell, styleID)
  9818. // maxWidth := len(header)
  9819. // colName := string('C' + i)
  9820. // f.SetColWidth(sheetName, colName, colName, 20)
  9821. f.SetColWidth(sheetName, header, header, 40)
  9822. }
  9823. num += 1
  9824. for _, planExec := range planExecMap[plan["id"]] {
  9825. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  9826. sort, _ := strconv.Atoi(planExec["sort"])
  9827. f.SetCellValue(sheetName, cell, sort)
  9828. f.SetCellStyle(sheetName, cell, cell, styleID)
  9829. cell = fmt.Sprintf("D%d", num)
  9830. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  9831. f.SetCellValue(sheetName, cell, lweight)
  9832. f.SetCellStyle(sheetName, cell, cell, styleID)
  9833. cell = fmt.Sprintf("E%d", num)
  9834. if _, ok := planExec["actualweightminus"]; ok {
  9835. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  9836. f.SetCellValue(sheetName, cell, actualweightminus)
  9837. f.SetCellStyle(sheetName, cell, cell, styleID)
  9838. } else {
  9839. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  9840. f.SetCellStyle(sheetName, cell, cell, styleID)
  9841. }
  9842. cell = fmt.Sprintf("F%d", num)
  9843. f.SetCellValue(sheetName, cell, planExec["fname"])
  9844. f.SetCellStyle(sheetName, cell, cell, styleID)
  9845. cell = fmt.Sprintf("G%d", num)
  9846. if _, ok := planExec["diff"]; ok {
  9847. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  9848. f.SetCellValue(sheetName, cell, diff)
  9849. f.SetCellStyle(sheetName, cell, cell, styleID)
  9850. } else {
  9851. f.SetCellValue(sheetName, cell, planExec["diff"])
  9852. f.SetCellStyle(sheetName, cell, cell, styleID)
  9853. }
  9854. cell = fmt.Sprintf("H%d", num)
  9855. if _, ok := planExec["diffRate"]; ok {
  9856. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  9857. f.SetCellValue(sheetName, cell, diffRate)
  9858. f.SetCellStyle(sheetName, cell, cell, styleID)
  9859. } else {
  9860. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  9861. f.SetCellStyle(sheetName, cell, cell, styleID)
  9862. }
  9863. cell = fmt.Sprintf("I%d", num)
  9864. f.SetCellValue(sheetName, cell, planExec["intime"])
  9865. f.SetCellStyle(sheetName, cell, cell, styleID)
  9866. cell = fmt.Sprintf("J%d", num)
  9867. if _, ok := planExec["lastactualweight"]; ok {
  9868. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  9869. f.SetCellValue(sheetName, cell, lastactualweight)
  9870. f.SetCellStyle(sheetName, cell, cell, styleID)
  9871. } else {
  9872. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  9873. f.SetCellStyle(sheetName, cell, cell, styleID)
  9874. }
  9875. cell = fmt.Sprintf("K%d", num)
  9876. if _, ok := planExec["actualweight"]; ok {
  9877. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  9878. f.SetCellValue(sheetName, cell, actualweight)
  9879. f.SetCellStyle(sheetName, cell, cell, styleID)
  9880. } else {
  9881. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  9882. f.SetCellStyle(sheetName, cell, cell, styleID)
  9883. }
  9884. num += 1
  9885. }
  9886. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  9887. for i, header := range headers2 {
  9888. cell := "%" + fmt.Sprintf("c%d", num)
  9889. cell = fmt.Sprintf(cell, 'C'+i)
  9890. f.SetCellValue(sheetName, cell, header)
  9891. f.SetCellStyle(sheetName, cell, cell, styleID)
  9892. maxWidth := len(header)
  9893. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  9894. }
  9895. num += 1
  9896. for _, plan2 := range plan2Map[plan["id"]] {
  9897. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  9898. sort, _ := strconv.Atoi(plan2["sort"])
  9899. f.SetCellValue(sheetName, cell, sort)
  9900. f.SetCellStyle(sheetName, cell, cell, styleID)
  9901. cell = fmt.Sprintf("D%d", num)
  9902. f.SetCellValue(sheetName, cell, plan2["fname"])
  9903. f.SetCellStyle(sheetName, cell, cell, styleID)
  9904. cell = fmt.Sprintf("E%d", num)
  9905. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  9906. f.SetCellValue(sheetName, cell, lweight)
  9907. f.SetCellStyle(sheetName, cell, cell, styleID)
  9908. cell = fmt.Sprintf("F%d", num)
  9909. if _, ok := plan2["actualweightminus"]; ok {
  9910. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  9911. f.SetCellValue(sheetName, cell, actualweightminus)
  9912. f.SetCellStyle(sheetName, cell, cell, styleID)
  9913. } else {
  9914. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  9915. f.SetCellStyle(sheetName, cell, cell, styleID)
  9916. }
  9917. cell = fmt.Sprintf("G%d", num)
  9918. if _, ok := plan2["diff"]; ok {
  9919. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  9920. f.SetCellValue(sheetName, cell, diff)
  9921. f.SetCellStyle(sheetName, cell, cell, styleID)
  9922. } else {
  9923. f.SetCellValue(sheetName, cell, plan2["diff"])
  9924. f.SetCellStyle(sheetName, cell, cell, styleID)
  9925. }
  9926. cell = fmt.Sprintf("H%d", num)
  9927. if _, ok := plan2["diffRate"]; ok {
  9928. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  9929. f.SetCellValue(sheetName, cell, diffRate)
  9930. f.SetCellStyle(sheetName, cell, cell, styleID)
  9931. } else {
  9932. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  9933. f.SetCellStyle(sheetName, cell, cell, styleID)
  9934. }
  9935. cell = fmt.Sprintf("I%d", num)
  9936. f.SetCellValue(sheetName, cell, plan2["intime"])
  9937. f.SetCellStyle(sheetName, cell, cell, styleID)
  9938. cell = fmt.Sprintf("J%d", num)
  9939. if _, ok := plan2["lastactualweight"]; ok {
  9940. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  9941. f.SetCellValue(sheetName, cell, lastactualweight)
  9942. f.SetCellStyle(sheetName, cell, cell, styleID)
  9943. } else {
  9944. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  9945. f.SetCellStyle(sheetName, cell, cell, styleID)
  9946. }
  9947. cell = fmt.Sprintf("K%d", num)
  9948. if _, ok := plan2["lastactualweight"]; ok {
  9949. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  9950. f.SetCellValue(sheetName, cell, actualweight)
  9951. f.SetCellStyle(sheetName, cell, cell, styleID)
  9952. } else {
  9953. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  9954. f.SetCellStyle(sheetName, cell, cell, styleID)
  9955. }
  9956. num += 1
  9957. }
  9958. num += 1
  9959. notBorder = append(notBorder, num)
  9960. }
  9961. for i := 2; i < num; i++ {
  9962. exist := false
  9963. for _, n := range notBorder {
  9964. if i+1 == n {
  9965. exist = true
  9966. break
  9967. }
  9968. }
  9969. if !exist {
  9970. // 为 A-K 列设置边框
  9971. for col := 'A'; col <= 'K'; col++ {
  9972. cellName := fmt.Sprintf("%c%d", col, i)
  9973. style, _ := f.NewStyle(&excelizexuri.Style{
  9974. Border: border, Alignment: &excelizexuri.Alignment{
  9975. Vertical: "center",
  9976. Horizontal: "center",
  9977. ShrinkToFit: true,
  9978. WrapText: true,
  9979. },
  9980. })
  9981. f.SetCellStyle(sheetName, cellName, cellName, style)
  9982. }
  9983. }
  9984. }
  9985. for col := 'A'; col <= 'K'; col++ {
  9986. colName := string(col)
  9987. switch colName {
  9988. case "A", "B": // 牧场名称、TMR列
  9989. f.SetColWidth(sheetName, colName, colName, 10)
  9990. case "C": // 操作编号列
  9991. f.SetColWidth(sheetName, colName, colName, 10)
  9992. case "D", "E": // 计划重量、实际重量列
  9993. f.SetColWidth(sheetName, colName, colName, 12)
  9994. case "F": // 代表成分/投料位置列
  9995. f.SetColWidth(sheetName, colName, colName, 20)
  9996. case "G", "H": // 误差数、准确率列
  9997. f.SetColWidth(sheetName, colName, colName, 12)
  9998. case "I": // 完成时间列
  9999. f.SetColWidth(sheetName, colName, colName, 15)
  10000. case "J", "K": // 起始读数重量、完成读数重量列
  10001. f.SetColWidth(sheetName, colName, colName, 15)
  10002. }
  10003. }
  10004. // 设置响应头
  10005. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10006. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10007. c.Header("Content-Transfer-Encoding", "binary")
  10008. // 写入 Excel 文件到响应
  10009. if err := f.Write(c.Writer); err != nil {
  10010. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10011. return
  10012. }
  10013. }
  10014. func RestartMqtt(c *gin.Context) {
  10015. appG := app.Gin{C: c}
  10016. // 发送 GET 请求到 MQTT 重启接口
  10017. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10018. if err != nil {
  10019. logging.Error("RestartMqtt request failed:", err)
  10020. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10021. return
  10022. }
  10023. defer resp.Body.Close()
  10024. // 读取响应内容f
  10025. body, err := ioutil.ReadAll(resp.Body)
  10026. if err != nil {
  10027. logging.Error("RestartMqtt read response failed:", err)
  10028. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10029. return
  10030. }
  10031. // 检查响应状态码
  10032. if resp.StatusCode != http.StatusOK {
  10033. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10034. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10035. return
  10036. }
  10037. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10038. }
  10039. func FpdBatchEditByWeight(c *gin.Context) {
  10040. appG := app.Gin{C: c}
  10041. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10042. fsions := gofasion.NewFasion(string(dataByte))
  10043. barList := fsions.Get("barList").Array()
  10044. pastureid := fsions.Get("pastureId").ValueStr()
  10045. tx := restful.Engine.NewSession()
  10046. defer tx.Close()
  10047. 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
  10048. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10049. if err != nil {
  10050. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10051. return
  10052. }
  10053. for _, barFsions := range barList {
  10054. dataexcel := make(map[string]interface{}, 0)
  10055. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10056. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10057. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10058. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10059. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10060. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10061. continue
  10062. }
  10063. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10064. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10065. // if err != nil {
  10066. // logs.Error(err)
  10067. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10068. // return
  10069. // }
  10070. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10071. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10072. // if err != nil {
  10073. // logs.Error(err)
  10074. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10075. // return
  10076. // }
  10077. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10078. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10079. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10080. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10081. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10082. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10083. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10084. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10085. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10086. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10087. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10088. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10089. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10090. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10091. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10092. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10093. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10094. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10095. if err != nil {
  10096. logs.Error(err)
  10097. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10098. return
  10099. }
  10100. if !ftexist {
  10101. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10102. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10103. if err != nil {
  10104. logs.Error(err)
  10105. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10106. return
  10107. }
  10108. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10109. if err != nil {
  10110. logs.Error(err)
  10111. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10112. return
  10113. }
  10114. }
  10115. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10116. if err != nil {
  10117. logs.Error(err)
  10118. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10119. return
  10120. }
  10121. if !exist {
  10122. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10123. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10124. if err != nil {
  10125. logs.Error(err)
  10126. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10127. return
  10128. }
  10129. }
  10130. var feedpargs []interface{}
  10131. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10132. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10133. if _, ok := dataexcel["ftname"]; ok {
  10134. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10135. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10136. // upFeedpSql += `,ftweight = ? `
  10137. // feedpargs = append(feedpargs, weight)
  10138. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10139. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10140. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10141. } else {
  10142. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10143. }
  10144. // if _, ok := dataexcel["ptsfname"]; ok {
  10145. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10146. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10147. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10148. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10149. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10150. // } else {
  10151. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10152. // }
  10153. upFeedpSql += " where barname = ? and pastureid = ? "
  10154. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10155. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10156. if err != nil {
  10157. logs.Error(err)
  10158. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10159. return
  10160. }
  10161. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10162. if err != nil {
  10163. logs.Error(err)
  10164. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10165. return
  10166. }
  10167. if !exist1 {
  10168. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10169. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10170. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10171. if err != nil {
  10172. logs.Error(err)
  10173. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10174. return
  10175. }
  10176. }
  10177. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10178. if err != nil {
  10179. logs.Error(err)
  10180. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10181. return
  10182. }
  10183. if !exist2 {
  10184. _, 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) `,
  10185. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10186. if err != nil {
  10187. logs.Error(err)
  10188. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10189. return
  10190. }
  10191. }
  10192. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10193. if err != nil {
  10194. logs.Error(err)
  10195. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10196. return
  10197. }
  10198. if !exist3 {
  10199. _, 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) `,
  10200. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10201. if err != nil {
  10202. logs.Error(err)
  10203. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10204. return
  10205. }
  10206. }
  10207. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10208. if err != nil {
  10209. logs.Error(err)
  10210. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10211. return
  10212. }
  10213. if !exist4 {
  10214. _, 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) `,
  10215. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10216. if err != nil {
  10217. logs.Error(err)
  10218. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10219. return
  10220. }
  10221. }
  10222. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  10223. if err != nil {
  10224. logs.Error(err)
  10225. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10226. return
  10227. }
  10228. if !exist5 {
  10229. _, 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) `,
  10230. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10231. if err != nil {
  10232. logs.Error(err)
  10233. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10234. return
  10235. }
  10236. }
  10237. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  10238. if err != nil {
  10239. logs.Error(err)
  10240. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10241. return
  10242. }
  10243. if !exist6 {
  10244. _, 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) `,
  10245. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10246. if err != nil {
  10247. logs.Error(err)
  10248. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10249. return
  10250. }
  10251. }
  10252. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10253. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10254. and pastureid = ? and times = ?`
  10255. var fpdargs1 []interface{}
  10256. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10257. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10258. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10259. if err != nil {
  10260. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10261. return
  10262. }
  10263. var fpdargs2 []interface{}
  10264. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10265. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10266. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10267. if err != nil {
  10268. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10269. return
  10270. }
  10271. var fpdargs3 []interface{}
  10272. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10273. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10274. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10275. if err != nil {
  10276. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10277. return
  10278. }
  10279. var fpdargs4 []interface{}
  10280. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10281. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10282. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10283. if err != nil {
  10284. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10285. return
  10286. }
  10287. var fpdargs5 []interface{}
  10288. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10289. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10290. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10291. if err != nil {
  10292. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10293. return
  10294. }
  10295. var fpdargs6 []interface{}
  10296. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10297. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10298. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10299. if err != nil {
  10300. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10301. return
  10302. }
  10303. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10304. 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()
  10305. if err != nil {
  10306. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10307. return
  10308. }
  10309. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10310. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10311. upFpdetailList := make([]*upFpdetail, 0)
  10312. for _, newfpd := range newList {
  10313. for _, oldfpd := range oldFpdList {
  10314. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10315. var oldweight, newweight float64
  10316. if oldfpd["weight"] != nil {
  10317. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10318. }
  10319. if newfpd["weight"] != nil {
  10320. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10321. }
  10322. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10323. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10324. Old: oldweight,
  10325. New: newweight,
  10326. Times: newfpd["times"].(int64),
  10327. Ptid: newfpd["ptid"].(int64),
  10328. Fweight: fweight,
  10329. Id: oldfpd["id"].(int64),
  10330. })
  10331. break
  10332. }
  10333. }
  10334. }
  10335. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10336. }
  10337. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10338. }
  10339. func FtImportExcel(c *gin.Context) {
  10340. appG := app.Gin{C: c}
  10341. inputdata := ""
  10342. c.Request.ParseForm()
  10343. params := c.Request.Form
  10344. file, _, err := c.Request.FormFile("file")
  10345. if err != nil {
  10346. appG.Response(http.StatusOK, e.ERROR, err)
  10347. return
  10348. }
  10349. sqlnamestrs := params.Get("name")
  10350. sheetname := params.Get("sheetname")
  10351. pastureid := params.Get("pastureid")
  10352. //importParams := params.Get("importParams")
  10353. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10354. // 必输项参数 (字符串格式 "field1,field2,field3")
  10355. requiredParams := params.Get("requiredParams")
  10356. // 日期参数
  10357. dateParams := params.Get("dateParams")
  10358. // 数字参数
  10359. numParams := params.Get("numParams")
  10360. //将字符串分割开
  10361. dateParamslist := strings.Split(dateParams, ",")
  10362. requiredParamslist := strings.Split(requiredParams, ",")
  10363. numParamslist := strings.Split(numParams, ",")
  10364. queryData := make([]interface{}, 0)
  10365. sqlslist := strings.Split(sqlnamestrs, ",")
  10366. xlsx1, err := excelize.OpenReader(file)
  10367. if err != nil {
  10368. fmt.Println(err)
  10369. return
  10370. }
  10371. ok := 0
  10372. error := 0
  10373. isdone := true
  10374. rows := xlsx1.GetRows(sheetname)
  10375. // 限制10000条,多余的截取掉
  10376. if len(rows) > 10000 {
  10377. rows = rows[:10000]
  10378. }
  10379. tx := restful.Engine.NewSession()
  10380. ftNameList := make(map[string]interface{})
  10381. for i, row := range rows {
  10382. if i > 0 {
  10383. entry := make(map[string]interface{})
  10384. outentry := make(map[string]interface{})
  10385. for j, colCell := range rows[0] {
  10386. for k, colCell1 := range row {
  10387. if j == k {
  10388. outentry[colCell] = colCell1
  10389. entry[colCell] = colCell1
  10390. }
  10391. }
  10392. }
  10393. inputdata = ""
  10394. a := ""
  10395. fmt.Println(outentry, entry)
  10396. //校验日期格式
  10397. for _, v := range dateParamslist {
  10398. if v == "" {
  10399. continue
  10400. }
  10401. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10402. dtime, err := TransfTime(d.(string))
  10403. if err != nil {
  10404. a = strings.Trim(v, " ")
  10405. break
  10406. }
  10407. outentry[strings.Trim(v, " ")] = dtime
  10408. }
  10409. }
  10410. if a != "" {
  10411. outentry["error_msg"] = a + " 格式错误"
  10412. error++
  10413. queryData = append(queryData, outentry)
  10414. continue
  10415. }
  10416. a = ""
  10417. //校验必填格式
  10418. for _, v := range requiredParamslist {
  10419. if v == "" {
  10420. continue
  10421. }
  10422. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  10423. a = strings.Trim(v, " ")
  10424. break
  10425. }
  10426. }
  10427. if a != "" {
  10428. outentry["error_msg"] = a + " 未填或格式错误"
  10429. error++
  10430. queryData = append(queryData, outentry)
  10431. continue
  10432. }
  10433. a = ""
  10434. //校验数字格式
  10435. for _, v := range numParamslist {
  10436. if v == "" {
  10437. continue
  10438. }
  10439. d, ok := outentry[strings.Trim(v, " ")]
  10440. if !ok || d == "" {
  10441. outentry[strings.Trim(v, " ")] = 0
  10442. } else {
  10443. var fl float64
  10444. switch d.(type) {
  10445. case string:
  10446. fl, err = strconv.ParseFloat(d.(string), 64)
  10447. }
  10448. if err != nil || fl < 0 {
  10449. a = strings.Trim(v, " ")
  10450. break
  10451. }
  10452. }
  10453. }
  10454. if a != "" {
  10455. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  10456. error++
  10457. queryData = append(queryData, outentry)
  10458. continue
  10459. }
  10460. err := tx.Begin()
  10461. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  10462. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  10463. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  10464. }
  10465. for _, sqlnamestr := range sqlslist {
  10466. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  10467. paramslist := strings.Split(paramslists, ",")
  10468. if len(paramslist) > 0 {
  10469. s_params := make([]interface{}, 0)
  10470. for _, value := range paramslist {
  10471. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  10472. if tempv, exists := c.Get("jwt_username"); exists {
  10473. s_params = append(s_params, tempv.(string))
  10474. } else {
  10475. s_params = append(s_params, "")
  10476. }
  10477. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  10478. s_params = append(s_params, pastureid)
  10479. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  10480. ids, err := setting.SnowIds.NextId()
  10481. if err != nil {
  10482. ids = time.Now().UnixNano()
  10483. logging.Info("create SnowIds err", err)
  10484. }
  10485. s_params = append(s_params, ids)
  10486. } else {
  10487. if outentry[strings.Trim(value, " ")] == nil {
  10488. s_params = append(s_params, "")
  10489. } else {
  10490. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  10491. }
  10492. }
  10493. }
  10494. outentry["input"] = inputdata
  10495. fmt.Println(sql, s_params)
  10496. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  10497. if err != nil {
  10498. if tx != nil {
  10499. tx.Rollback()
  10500. }
  10501. if tx != nil {
  10502. tx.Close()
  10503. }
  10504. msg := geterrmsg(err.Error())
  10505. outentry["error_msg"] = msg
  10506. error++
  10507. queryData = append(queryData, outentry)
  10508. isdone = true
  10509. break
  10510. } else {
  10511. if len(returnmsgmap1) > 0 {
  10512. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  10513. if tx != nil {
  10514. tx.Rollback()
  10515. }
  10516. if tx != nil {
  10517. tx.Close()
  10518. }
  10519. msg := geterrmsg(va.(string))
  10520. outentry["error_msg"] = msg
  10521. error++
  10522. queryData = append(queryData, outentry)
  10523. isdone = true
  10524. break
  10525. }
  10526. }
  10527. isdone = false
  10528. }
  10529. }
  10530. }
  10531. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  10532. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  10533. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  10534. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  10535. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  10536. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  10537. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  10538. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  10539. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, outentry["配方名称"]).QueryString()
  10540. FpdBatchEditGrfd(pastureid, values1)
  10541. switch {
  10542. case err != nil:
  10543. if tx != nil {
  10544. tx.Rollback()
  10545. }
  10546. default:
  10547. if tx != nil {
  10548. err = tx.Commit()
  10549. }
  10550. }
  10551. if tx != nil {
  10552. tx.Close()
  10553. }
  10554. }
  10555. if !isdone {
  10556. ok++
  10557. isdone = true
  10558. }
  10559. }
  10560. data := make(map[string]interface{})
  10561. data["result"] = queryData
  10562. data["success"] = ok
  10563. data["err_count"] = error
  10564. appG.Response(http.StatusOK, e.SUCCESS, data)
  10565. }