ops.go 458 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "math"
  11. "net/http"
  12. "os"
  13. "path"
  14. "regexp"
  15. "sort"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "tmr-watch/conf/setting"
  21. "tmr-watch/http/handle/jpud"
  22. "tmr-watch/http/handle/restful"
  23. "tmr-watch/http/handle/ymy"
  24. "tmr-watch/models"
  25. "tmr-watch/module"
  26. "tmr-watch/pkg/app"
  27. "tmr-watch/pkg/e"
  28. "tmr-watch/pkg/logging"
  29. "github.com/360EntSecGroup-Skylar/excelize"
  30. "github.com/Anderson-Lu/gofasion/gofasion"
  31. "github.com/astaxie/beego/logs"
  32. "github.com/gin-gonic/gin"
  33. "github.com/qichengzx/coordtransform"
  34. "github.com/tealeg/xlsx"
  35. "github.com/xormplus/xorm"
  36. excelizexuri "github.com/xuri/excelize/v2"
  37. )
  38. // @Summary 根据SQL执行得到数据集
  39. // @Tags getData
  40. // @Accept json
  41. // @Produce json
  42. // @Param sql query string true "sql"
  43. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  44. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  45. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  46. // @Router /data/getdata [POST]
  47. func GetData(c *gin.Context) {
  48. appG := app.Gin{C: c}
  49. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  50. fsion := gofasion.NewFasion(string(dataByte))
  51. sqlstr := fsion.Get("sql").ValueStr()
  52. offset := fsion.Get("offset").ValueDefaultInt(0)
  53. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  54. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  55. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  56. if err != nil {
  57. appG.Response(http.StatusOK, e.ERROR, err.Error())
  58. } else {
  59. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  60. }
  61. }
  62. func Testpartitions(c *gin.Context) {
  63. appG := app.Gin{C: c}
  64. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  65. fsion := gofasion.NewFasion(string(dataByte))
  66. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  67. user := fsion.Get("user").ValueStr() //获取新数据库用户
  68. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  69. host := fsion.Get("host").ValueStr() //获取新数据库名称
  70. port := fsion.Get("port").ValueStr() //获取新数据库名称
  71. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  72. if sqls == nil || err1 != nil {
  73. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  74. }
  75. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  76. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  77. mydb, err := sql.Open("mysql", connecting) //连接新连接
  78. if err != nil {
  79. println("err1", err.Error())
  80. }
  81. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  82. if err != nil {
  83. println("err2", err.Error())
  84. }
  85. mydb.Close()
  86. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  87. mydb, err = sql.Open("mysql", connecting)
  88. if err != nil {
  89. println("err3", err.Error())
  90. }
  91. defer mydb.Close()
  92. if err == nil {
  93. mydb.SetMaxOpenConns(10)
  94. mydb.SetMaxIdleConns(10)
  95. }
  96. errmsg := ""
  97. if err == nil {
  98. //tx ,_ :=mydb.Begin()
  99. for _, sqlstr := range sqlstrs {
  100. //println("sqlstr---",sqlstr)
  101. if sqlstr == "" {
  102. continue
  103. }
  104. _, err = mydb.Exec(sqlstr)
  105. if err != nil {
  106. println("err4", err.Error())
  107. errmsg = err.Error()
  108. //err1 :=tx.Rollback()
  109. }
  110. }
  111. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  112. //err =tx.Commit()
  113. }
  114. if errmsg == "" {
  115. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  116. } else {
  117. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  118. }
  119. }
  120. func TestData(c *gin.Context) {
  121. appG := app.Gin{C: c}
  122. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  123. fsion := gofasion.NewFasion(string(dataByte))
  124. sqlstr := fsion.Get("sql").ValueStr()
  125. token := ""
  126. if tempv, exists := c.Get("jwt_username"); exists {
  127. token = tempv.(string)
  128. }
  129. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  130. }
  131. // @Summary 根据APISQL表中SQL执行得到数据集
  132. // @Tags GetDataByName
  133. // @Accept json
  134. // @Produce json
  135. // @Param sqlname body string true "sqlname"
  136. // @Param offset body int true "offset"
  137. // @Param pagecount body int true "pagecount"
  138. // @Param returntype body string true "returntype"
  139. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  140. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  141. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  142. // @Router /data/GetDataByName [POST]
  143. func GetDataByName(c *gin.Context) {
  144. appG := app.Gin{C: c}
  145. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  146. fsion := gofasion.NewFasion(string(dataByte))
  147. sqlnamestr := fsion.Get("name").ValueStr()
  148. offset := fsion.Get("offset").ValueDefaultInt(0)
  149. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  150. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  151. tx := restful.Engine.NewSession()
  152. err := tx.Begin()
  153. defer func() {
  154. switch {
  155. case err != nil:
  156. logging.Error("tx.Begin 事务启动失败__error:", err)
  157. if tx != nil {
  158. tx.Rollback()
  159. }
  160. default:
  161. if tx != nil {
  162. err = tx.Commit()
  163. }
  164. }
  165. if tx != nil {
  166. tx.Close()
  167. }
  168. }()
  169. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  170. if sql != "" {
  171. s_params := make([]interface{}, 0)
  172. if fsion.HasKey("parammaps") {
  173. parammaps := fsion.Get("parammaps")
  174. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  175. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  176. }
  177. paramslist := strings.Split(p, ",")
  178. if len(paramslist) > 0 && p != "" {
  179. for _, value := range paramslist {
  180. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  181. if tempv, exists := c.Get("jwt_username"); exists {
  182. s_params = append(s_params, tempv.(string))
  183. } else {
  184. s_params = append(s_params, "")
  185. }
  186. } else {
  187. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  188. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  189. // tmrNameList := []string{}
  190. // for _, tmr := range tmrArray {
  191. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  192. // }
  193. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  194. // } else {
  195. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  196. // }
  197. }
  198. }
  199. }
  200. } else if fsion.HasKey("params") {
  201. params := fsion.Get("params").Array()
  202. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  203. for _, v_params := range params {
  204. s_params = append(s_params, v_params.ValueStr())
  205. }
  206. }
  207. if returntype == "xlsx" {
  208. var xlsxfile *xlsx.File
  209. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  210. //c.File("c:/dd.xlsx")
  211. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  212. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  213. c.Header("Content-Transfer-Encoding", "binary")
  214. _ = xlsxfile.Write(c.Writer)
  215. } else {
  216. if sqlnamestr == "getHomepageStr" {
  217. parammaps := fsion.Get("parammaps")
  218. pastureid := parammaps.Get("pastureid").ValueStr()
  219. var montimeList []float64
  220. var montime float64
  221. var wg sync.WaitGroup
  222. now := time.Now()
  223. for i := 0; i < 30; i++ {
  224. wg.Add(1)
  225. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  226. go func(nowstr string) {
  227. defer wg.Done()
  228. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  229. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  230. if len(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})) > 0 {
  231. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  232. montimeList = append(montimeList, m)
  233. }
  234. }(nowstr)
  235. }
  236. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  237. if err != nil {
  238. logging.Error("GetDataByName err: ", err)
  239. msg := geterrmsg(err.Error())
  240. appG.Response(http.StatusOK, e.ERROR, msg)
  241. }
  242. wg.Wait()
  243. for _, m := range montimeList {
  244. montime += m
  245. }
  246. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  247. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  248. return
  249. }
  250. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  251. if err != nil {
  252. logging.Error("GetDataByName err: ", err)
  253. msg := geterrmsg(err.Error())
  254. appG.Response(http.StatusOK, e.ERROR, msg)
  255. } else {
  256. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  257. }
  258. }
  259. } else {
  260. appG.Response(http.StatusOK, e.SUCCESS, nil)
  261. }
  262. }
  263. // @Summary 根据APISQL表中SQL执行得到数据集
  264. // @Tags GetDataByName
  265. // @Accept json
  266. // @Produce json
  267. // @Param sqlname body string true "sqlname"
  268. // @Param offset body int true "offset"
  269. // @Param pagecount body int true "pagecount"
  270. // @Param returntype body string true "returntype"
  271. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  272. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  273. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  274. // @Router /data/GetDataByName [POST]
  275. func GetDataBySqlIN(c *gin.Context) {
  276. appG := app.Gin{C: c}
  277. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  278. fsion := gofasion.NewFasion(string(dataByte))
  279. sqlnamestr := fsion.Get("name").ValueStr()
  280. offset := fsion.Get("offset").ValueDefaultInt(0)
  281. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  282. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  283. tx := restful.Engine.NewSession()
  284. err := tx.Begin()
  285. defer func() {
  286. switch {
  287. case err != nil:
  288. logging.Error("tx.Begin 事务启动失败__error:", err)
  289. if tx != nil {
  290. tx.Rollback()
  291. }
  292. default:
  293. if tx != nil {
  294. err = tx.Commit()
  295. }
  296. }
  297. if tx != nil {
  298. tx.Close()
  299. }
  300. }()
  301. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  302. if sql != "" {
  303. s_params := make([]interface{}, 0)
  304. if fsion.HasKey("parammaps") {
  305. parammaps := fsion.Get("parammaps")
  306. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  307. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  308. }
  309. paramslist := strings.Split(p, ",")
  310. if len(paramslist) > 0 && p != "" {
  311. for _, value := range paramslist {
  312. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  313. if tempv, exists := c.Get("jwt_username"); exists {
  314. s_params = append(s_params, tempv.(string))
  315. } else {
  316. s_params = append(s_params, "")
  317. }
  318. } else {
  319. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  320. }
  321. }
  322. }
  323. } else if fsion.HasKey("params") {
  324. params := fsion.Get("params").Array()
  325. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  326. for _, v_params := range params {
  327. s_params = append(s_params, v_params.ValueStr())
  328. }
  329. }
  330. if returntype == "xlsx" {
  331. var xlsxfile *xlsx.File
  332. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  333. //c.File("c:/dd.xlsx")
  334. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  335. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  336. c.Header("Content-Transfer-Encoding", "binary")
  337. _ = xlsxfile.Write(c.Writer)
  338. } else {
  339. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  340. if err != nil {
  341. logging.Error("GetDataByName err: ", err)
  342. msg := geterrmsg(err.Error())
  343. appG.Response(http.StatusOK, e.ERROR, msg)
  344. } else {
  345. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  346. }
  347. }
  348. } else {
  349. appG.Response(http.StatusOK, e.SUCCESS, nil)
  350. }
  351. }
  352. // 错误处理
  353. // 将报错信息处理成汉字
  354. func geterrmsg(errstr string) (msgstr string) {
  355. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  356. rs := []rune(errstr)
  357. if hzRegexp.MatchString(string(rs[0])) {
  358. msgstr = errstr
  359. return
  360. }
  361. if strings.Contains(errstr, "Duplicate entry") {
  362. strs := strings.Split(errstr, ` key '`)
  363. if len(strs) > 1 {
  364. if len(strs[len(strs)-1]) > 1 {
  365. errstr = "Duplicate entry :" + strs[len(strs)-1]
  366. }
  367. }
  368. }
  369. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  370. if err != nil {
  371. msgstr = errstr
  372. return
  373. }
  374. if msg == nil || len(msg) == 0 {
  375. var param []interface{}
  376. param = append(param, errstr, errstr)
  377. go func() {
  378. tx := restful.Engine.NewSession()
  379. err := tx.Begin()
  380. defer func() {
  381. switch {
  382. case err != nil:
  383. logging.Error("tx.Begin 事务启动失败__error:", err)
  384. if tx != nil {
  385. tx.Rollback()
  386. }
  387. default:
  388. if tx != nil {
  389. err = tx.Commit()
  390. }
  391. }
  392. if tx != nil {
  393. tx.Close()
  394. }
  395. }()
  396. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  397. if err != nil {
  398. logging.Error("insert into err_msg(err,msg) err", err)
  399. }
  400. }()
  401. msgstr = errstr
  402. } else {
  403. msgstr = msg[0]["msg"]
  404. }
  405. return
  406. }
  407. // @Summary 根据APISQL表中SQL执行得到数据集
  408. // @Tags GetDataByNameForm
  409. // @Accept json
  410. // @Produce json
  411. // @Param sqlname body json true "sqlname"
  412. // @Param offset query int true "offset"
  413. // @Param pagecount query int true "pagecount"
  414. // @Param returntype query string true "returntype"
  415. // @Param s formData json true "ss"
  416. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  417. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  418. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  419. // @Router /data/GetDataByNameForm [POST]
  420. func GetDataByNameForm(c *gin.Context) {
  421. appG := app.Gin{C: c}
  422. //sqlnamestr := c.PostForm("measureNumber")
  423. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  424. //fsion := gofasion.NewFasion(string(dataByte))
  425. //sqlnamestr := fsion.Get("name").ValueStr()
  426. //offset := fsion.Get("offset").ValueInt()
  427. //pagecount := fsion.Get("pagecount").ValueInt()
  428. //returntype := fsion.Get("returntype").ValueStr()
  429. //params := fsion.Get("params").Array()
  430. c.Request.ParseForm()
  431. params := c.Request.Form
  432. offset := 0
  433. pageSize_ := 0
  434. returntype := params.Get("page")
  435. if returntype == "" {
  436. returntype = "0"
  437. }
  438. if tempv, exists := c.Get("jwt_username"); exists {
  439. params.Set("JwtUserName", tempv.(string))
  440. } else {
  441. params.Set("JwtUserName", "")
  442. }
  443. sqlnamestr := params.Get("name")
  444. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  445. s_params := make([]interface{}, 0)
  446. if returntype == "1" {
  447. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  448. if error != nil {
  449. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  450. }
  451. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  452. if error != nil {
  453. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  454. }
  455. pageSize_ = pageSize
  456. offset = pageNum
  457. }
  458. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  459. paramslist := strings.Split(p, ",")
  460. if len(paramslist) > 0 && p != "" {
  461. for _, value := range paramslist {
  462. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  463. }
  464. }
  465. if sql != "" {
  466. if returntype == "xlsx" {
  467. var xlsxfile *xlsx.File
  468. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  469. c.Header("Content-Type", "application/octet-stream")
  470. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  471. c.Header("Content-Transfer-Encoding", "binary")
  472. _ = xlsxfile.Write(c.Writer)
  473. } else {
  474. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  475. if err != nil {
  476. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  477. } else {
  478. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  479. }
  480. }
  481. } else {
  482. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  483. }
  484. }
  485. // @Summary 递归获取所有
  486. // @Tags menu
  487. // @Accept json
  488. // @Produce json
  489. // @Param Ton query string true "Ton"
  490. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  491. // @Router /authdata/GetRoleMenus [GET]
  492. func GetRecuDataByName(c *gin.Context) {
  493. appG := app.Gin{C: c}
  494. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  495. fsion := gofasion.NewFasion(string(dataByte))
  496. sqlnamestr := fsion.Get("name").ValueStr()
  497. parentidname := fsion.Get("idname").ValueStr()
  498. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  499. params := make(map[string]interface{})
  500. s_params := make([]interface{}, 0)
  501. if fsion.HasKey("params") {
  502. for _, v_params := range fsion.Get("params").Array() {
  503. s_params = append(s_params, v_params.ValueStr())
  504. }
  505. params["params"] = s_params
  506. } else {
  507. jparams := fsion.Get("parammaps")
  508. paramslist := strings.Split(p, ",")
  509. if len(paramslist) > 0 && p != "" {
  510. for _, value := range paramslist {
  511. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  512. if tempv, exists := c.Get("jwt_username"); exists {
  513. params[value] = tempv.(string)
  514. } else {
  515. params[value] = ""
  516. }
  517. } else {
  518. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  519. }
  520. }
  521. }
  522. }
  523. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  524. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  525. if err != nil {
  526. appG.Response(http.StatusOK, e.ERROR, err.Error())
  527. }
  528. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  529. }
  530. // @Summary 根据APISQL表中SQL执行得到数据集
  531. // @Tags GetDataByNames
  532. // @Accept json
  533. // @Produce json
  534. // @RequestBody sqlname query string true "sqlname"
  535. // @Param offset query int true "offset"
  536. // @Param pagecount query int true "pagecount"
  537. // @Param returntype query string true "returntype"
  538. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  539. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  540. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  541. // @Router /data/GetDataByNames [POST]
  542. func GetDataByNames(c *gin.Context) {
  543. appG := app.Gin{C: c}
  544. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  545. fsion := gofasion.NewFasion(string(dataByte))
  546. sqlParams := fsion.Array()
  547. queryData := make(map[string]interface{})
  548. for _, v := range sqlParams {
  549. fsion2 := gofasion.NewFasion(v.Json())
  550. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  551. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  552. if sql == "" {
  553. errorm := make(map[string]interface{})
  554. errorm["code"] = e.ERROR
  555. errorm["message"] = "sql没找到"
  556. queryData[fsion2.Get("name").ValueStr()] = errorm
  557. continue
  558. } else if sql != "" {
  559. offset := fsion2.Get("offset").ValueInt()
  560. pagecount := fsion2.Get("pagecount").ValueInt()
  561. returntype := fsion2.Get("returntype").ValueStr()
  562. s_params := make([]interface{}, 0)
  563. if fsion2.HasKey("parammaps") {
  564. parammaps := fsion2.Get("parammaps")
  565. paramslist := strings.Split(p, ",")
  566. if len(paramslist) > 0 && p != "" {
  567. for _, value := range paramslist {
  568. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  569. if tempv, exists := c.Get("jwt_username"); exists {
  570. s_params = append(s_params, tempv.(string))
  571. } else {
  572. s_params = append(s_params, "")
  573. }
  574. } else {
  575. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  576. }
  577. }
  578. }
  579. } else if fsion2.HasKey("params") {
  580. params := fsion2.Get("params").Array()
  581. for _, v_params := range params {
  582. s_params = append(s_params, v_params.ValueStr())
  583. }
  584. }
  585. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  586. if err != nil {
  587. errorm := make(map[string]interface{})
  588. errorm["code"] = e.ERROR
  589. errorm["message"] = err.Error()
  590. queryData[fsion2.Get("name").ValueStr()] = errorm
  591. logging.Error("GetDataByNames err: ", err)
  592. continue
  593. } else {
  594. queryData[fsion2.Get("name").ValueStr()] = queryData1
  595. }
  596. }
  597. }
  598. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  599. }
  600. // @Summary 根据APISQL表中SQL执行得到数据集
  601. // @Tags PostDataByNameForm
  602. // @Accept json
  603. // @Produce json
  604. // @Param sqlname query string true "sqlname"
  605. // @Param offset query int true "offset"
  606. // @Param pagecount query int true "pagecount"
  607. // @Param returntype query string true "returntype"
  608. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  609. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  610. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  611. // @Router /data/PostDataByNameForm [POST]
  612. func PostDataByNameForm(c *gin.Context) {
  613. appG := app.Gin{C: c}
  614. c.Request.ParseForm()
  615. params := c.Request.Form
  616. sqlnamestr := params.Get("name")
  617. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  618. s_params := make([]interface{}, 0)
  619. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  620. paramslist := strings.Split(p, ",")
  621. if len(paramslist) > 0 {
  622. for _, value := range paramslist {
  623. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  624. }
  625. }
  626. if sql != "" {
  627. queryData, err := execDataBySql(sql, s_params)
  628. if err != nil {
  629. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  630. } else {
  631. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  632. }
  633. } else {
  634. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  635. }
  636. }
  637. // GetReportform 将数据集转换格式
  638. // @Tags PostDataByNameForm
  639. // @Accept json
  640. // @Produce json
  641. // @Param sqlname query string true "sqlname"
  642. // @Param offset query int true "offset"
  643. // @Param pagecount query int true "pagecount"
  644. // @Param returntype query string true "returntype"
  645. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  646. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  647. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  648. func GetReportform(c *gin.Context) {
  649. appG := app.Gin{C: c}
  650. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  651. fsion := gofasion.NewFasion(string(dataByte))
  652. sqlnamestr := fsion.Get("name").ValueStr()
  653. checked := fsion.Get("checked").ValueStr()
  654. offset := fsion.Get("offset").ValueDefaultInt(0)
  655. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  656. parammaps := fsion.Get("parammaps")
  657. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  658. mode := parammaps.Get("mode").ValueDefaultInt(0)
  659. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  660. tx := restful.Engine.NewSession()
  661. err := tx.Begin()
  662. defer func() {
  663. switch {
  664. case err != nil:
  665. if tx != nil {
  666. tx.Rollback()
  667. }
  668. default:
  669. if tx != nil {
  670. err = tx.Commit()
  671. }
  672. }
  673. if tx != nil {
  674. tx.Close()
  675. }
  676. }()
  677. //fmt.Println("***************************************")
  678. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  679. if err != nil {
  680. appG.Response(http.StatusOK, e.ERROR, err.Error())
  681. } else {
  682. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  683. }
  684. }
  685. // GetUpkeepPlan 保养计划
  686. func GetUpkeepPlan(c *gin.Context) {
  687. appG := app.Gin{C: c}
  688. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  689. fsion := gofasion.NewFasion(string(dataByte))
  690. sqlnamestr := fsion.Get("name").ValueStr()
  691. offset := fsion.Get("offset").ValueDefaultInt(0)
  692. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  693. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  694. month := fsion.Get("month").ValueDefaultStr("map")
  695. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  696. tx := restful.Engine.NewSession()
  697. err := tx.Begin()
  698. defer func() {
  699. switch {
  700. case err != nil:
  701. if tx != nil {
  702. tx.Rollback()
  703. }
  704. default:
  705. if tx != nil {
  706. err = tx.Commit()
  707. }
  708. }
  709. if tx != nil {
  710. tx.Close()
  711. }
  712. }()
  713. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  714. if sql != "" {
  715. s_params := make([]interface{}, 0)
  716. if fsion.HasKey("parammaps") {
  717. parammaps := fsion.Get("parammaps")
  718. paramslist := strings.Split(p, ",")
  719. if len(paramslist) > 0 && p != "" {
  720. for _, value := range paramslist {
  721. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  722. if tempv, exists := c.Get("jwt_username"); exists {
  723. s_params = append(s_params, tempv.(string))
  724. } else {
  725. s_params = append(s_params, "")
  726. }
  727. } else {
  728. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  729. }
  730. }
  731. }
  732. } else if fsion.HasKey("params") {
  733. params := fsion.Get("params").Array()
  734. for _, v_params := range params {
  735. s_params = append(s_params, v_params.ValueStr())
  736. }
  737. }
  738. if returntype == "xlsx" {
  739. var xlsxfile *xlsx.File
  740. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  741. //c.File("c:/dd.xlsx")
  742. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  743. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  744. c.Header("Content-Transfer-Encoding", "binary")
  745. _ = xlsxfile.Write(c.Writer)
  746. } else {
  747. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  748. if err != nil {
  749. appG.Response(http.StatusOK, e.ERROR, err.Error())
  750. } else {
  751. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  752. if v, ok := value["id"]; ok {
  753. //month = "2020-03"
  754. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  755. if seviceplans != nil {
  756. for _, va := range seviceplans { //根据保养计划获取保养单
  757. //day,_ :=strconv.Atoi(va["day"])
  758. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  759. //buk := make(map[string]map[string]string)
  760. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  761. jstr := ""
  762. if bu["plantime"][8:9] == "0" {
  763. jstr = "m" + bu["plantime"][9:]
  764. } else {
  765. jstr = "m" + bu["plantime"][8:]
  766. }
  767. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  768. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  769. } else {
  770. if bu["flowCompeleted"] >= "2" {
  771. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  772. } else {
  773. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  774. }
  775. }
  776. }
  777. }
  778. }
  779. }
  780. }
  781. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  782. }
  783. }
  784. } else {
  785. appG.Response(http.StatusOK, e.SUCCESS, nil)
  786. }
  787. }
  788. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  789. // todo 优化性能 children统一查询
  790. // @Tags PostDataByNameForm
  791. // @Accept json
  792. // @Produce json
  793. // @Param sqlname query string true "sqlname"
  794. // @Param offset query int true "offset"
  795. // @Param pagecount query int true "pagecount"
  796. // @Param returntype query string true "returntype"
  797. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  798. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  799. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  800. func GetArrList(c *gin.Context) {
  801. appG := app.Gin{C: c}
  802. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  803. fsion := gofasion.NewFasion(string(dataByte))
  804. sqlnamestr := fsion.Get("name").ValueStr()
  805. sqlnamestr1 := fsion.Get("name1").ValueStr()
  806. offset := fsion.Get("offset").ValueDefaultInt(0)
  807. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  808. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  809. month := fsion.Get("month").ValueDefaultStr("map")
  810. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  811. tx := restful.Engine.NewSession()
  812. err := tx.Begin()
  813. defer func() {
  814. switch {
  815. case err != nil:
  816. if tx != nil {
  817. tx.Rollback()
  818. }
  819. default:
  820. if tx != nil {
  821. err = tx.Commit()
  822. }
  823. }
  824. if tx != nil {
  825. tx.Close()
  826. }
  827. }()
  828. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  829. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  830. if sql != "" {
  831. s_params := make([]interface{}, 0)
  832. if fsion.HasKey("parammaps") {
  833. parammaps := fsion.Get("parammaps")
  834. paramslist := strings.Split(p, ",")
  835. if len(paramslist) > 0 && p != "" {
  836. for _, value := range paramslist {
  837. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  838. if tempv, exists := c.Get("jwt_username"); exists {
  839. s_params = append(s_params, tempv.(string))
  840. } else {
  841. s_params = append(s_params, "")
  842. }
  843. } else {
  844. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  845. }
  846. }
  847. }
  848. }
  849. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  850. if err != nil {
  851. appG.Response(http.StatusOK, e.ERROR, err.Error())
  852. } else {
  853. paramslist1 := strings.Split(p1, ",")
  854. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  855. s_params1 := make([]interface{}, 0)
  856. if len(paramslist1) > 0 && p1 != "" {
  857. for _, v := range paramslist1 {
  858. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  859. }
  860. }
  861. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  862. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  863. }
  864. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  865. }
  866. } else {
  867. appG.Response(http.StatusOK, e.SUCCESS, nil)
  868. }
  869. }
  870. func GetAccount(c *gin.Context) {
  871. appG := app.Gin{C: c}
  872. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  873. fsion := gofasion.NewFasion(string(dataByte))
  874. sqlnamestr := fsion.Get("name").ValueStr()
  875. offset := fsion.Get("offset").ValueDefaultInt(0)
  876. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  877. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  878. tx := restful.Engine.NewSession()
  879. err := tx.Begin()
  880. defer func() {
  881. switch {
  882. case err != nil:
  883. logging.Error("tx.Begin 事务启动失败__error:", err)
  884. if tx != nil {
  885. tx.Rollback()
  886. }
  887. default:
  888. if tx != nil {
  889. err = tx.Commit()
  890. }
  891. }
  892. if tx != nil {
  893. tx.Close()
  894. }
  895. }()
  896. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  897. if sql != "" {
  898. s_params := make([]interface{}, 0)
  899. if fsion.HasKey("parammaps") {
  900. parammaps := fsion.Get("parammaps")
  901. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  902. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  903. }
  904. paramslist := strings.Split(p, ",")
  905. if len(paramslist) > 0 && p != "" {
  906. for _, value := range paramslist {
  907. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  908. if tempv, exists := c.Get("jwt_username"); exists {
  909. s_params = append(s_params, tempv.(string))
  910. } else {
  911. s_params = append(s_params, "")
  912. }
  913. } else {
  914. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  915. }
  916. }
  917. }
  918. } else if fsion.HasKey("params") {
  919. params := fsion.Get("params").Array()
  920. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  921. for _, v_params := range params {
  922. s_params = append(s_params, v_params.ValueStr())
  923. }
  924. }
  925. if returntype == "xlsx" {
  926. var xlsxfile *xlsx.File
  927. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  928. //c.File("c:/dd.xlsx")
  929. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  930. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  931. c.Header("Content-Transfer-Encoding", "binary")
  932. _ = xlsxfile.Write(c.Writer)
  933. } else {
  934. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  935. if err != nil {
  936. logging.Error("GetDataByName err: ", err)
  937. msg := geterrmsg(err.Error())
  938. appG.Response(http.StatusOK, e.ERROR, msg)
  939. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  940. } else {
  941. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  942. }
  943. }
  944. } else {
  945. appG.Response(http.StatusOK, e.SUCCESS, nil)
  946. }
  947. }
  948. // PostDataByName 根据APISQL表中SQL执行得到数据集
  949. // @Accept json
  950. // @Produce json
  951. // @Param sqlname query string true "sqlname"
  952. // @Param offset query int true "offset"
  953. // @Param pagecount query int true "pagecount"
  954. // @Param returntype query string true "returntype"
  955. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  956. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  957. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  958. // @Router /data/PostDataByName [POST]
  959. func PostDataByName(c *gin.Context) {
  960. appG := app.Gin{C: c}
  961. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  962. fsion := gofasion.NewFasion(string(dataByte))
  963. var err error
  964. queryData, err := module.PostDataByName(c, fsion)
  965. if err != nil {
  966. appG.Response(http.StatusOK, e.ERROR, err.Error())
  967. return
  968. }
  969. var (
  970. keyWord string
  971. )
  972. switch fsion.Get("name").ValueStr() {
  973. case "insertFeedclass":
  974. keyWord = "feed"
  975. err = module.GroupCategorySync(keyWord, fsion)
  976. case "deleteFeedclass":
  977. keyWord = "feed_delete"
  978. err = module.GroupCategoryDelete(keyWord, fsion)
  979. case "insertCowclass":
  980. keyWord = "cow"
  981. err = module.GroupCategorySync(keyWord, fsion)
  982. case "deleteCowclass":
  983. keyWord = "cow_delete"
  984. err = module.GroupCategoryDelete(keyWord, fsion)
  985. // case "updateFT":
  986. // FtdetailSurplus(fsion)
  987. // case "updateFeed":
  988. // FeedSurplus(fsion)
  989. default:
  990. }
  991. if err != nil {
  992. logging.Error(keyWord, err)
  993. }
  994. if queryData != nil {
  995. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  996. return
  997. }
  998. appG.Response(http.StatusOK, e.SUCCESS, nil)
  999. }
  1000. //人脸识别/格润富德接口
  1001. func GetRJSBData(c *gin.Context) {
  1002. appG := app.Gin{C: c}
  1003. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1004. fsion := gofasion.NewFasion(string(dataByte))
  1005. sqlnamestr := fsion.Get("name").ValueStr()
  1006. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1007. offset := fsion.Get("offset").ValueDefaultInt(0)
  1008. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1009. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1010. month := fsion.Get("month").ValueDefaultStr("map")
  1011. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1012. pagecount = 1
  1013. tx := restful.Engine.NewSession()
  1014. err := tx.Begin()
  1015. defer func() {
  1016. switch {
  1017. case err != nil:
  1018. if tx != nil {
  1019. tx.Rollback()
  1020. }
  1021. default:
  1022. if tx != nil {
  1023. err = tx.Commit()
  1024. }
  1025. }
  1026. if tx != nil {
  1027. tx.Close()
  1028. }
  1029. }()
  1030. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1031. _, err = tx.SQL(`update tmr set xianfeng = (select id from downloadedplan where lpplantype = 5 and mydate = date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted = 0 )
  1032. where id = (select tmrid from downloadedplan d where d.pid = (select pid from downloadedplan where lpplantype = 5 and mydate =
  1033. date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted= 0 ) and mydate = date_format(now() ,'%Y-%m-%d')
  1034. and lpplantype in(0,1)) `).Execute()
  1035. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1036. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1037. if sql != "" {
  1038. s_params := make([]interface{}, 0)
  1039. if fsion.HasKey("parammaps") {
  1040. parammaps := fsion.Get("parammaps")
  1041. paramslist := strings.Split(p, ",")
  1042. if len(paramslist) > 0 && p != "" {
  1043. for _, value := range paramslist {
  1044. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1045. if tempv, exists := c.Get("jwt_username"); exists {
  1046. s_params = append(s_params, tempv.(string))
  1047. } else {
  1048. s_params = append(s_params, "")
  1049. }
  1050. } else {
  1051. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1052. }
  1053. }
  1054. }
  1055. }
  1056. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1057. if err != nil {
  1058. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1059. } else {
  1060. paramslist1 := strings.Split(p1, ",")
  1061. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1062. s_params1 := make([]interface{}, 0)
  1063. if len(paramslist1) > 0 && p1 != "" {
  1064. for _, v := range paramslist1 {
  1065. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1066. }
  1067. }
  1068. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1069. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1070. }
  1071. var wg sync.WaitGroup
  1072. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1073. wg.Add(1)
  1074. go func(value map[string]interface{}) {
  1075. defer wg.Done()
  1076. // ,havebutton = 1
  1077. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1078. }(value)
  1079. }
  1080. wg.Wait()
  1081. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1082. }
  1083. fmt.Println("先锋获取数据:", time.Now(), queryData)
  1084. } else {
  1085. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1086. }
  1087. }
  1088. func PostRJSBData(c *gin.Context) {
  1089. appG := app.Gin{C: c}
  1090. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1091. fsion := gofasion.NewFasion(string(dataByte))
  1092. logging.Info("PostRJSBData err: ", string(dataByte))
  1093. s_params := make([]interface{}, 0)
  1094. tx := restful.Engine.NewSession()
  1095. err := tx.Begin()
  1096. defer func() {
  1097. switch {
  1098. case err != nil:
  1099. if tx != nil {
  1100. tx.Rollback()
  1101. }
  1102. default:
  1103. if tx != nil {
  1104. err = tx.Commit()
  1105. }
  1106. }
  1107. if tx != nil {
  1108. tx.Close()
  1109. }
  1110. }()
  1111. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1112. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1113. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1114. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1115. if !fsion.HasKey("parammaps") {
  1116. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1117. return
  1118. }
  1119. parammaps := fsion.Get("parammaps")
  1120. paramslist := strings.Split(p, ",")
  1121. if len(paramslist) > 0 && p != "" {
  1122. for _, value := range paramslist {
  1123. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1124. }
  1125. }
  1126. projuctid := parammaps.Get("projuctid").ValueStr()
  1127. _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
  1128. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1129. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1130. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1131. and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1132. if err != nil {
  1133. logging.Error("PostRJSBData-0 err: ", err)
  1134. msg := geterrmsg(err.Error())
  1135. // appG.Response(http.StatusOK, e.ERROR, msg)
  1136. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1137. return
  1138. }
  1139. _, err = tx.SQL(sql, s_params...).Execute()
  1140. if err != nil {
  1141. logging.Error("PostRJSBData err: ", err)
  1142. msg := geterrmsg(err.Error())
  1143. // appG.Response(http.StatusOK, e.ERROR, msg)
  1144. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1145. return
  1146. }
  1147. s_params = make([]interface{}, 0)
  1148. paramslist = strings.Split(p1, ",")
  1149. if len(paramslist) > 0 && p1 != "" {
  1150. for _, value := range paramslist {
  1151. // if value == "ID" {
  1152. // id := parammaps.Get("ID").ValueStr()
  1153. // pastureid := parammaps.Get("pastureid").ValueStr()
  1154. // datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  1155. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1156. // if err != nil {
  1157. // logging.Error("PostRJSBData err: ", err)
  1158. // msg := geterrmsg(err.Error())
  1159. // appG.Response(http.StatusOK, e.ERROR, msg)
  1160. // return
  1161. // }
  1162. // for _, item := range datalist {
  1163. // id = item["id"]
  1164. // }
  1165. // s_params = append(s_params, id)
  1166. // } else {
  1167. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1168. // }
  1169. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1170. }
  1171. }
  1172. _, err = tx.SQL(sql1, s_params...).Execute()
  1173. if err != nil {
  1174. logging.Error("PostRJSBData1 err: ", err)
  1175. msg := geterrmsg(err.Error())
  1176. appG.Response(http.StatusOK, e.ERROR, msg)
  1177. return
  1178. }
  1179. s_params = make([]interface{}, 0)
  1180. paramslist = strings.Split(p2, ",")
  1181. if len(paramslist) > 0 && p2 != "" {
  1182. for _, value := range paramslist {
  1183. if value == "ID" {
  1184. id := parammaps.Get("ID").ValueStr()
  1185. pastureid := parammaps.Get("pastureid").ValueStr()
  1186. 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
  1187. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1188. if err != nil {
  1189. logging.Error("PostRJSBData err: ", err)
  1190. msg := geterrmsg(err.Error())
  1191. appG.Response(http.StatusOK, e.ERROR, msg)
  1192. return
  1193. }
  1194. for _, item := range datalist {
  1195. id = item["id"]
  1196. }
  1197. s_params = append(s_params, id)
  1198. } else {
  1199. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1200. }
  1201. }
  1202. }
  1203. _, err = tx.SQL(sql2, s_params...).Execute()
  1204. if err != nil {
  1205. logging.Error("PostRJSBData2 err: ", err)
  1206. msg := geterrmsg(err.Error())
  1207. appG.Response(http.StatusOK, e.ERROR, msg)
  1208. return
  1209. }
  1210. s_params = make([]interface{}, 0)
  1211. paramslist = strings.Split(p3, ",")
  1212. if len(paramslist) > 0 && p3 != "" {
  1213. for _, value := range paramslist {
  1214. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1215. }
  1216. }
  1217. _, err = tx.SQL(sql3, s_params...).Execute()
  1218. if err != nil {
  1219. logging.Error("PostRJSBData3 err: ", err)
  1220. msg := geterrmsg(err.Error())
  1221. appG.Response(http.StatusOK, e.ERROR, msg)
  1222. return
  1223. }
  1224. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1225. }
  1226. func PostRJSBDatas(c *gin.Context) {
  1227. appG := app.Gin{C: c}
  1228. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1229. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1230. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1231. fmt.Println("先锋回传数据:", time.Now(), string(dataByte))
  1232. tx := restful.Engine.NewSession()
  1233. err := tx.Begin()
  1234. defer func() {
  1235. switch {
  1236. case err != nil:
  1237. if tx != nil {
  1238. tx.Rollback()
  1239. }
  1240. default:
  1241. if tx != nil {
  1242. err = tx.Commit()
  1243. }
  1244. }
  1245. if tx != nil {
  1246. tx.Close()
  1247. }
  1248. }()
  1249. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1250. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1251. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1252. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1253. for _, fsion := range fsions {
  1254. if !fsion.HasKey("parammaps") {
  1255. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1256. return
  1257. }
  1258. parammaps := fsion.Get("parammaps")
  1259. ID := parammaps.Get("ID").ValueStr()
  1260. if ID == "" {
  1261. continue
  1262. }
  1263. s_params := make([]interface{}, 0)
  1264. paramslist := strings.Split(p, ",")
  1265. if len(paramslist) > 0 && p != "" {
  1266. for _, value := range paramslist {
  1267. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1268. }
  1269. }
  1270. _, err := tx.SQL(sql, s_params...).Execute()
  1271. if err != nil {
  1272. logging.Error("PostRJSBData err: ", err)
  1273. msg := geterrmsg(err.Error())
  1274. // appG.Response(http.StatusOK, e.ERROR, msg)
  1275. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1276. return
  1277. }
  1278. s_params = make([]interface{}, 0)
  1279. paramslist = strings.Split(p1, ",")
  1280. if len(paramslist) > 0 && p1 != "" {
  1281. for _, value := range paramslist {
  1282. // if value == "ID" {
  1283. // id := parammaps.Get("ID").ValueStr()
  1284. // pastureid := parammaps.Get("pastureid").ValueStr()
  1285. // 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
  1286. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1287. // if err != nil {
  1288. // logging.Error("PostRJSBData err: ", err)
  1289. // msg := geterrmsg(err.Error())
  1290. // appG.Response(http.StatusOK, e.ERROR, msg)
  1291. // return
  1292. // }
  1293. // for _, item := range datalist {
  1294. // id = item["id"]
  1295. // }
  1296. // s_params = append(s_params, id)
  1297. // } else {
  1298. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1299. // }
  1300. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1301. }
  1302. }
  1303. _, err = tx.SQL(sql1, s_params...).Execute()
  1304. if err != nil {
  1305. logging.Error("PostRJSBData1 err: ", err)
  1306. msg := geterrmsg(err.Error())
  1307. appG.Response(http.StatusOK, e.ERROR, msg)
  1308. return
  1309. }
  1310. s_params = make([]interface{}, 0)
  1311. paramslist = strings.Split(p2, ",")
  1312. if len(paramslist) > 0 && p2 != "" {
  1313. for _, value := range paramslist {
  1314. if value == "ID" {
  1315. id := parammaps.Get("ID").ValueStr()
  1316. pastureid := parammaps.Get("pastureid").ValueStr()
  1317. 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
  1318. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1319. if err != nil {
  1320. logging.Error("PostRJSBData err: ", err)
  1321. msg := geterrmsg(err.Error())
  1322. appG.Response(http.StatusOK, e.ERROR, msg)
  1323. return
  1324. }
  1325. for _, item := range datalist {
  1326. id = item["id"]
  1327. }
  1328. s_params = append(s_params, id)
  1329. } else {
  1330. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1331. }
  1332. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1333. }
  1334. }
  1335. _, err = tx.SQL(sql2, s_params...).Execute()
  1336. if err != nil {
  1337. logging.Error("PostRJSBData2 err: ", err)
  1338. msg := geterrmsg(err.Error())
  1339. appG.Response(http.StatusOK, e.ERROR, msg)
  1340. return
  1341. }
  1342. s_params = make([]interface{}, 0)
  1343. paramslist = strings.Split(p3, ",")
  1344. if len(paramslist) > 0 && p3 != "" {
  1345. for _, value := range paramslist {
  1346. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1347. }
  1348. }
  1349. _, err = tx.SQL(sql3, s_params...).Execute()
  1350. if err != nil {
  1351. logging.Error("PostRJSBData3 err: ", err)
  1352. msg := geterrmsg(err.Error())
  1353. appG.Response(http.StatusOK, e.ERROR, msg)
  1354. return
  1355. }
  1356. // ALTER TABLE `tmr`
  1357. // ADD COLUMN `concentrate` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 未回传 1 已回传' AFTER `appoint`
  1358. projuctid := parammaps.Get("projuctid").ValueStr()
  1359. _, err = tx.SQL(`update tmr set xianfeng = 0, concentrate = (select d.id from downloadedplan d
  1360. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1361. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1362. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1363. and lpplantype in(0,1)) and ( select count(1) from downloadedplan where id = ? and iscompleted = 0 ) = 0 `,
  1364. projuctid, projuctid, projuctid, projuctid, projuctid).Execute()
  1365. if err != nil {
  1366. logging.Error("PostRJSBData-0 err: ", err)
  1367. msg := geterrmsg(err.Error())
  1368. // appG.Response(http.StatusOK, e.ERROR, msg)
  1369. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1370. return
  1371. }
  1372. count, _ := tx.SQL(`select count(1) from downloadedplan where id = ? and iscompleted = 0`, projuctid).Count()
  1373. if count == 0 {
  1374. fmt.Println(projuctid, "先锋回传计划已完成", count, err)
  1375. }
  1376. }
  1377. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1378. }
  1379. // @Summary 根据APISQL表中SQL执行得到数据集
  1380. // @Tags ExecDataByConfig
  1381. // @Accept json
  1382. // @Produce json
  1383. // @Param sqlname query string true "sqlname"
  1384. // @Param offset query int true "offset"
  1385. // @Param pagecount query int true "pagecount"
  1386. // @Param returntype query string true "returntype"
  1387. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1388. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1389. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1390. // @Router /data/PostDataByName [POST]
  1391. func ExecDataByConfig(c *gin.Context) {
  1392. appG := app.Gin{C: c}
  1393. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1394. tempval_ := make(map[string]interface{})
  1395. tempCommon := make(map[string]interface{})
  1396. tempval := make([]map[string]interface{}, 0)
  1397. err := json.Unmarshal(dataByte, &tempval_)
  1398. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1399. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1400. if err != nil {
  1401. } else {
  1402. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1403. tempCommon = v
  1404. }
  1405. if v, ok := tempval_["data"].([]interface{}); ok {
  1406. for _, Tvalue := range v {
  1407. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1408. tempval = append(tempval, v1)
  1409. }
  1410. }
  1411. }
  1412. tx := restful.Engine.NewSession()
  1413. err := tx.Begin()
  1414. if err != nil {
  1415. logging.Error("tx.Begin 事务启动失败__error:", err)
  1416. }
  1417. defer func() {
  1418. switch {
  1419. case err != nil:
  1420. if tx != nil {
  1421. tx.Rollback()
  1422. }
  1423. default:
  1424. if tx != nil {
  1425. err = tx.Commit()
  1426. }
  1427. }
  1428. if tx != nil {
  1429. tx.Close()
  1430. }
  1431. }()
  1432. if err == nil {
  1433. if tempv, exists := c.Get("jwt_username"); exists {
  1434. tempCommon["jwt_username"] = tempv.(string)
  1435. }
  1436. for _, paramvalue := range tempval {
  1437. fmt.Println(paramvalue["name"])
  1438. if paramvalue["name"].(string) == "updateBigFP" {
  1439. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1440. if err != nil {
  1441. msg := geterrmsg(err.Error())
  1442. appG.Response(http.StatusOK, e.ERROR, msg)
  1443. return
  1444. }
  1445. }
  1446. }
  1447. for _, paramvalue := range tempval {
  1448. if _, ok := paramvalue["resultname"]; !ok {
  1449. paramvalue["resultname"] = paramvalue["name"]
  1450. }
  1451. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1452. if err != nil {
  1453. logging.Error("ExecDataParam error:", err)
  1454. break
  1455. }
  1456. if paramvalue["name"].(string) == "createdownloadedplan" {
  1457. checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1458. }
  1459. }
  1460. if err == nil {
  1461. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1462. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1463. } else {
  1464. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1465. }
  1466. } else {
  1467. msg := geterrmsg(err.Error())
  1468. appG.Response(http.StatusOK, e.ERROR, msg)
  1469. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1470. }
  1471. }
  1472. }
  1473. if err != nil {
  1474. msg := geterrmsg(err.Error())
  1475. appG.Response(http.StatusOK, e.ERROR, msg)
  1476. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1477. }
  1478. }
  1479. func interfacetostring(val interface{}) string {
  1480. switch val.(type) {
  1481. case string:
  1482. ss := val.(string)
  1483. return ss
  1484. break
  1485. case int:
  1486. ss := val.(int)
  1487. return strconv.Itoa(ss)
  1488. break
  1489. case int64:
  1490. ss := val.(int64)
  1491. return strconv.FormatInt(ss, 10)
  1492. break
  1493. case float64:
  1494. ss := val.(float64)
  1495. return strconv.FormatFloat(ss, 'E', -1, 32)
  1496. break
  1497. }
  1498. return ""
  1499. }
  1500. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1501. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1502. tempstrb := strings.IndexAny(valuestring, "@")
  1503. tempstre := strings.IndexAny(valuestring, ".")
  1504. if tempstrb > -1 && tempstre > -1 {
  1505. for _, ParamMapList := range ParamMap {
  1506. if v, ok := ParamMapList["resultname"]; ok {
  1507. if v == valuestring[tempstrb+1:tempstre] {
  1508. if v1, ok := ParamMapList["resultmaps"]; ok {
  1509. if newA, ok := v1.([]map[string]interface{}); ok {
  1510. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1511. } else if newA, ok := v1.(map[string]interface{}); ok {
  1512. return interfacetostring(newA[valuestring[tempstre+1:]])
  1513. }
  1514. }
  1515. }
  1516. }
  1517. }
  1518. } else {
  1519. return valuestring
  1520. }
  1521. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1522. return fmt.Sprintf("%f", valuestring)
  1523. }
  1524. return ""
  1525. }
  1526. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1527. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1528. tempstrb := strings.IndexAny(valuestring, "@")
  1529. tempstre := strings.IndexAny(valuestring, ".")
  1530. if tempstrb > -1 && tempstre > -1 {
  1531. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1532. if s, ok := v.(string); ok {
  1533. return s
  1534. } else if s, ok := v.(float64); ok {
  1535. return strconv.FormatFloat(s, 'f', -1, 64)
  1536. // return strconv.FormatInt(int64(s), 10)
  1537. }
  1538. }
  1539. }
  1540. }
  1541. return ""
  1542. }
  1543. 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) {
  1544. sqlname := fasion["name"].(string)
  1545. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1546. if v, ok := fasion["type"]; ok {
  1547. sqltype = v.(string)
  1548. }
  1549. sql := ""
  1550. p := ""
  1551. s_params := make([]interface{}, 0)
  1552. if sqltype != "" {
  1553. sql, p = restful.GetSqlByName(sqlname, tx)
  1554. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1555. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1556. paramslist := strings.Split(p, ",")
  1557. if len(paramslist) > 0 && p != "" {
  1558. for _, value := range paramslist {
  1559. ss := ""
  1560. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1561. ids, err := setting.SnowIds.NextId()
  1562. if err != nil {
  1563. ids = time.Now().UnixNano()
  1564. logging.Info("create SnowIds err", err)
  1565. }
  1566. s_params = append(s_params, ids)
  1567. } else {
  1568. if ss == "" && CommonParamMap != nil {
  1569. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1570. ss = valuestring
  1571. tempstrb := strings.IndexAny(valuestring, "@")
  1572. tempstre := strings.IndexAny(valuestring, ".")
  1573. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1574. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1575. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1576. }
  1577. } else {
  1578. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1579. ss = ""
  1580. }
  1581. }
  1582. }
  1583. }
  1584. if ss == "" && ParentParamMap != nil {
  1585. ss = getParamValue_(v, value, ParentParamMap)
  1586. }
  1587. if ss == "" && sameParamMap != nil {
  1588. ss = getParamValue(v, value, sameParamMap)
  1589. }
  1590. if ss == "" && ParamMap != nil {
  1591. ss = getParamValue(v, value, ParamMap)
  1592. }
  1593. s_params = append(s_params, ss)
  1594. }
  1595. }
  1596. }
  1597. }
  1598. }
  1599. if sql == "" {
  1600. sqltype = ""
  1601. }
  1602. if sqltype == "s1" {
  1603. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1604. if v, ok := tempValParam.(map[string]interface{}); ok {
  1605. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  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 == "sm" {
  1616. tempValParam, err := restful.QueryByMap(sql, 0, 0, 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. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1625. if err != nil {
  1626. return nil, err
  1627. }
  1628. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1629. } else if sqltype == "v" {
  1630. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1631. if v, ok := tempValParam.(map[string]interface{}); ok {
  1632. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1633. } else {
  1634. }
  1635. if err != nil {
  1636. return nil, err
  1637. }
  1638. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1639. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1640. }
  1641. } else if sqltype == "e" {
  1642. tempVal_arrary := make([]map[string]interface{}, 0)
  1643. tempVal_map := make(map[string]interface{})
  1644. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1645. if err == nil {
  1646. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1647. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1648. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1649. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1650. return tempVal_arrary, err
  1651. }
  1652. return nil, err
  1653. } else {
  1654. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1655. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1656. if err != nil {
  1657. return nil, err
  1658. }
  1659. return nil, err
  1660. }
  1661. }
  1662. return nil, nil
  1663. }
  1664. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1665. var err error
  1666. subarray, ok := fasion["children"]
  1667. if ok {
  1668. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1669. tempVal_arrary := make([]map[string]interface{}, 0)
  1670. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1671. tempVal_ := make(map[string]interface{})
  1672. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1673. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1674. } else {
  1675. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1676. }
  1677. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1678. if err != nil {
  1679. return err
  1680. }
  1681. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1682. }
  1683. v.(map[string]interface{})["children"] = tempVal_arrary
  1684. }
  1685. }
  1686. return nil
  1687. }
  1688. // @Summary 删除图片
  1689. // @Tags RemovePicByName
  1690. // @Accept json
  1691. // @Produce json
  1692. // @Param sqlname query string true "sqlname"
  1693. // @Param offset query int true "offset"
  1694. // @Param pagecount query int true "pagecount"
  1695. // @Param returntype query string true "returntype"
  1696. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1697. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1698. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1699. // @Router /data/PostDataByName [POST]
  1700. func RemovePicByName(c *gin.Context) {
  1701. logging.Info("RemovePicByName ", c.Keys)
  1702. appG := app.Gin{C: c}
  1703. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1704. fsion := gofasion.NewFasion(string(dataByte))
  1705. sqlnamestr := fsion.Get("name").ValueStr()
  1706. picname := fsion.Get("picname").ValueStr()
  1707. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1708. params := fsion.Get("params").Array()
  1709. s_params := make([]interface{}, 0)
  1710. for _, v_params := range params {
  1711. s_params = append(s_params, v_params.ValueStr())
  1712. }
  1713. if sql != "" {
  1714. queryData, err := execDataBySql(sql, s_params)
  1715. if picname != "" {
  1716. // Destination
  1717. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1718. err := os.Remove(distPath) //删除文件test.txt
  1719. if err != nil {
  1720. //如果删除失败则输出 file remove Error!
  1721. fmt.Println("file remove Error!")
  1722. //输出错误详细信息
  1723. fmt.Printf("%s", err)
  1724. } else {
  1725. //如果删除成功则输出 file remove OK!
  1726. fmt.Print("file remove OK!")
  1727. }
  1728. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1729. err = os.Remove(distPath) //删除文件test.txt
  1730. if err != nil {
  1731. //如果删除失败则输出 file remove Error!
  1732. fmt.Println("file remove Error!")
  1733. //输出错误详细信息
  1734. fmt.Printf("%s", err)
  1735. } else {
  1736. //如果删除成功则输出 file remove OK!
  1737. fmt.Print("file remove OK!")
  1738. }
  1739. }
  1740. if err != nil {
  1741. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1742. } else {
  1743. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1744. }
  1745. } else {
  1746. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1747. }
  1748. }
  1749. // @Summary 删除文件
  1750. // @Tags RemoveFileByName
  1751. // @Accept json
  1752. // @Produce json
  1753. // @Param sqlname query string true "sqlname"
  1754. // @Param offset query int true "offset"
  1755. // @Param pagecount query int true "pagecount"
  1756. // @Param returntype query string true "returntype"
  1757. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1758. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1759. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1760. // @Router /data/PostDataByName [POST]
  1761. func RemoveFileByName(c *gin.Context) {
  1762. appG := app.Gin{C: c}
  1763. id := c.Param("id")
  1764. logging.Info("DownloadFile ", c.Keys, id)
  1765. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1766. if eqdoc == nil {
  1767. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1768. return
  1769. }
  1770. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1771. err = os.Remove(distPath) //删除文件test.txt
  1772. if err != nil {
  1773. //如果删除失败则输出 file remove Error!
  1774. fmt.Println("file remove Error!")
  1775. //输出错误详细信息
  1776. fmt.Printf("%s", err)
  1777. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1778. return
  1779. }
  1780. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1781. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1782. }
  1783. // @Summary 根据APISQL表中SQL执行得到数据集
  1784. // @Tags PostDataByName
  1785. // @Accept json
  1786. // @Produce json
  1787. // @Param sqlname query string true "sqlname"
  1788. // @Param offset query int true "offset"
  1789. // @Param pagecount query int true "pagecount"
  1790. // @Param returntype query string true "returntype"
  1791. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1792. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1793. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1794. // @Router /data/PostDataByName [POST]
  1795. func UpdateDataRelation(c *gin.Context) {
  1796. appG := app.Gin{C: c}
  1797. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1798. fsion := gofasion.NewFasion(string(dataByte))
  1799. tablename := fsion.Get("name").ValueStr()
  1800. dataname := fsion.Get("dataname").ValueStr()
  1801. datavalue := fsion.Get("datavalue").ValueStr()
  1802. valuename := fsion.Get("valuename").ValueStr()
  1803. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1804. values := fsion.Get("values").Array()
  1805. tx := restful.Engine.NewSession()
  1806. err := tx.Begin()
  1807. defer func() {
  1808. switch {
  1809. case err != nil:
  1810. if tx != nil {
  1811. tx.Rollback()
  1812. }
  1813. default:
  1814. if tx != nil {
  1815. err = tx.Commit()
  1816. }
  1817. }
  1818. if tx != nil {
  1819. tx.Close()
  1820. }
  1821. }()
  1822. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1823. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1824. d_params := make([]interface{}, 4)
  1825. d_params[0] = datavalue
  1826. s_params := ""
  1827. for _, v_values := range values {
  1828. d_params[1] = v_values.ValueStr()
  1829. if s_params == "" {
  1830. s_params = v_values.ValueStr()
  1831. } else {
  1832. s_params = s_params + "," + v_values.ValueStr()
  1833. }
  1834. d_params[2] = d_params[1]
  1835. d_params[3] = d_params[0]
  1836. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1837. if err != nil {
  1838. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1839. break
  1840. }
  1841. }
  1842. if s_params != "" {
  1843. deleteSqlstr := "delete from " + tablename + " " +
  1844. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1845. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1846. if err != nil {
  1847. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1848. } else if err == nil {
  1849. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1850. }
  1851. } else {
  1852. deleteSqlstr := "delete from " + tablename + " " +
  1853. " where " + dataname + " = " + datavalue
  1854. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1855. if err != nil {
  1856. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1857. } else if err == nil {
  1858. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1859. }
  1860. }
  1861. }
  1862. // @Summary 根据APISQL表中SQL执行得到数据集
  1863. // @Tags PostDatasByName
  1864. // @Accept json
  1865. // @Produce json
  1866. // @Param sqlname query string true "sqlname"
  1867. // @Param offset query int true "offset"
  1868. // @Param pagecount query int true "pagecount"
  1869. // @Param returntype query string true "returntype"
  1870. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1871. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1872. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1873. // @Router /data/PostDatasByName [POST]
  1874. func PostDataByNames(c *gin.Context) {
  1875. appG := app.Gin{C: c}
  1876. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1877. fsion := gofasion.NewFasion(string(dataByte))
  1878. sqlParams := fsion.Get("array").Array()
  1879. queryData := make(map[string]interface{})
  1880. for _, v := range sqlParams {
  1881. fsion2 := gofasion.NewFasion(v.Json())
  1882. ss := fsion2.Get("name")
  1883. aa := fsion2.Get("params")
  1884. fmt.Println(ss, aa)
  1885. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1886. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1887. if sql == "" {
  1888. errorm := make(map[string]interface{})
  1889. errorm["code"] = e.ERROR
  1890. errorm["message"] = "sql没有找到"
  1891. errorm["param"] = ""
  1892. queryData[fsion2.Get("name").ValueStr()] = errorm
  1893. continue
  1894. } else if sql != "" {
  1895. s_params := make([]interface{}, 0)
  1896. if fsion2.HasKey("parammaps") {
  1897. parammaps := fsion2.Get("parammaps")
  1898. paramslist := strings.Split(p, ",")
  1899. if len(paramslist) > 0 && p != "" {
  1900. for _, value := range paramslist {
  1901. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1902. if tempv, exists := c.Get("jwt_username"); exists {
  1903. s_params = append(s_params, tempv.(string))
  1904. } else {
  1905. s_params = append(s_params, "")
  1906. }
  1907. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1908. ids, err := setting.SnowIds.NextId()
  1909. if err != nil {
  1910. ids = time.Now().UnixNano()
  1911. logging.Info("create SnowIds err", err)
  1912. }
  1913. s_params = append(s_params, ids)
  1914. } else {
  1915. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1916. }
  1917. }
  1918. }
  1919. } else if fsion2.HasKey("params") {
  1920. params := fsion2.Get("params").Array()
  1921. //ids,err := setting.SnowIds.NextId()
  1922. //if err !=nil{
  1923. // ids = time.Now().UnixNano()
  1924. // logging.Info("create SnowIds err",err)
  1925. //}
  1926. //s_params = append(s_params, ids)
  1927. for _, v_params := range params {
  1928. s_params = append(s_params, v_params.ValueStr())
  1929. }
  1930. }
  1931. _, err := execDataBySql(sql, s_params)
  1932. if err != nil {
  1933. logging.Error("PostDataByName err: ", err)
  1934. errorm := make(map[string]interface{})
  1935. errorm["code"] = e.ERROR
  1936. errorm["message"] = err.Error()
  1937. errorm["param"] = s_params
  1938. queryData[fsion2.Get("name").ValueStr()] = errorm
  1939. continue
  1940. } else {
  1941. errorm := make(map[string]interface{})
  1942. errorm["code"] = e.SUCCESS
  1943. errorm["message"] = "success"
  1944. queryData[fsion2.Get("name").ValueStr()] = errorm
  1945. continue
  1946. }
  1947. } else {
  1948. errorm := make(map[string]interface{})
  1949. errorm["code"] = e.ERROR
  1950. errorm["message"] = "NO SQL"
  1951. errorm["param"] = ""
  1952. queryData[fsion2.Get("name").ValueStr()] = errorm
  1953. }
  1954. }
  1955. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1956. }
  1957. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1958. if offset > 0 {
  1959. offset = offset - 1
  1960. }
  1961. //if pagecount == 0 {
  1962. // pagecount = setting.AppSetting.PageSize
  1963. //}else if pagecount>setting.AppSetting.PageSize{
  1964. // pagecount = setting.AppSetting.PageSize
  1965. //}
  1966. if returntype == "list" {
  1967. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1968. return queryData, err
  1969. } else if returntype == "listlist" {
  1970. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1971. return queryData, err
  1972. } else {
  1973. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1974. return queryData, err
  1975. }
  1976. }
  1977. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1978. if offset > 0 {
  1979. offset = offset - 1
  1980. }
  1981. //if pagecount == 0 {
  1982. // pagecount = setting.AppSetting.PageSize
  1983. //}else if pagecount>setting.AppSetting.PageSize{
  1984. // pagecount = setting.AppSetting.PageSize
  1985. //}
  1986. if returntype == "list" {
  1987. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1988. return queryData, err
  1989. } else if returntype == "listlist" {
  1990. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1991. return queryData, err
  1992. } else {
  1993. fmt.Println(params)
  1994. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1995. return queryData, err
  1996. }
  1997. }
  1998. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1999. paramslist := strings.Split(Params, ",")
  2000. s_params := make([]interface{}, 0)
  2001. if isList {
  2002. for _, v_params := range thisParams["params"].([]interface{}) {
  2003. s_params = append(s_params, v_params)
  2004. }
  2005. } else {
  2006. paramslist := strings.Split(Params, ",")
  2007. if len(paramslist) > 0 && Params != "" {
  2008. for _, value := range paramslist {
  2009. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2010. }
  2011. }
  2012. }
  2013. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  2014. for _, queryData_ := range queryData {
  2015. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  2016. if isList {
  2017. if queryData_[idname] != nil {
  2018. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  2019. }
  2020. } else {
  2021. if queryData_[idname] != nil {
  2022. thisParams[idname] = queryData_[idname].(interface{})
  2023. }
  2024. if len(paramslist) > 0 && Params != "" {
  2025. s_params = make([]interface{}, 0)
  2026. for _, value := range paramslist {
  2027. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2028. }
  2029. }
  2030. }
  2031. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  2032. } else {
  2033. }
  2034. }
  2035. return queryData, err
  2036. }
  2037. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2038. queryData, err := restful.ExecQuery(sqlstr, params)
  2039. return queryData, err
  2040. }
  2041. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2042. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2043. return queryData, err
  2044. }
  2045. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2046. queryData, err := restful.ExecQuery(sqlstr, params)
  2047. return queryData, err
  2048. }
  2049. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2050. // @Tags ImportExcel
  2051. // @Accept json
  2052. // @Produce json
  2053. // @Param file query string true "文件名"
  2054. // @Param name header string true "执行sql的名字"
  2055. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2056. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2057. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2058. // @Router /data/ImportExcel [POST]
  2059. func ImportExcel(c *gin.Context) {
  2060. appG := app.Gin{C: c}
  2061. inputdata := ""
  2062. c.Request.ParseForm()
  2063. params := c.Request.Form
  2064. file, _, err := c.Request.FormFile("file")
  2065. if err != nil {
  2066. appG.Response(http.StatusOK, e.ERROR, err)
  2067. return
  2068. }
  2069. sqlnamestrs := params.Get("name")
  2070. sheetname := params.Get("sheetname")
  2071. pastureid := params.Get("pastureid")
  2072. //importParams := params.Get("importParams")
  2073. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2074. // 必输项参数 (字符串格式 "field1,field2,field3")
  2075. requiredParams := params.Get("requiredParams")
  2076. // 日期参数
  2077. dateParams := params.Get("dateParams")
  2078. // 数字参数
  2079. numParams := params.Get("numParams")
  2080. //将字符串分割开
  2081. dateParamslist := strings.Split(dateParams, ",")
  2082. requiredParamslist := strings.Split(requiredParams, ",")
  2083. numParamslist := strings.Split(numParams, ",")
  2084. queryData := make([]interface{}, 0)
  2085. sqlslist := strings.Split(sqlnamestrs, ",")
  2086. xlsx1, err := excelize.OpenReader(file)
  2087. if err != nil {
  2088. fmt.Println(err)
  2089. return
  2090. }
  2091. ok := 0
  2092. error := 0
  2093. isdone := true
  2094. rows := xlsx1.GetRows(sheetname)
  2095. // 限制10000条,多余的截取掉
  2096. if len(rows) > 10000 {
  2097. rows = rows[:10000]
  2098. }
  2099. for i, row := range rows {
  2100. if i > 0 {
  2101. entry := make(map[string]interface{})
  2102. outentry := make(map[string]interface{})
  2103. for j, colCell := range rows[0] {
  2104. for k, colCell1 := range row {
  2105. if j == k {
  2106. outentry[colCell] = colCell1
  2107. entry[colCell] = colCell1
  2108. }
  2109. }
  2110. }
  2111. inputdata = ""
  2112. a := ""
  2113. fmt.Println(outentry, entry)
  2114. //校验日期格式
  2115. for _, v := range dateParamslist {
  2116. if v == "" {
  2117. continue
  2118. }
  2119. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2120. dtime, err := TransfTime(d.(string))
  2121. if err != nil {
  2122. a = strings.Trim(v, " ")
  2123. break
  2124. }
  2125. outentry[strings.Trim(v, " ")] = dtime
  2126. }
  2127. }
  2128. if a != "" {
  2129. outentry["error_msg"] = a + " 格式错误"
  2130. error++
  2131. queryData = append(queryData, outentry)
  2132. continue
  2133. }
  2134. a = ""
  2135. //校验必填格式
  2136. for _, v := range requiredParamslist {
  2137. if v == "" {
  2138. continue
  2139. }
  2140. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2141. a = strings.Trim(v, " ")
  2142. break
  2143. }
  2144. }
  2145. if a != "" {
  2146. outentry["error_msg"] = a + " 未填或格式错误"
  2147. error++
  2148. queryData = append(queryData, outentry)
  2149. continue
  2150. }
  2151. a = ""
  2152. //校验数字格式
  2153. for _, v := range numParamslist {
  2154. if v == "" {
  2155. continue
  2156. }
  2157. d, ok := outentry[strings.Trim(v, " ")]
  2158. if !ok || d == "" {
  2159. outentry[strings.Trim(v, " ")] = 0
  2160. } else {
  2161. var fl float64
  2162. switch d.(type) {
  2163. case string:
  2164. fl, err = strconv.ParseFloat(d.(string), 64)
  2165. }
  2166. if err != nil || fl < 0 {
  2167. a = strings.Trim(v, " ")
  2168. break
  2169. }
  2170. }
  2171. }
  2172. if a != "" {
  2173. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2174. error++
  2175. queryData = append(queryData, outentry)
  2176. continue
  2177. }
  2178. tx := restful.Engine.NewSession()
  2179. err := tx.Begin()
  2180. for _, sqlnamestr := range sqlslist {
  2181. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2182. paramslist := strings.Split(paramslists, ",")
  2183. if len(paramslist) > 0 {
  2184. s_params := make([]interface{}, 0)
  2185. for _, value := range paramslist {
  2186. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2187. if tempv, exists := c.Get("jwt_username"); exists {
  2188. s_params = append(s_params, tempv.(string))
  2189. } else {
  2190. s_params = append(s_params, "")
  2191. }
  2192. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2193. s_params = append(s_params, pastureid)
  2194. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2195. ids, err := setting.SnowIds.NextId()
  2196. if err != nil {
  2197. ids = time.Now().UnixNano()
  2198. logging.Info("create SnowIds err", err)
  2199. }
  2200. s_params = append(s_params, ids)
  2201. } else {
  2202. if outentry[strings.Trim(value, " ")] == nil {
  2203. s_params = append(s_params, "")
  2204. } else {
  2205. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2206. }
  2207. }
  2208. }
  2209. outentry["input"] = inputdata
  2210. fmt.Println(sql, s_params)
  2211. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2212. if err != nil {
  2213. if tx != nil {
  2214. tx.Rollback()
  2215. }
  2216. if tx != nil {
  2217. tx.Close()
  2218. }
  2219. msg := geterrmsg(err.Error())
  2220. outentry["error_msg"] = msg
  2221. error++
  2222. queryData = append(queryData, outentry)
  2223. isdone = true
  2224. break
  2225. } else {
  2226. if len(returnmsgmap1) > 0 {
  2227. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2228. if tx != nil {
  2229. tx.Rollback()
  2230. }
  2231. if tx != nil {
  2232. tx.Close()
  2233. }
  2234. msg := geterrmsg(va.(string))
  2235. outentry["error_msg"] = msg
  2236. error++
  2237. queryData = append(queryData, outentry)
  2238. isdone = true
  2239. break
  2240. }
  2241. }
  2242. isdone = false
  2243. }
  2244. }
  2245. }
  2246. switch {
  2247. case err != nil:
  2248. if tx != nil {
  2249. tx.Rollback()
  2250. }
  2251. default:
  2252. if tx != nil {
  2253. err = tx.Commit()
  2254. }
  2255. }
  2256. if tx != nil {
  2257. tx.Close()
  2258. }
  2259. }
  2260. if !isdone {
  2261. ok++
  2262. isdone = true
  2263. }
  2264. }
  2265. data := make(map[string]interface{})
  2266. data["result"] = queryData
  2267. data["success"] = ok
  2268. data["err_count"] = error
  2269. appG.Response(http.StatusOK, e.SUCCESS, data)
  2270. }
  2271. func TransfTime(timestr string) (string, error) {
  2272. if timestr == "" {
  2273. return time.Now().Format("2006-01-02"), nil
  2274. }
  2275. days, err := strconv.Atoi(timestr)
  2276. if err != nil {
  2277. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2278. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2279. }
  2280. _, err := time.Parse("2006-01-02", timestr)
  2281. if err != nil {
  2282. t, err := time.Parse("2006/01/02", timestr)
  2283. if err != nil {
  2284. t, err := time.Parse("2006.01.02", timestr)
  2285. if err != nil {
  2286. return "", err
  2287. } else {
  2288. return t.Format("2006-01-02"), nil
  2289. }
  2290. } else {
  2291. return t.Format("2006-01-02"), nil
  2292. }
  2293. } else {
  2294. return timestr, nil
  2295. }
  2296. }
  2297. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2298. times = times.AddDate(0, 0, days)
  2299. return times.Format("2006-01-02"), nil
  2300. }
  2301. func Createchart(c *gin.Context) {
  2302. appG := app.Gin{C: c}
  2303. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2304. fsion := gofasion.NewFasion(string(dataByte))
  2305. chart_name := fsion.Get("chart_name").ValueStr()
  2306. desc := fsion.Get("desc").ValueStr()
  2307. pastureid := fsion.Get("pastureid").ValueStr()
  2308. source_id := fsion.Get("source_id").ValueStr()
  2309. emp := fsion.Get("emp").ValueStr()
  2310. content := fsion.Get("content").Json()
  2311. var mapResult map[string]interface{}
  2312. err1 := json.Unmarshal([]byte(content), &mapResult)
  2313. if err1 != nil {
  2314. fmt.Println("JsonToMapDemo err: ", err1)
  2315. }
  2316. tx := restful.Engine.NewSession()
  2317. err := tx.Begin()
  2318. defer func() {
  2319. switch {
  2320. case err != nil:
  2321. logging.Error("tx.Begin 事务启动失败__error:", err)
  2322. if tx != nil {
  2323. tx.Rollback()
  2324. }
  2325. default:
  2326. if tx != nil {
  2327. err = tx.Commit()
  2328. }
  2329. }
  2330. if tx != nil {
  2331. tx.Close()
  2332. }
  2333. }()
  2334. ids, err := setting.SnowIds.NextId()
  2335. if err != nil {
  2336. ids = time.Now().UnixNano()
  2337. logging.Info("create SnowIds err", err)
  2338. }
  2339. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2340. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2341. if err != nil {
  2342. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2343. } else {
  2344. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2345. }
  2346. }
  2347. func Updatedashboard(c *gin.Context) {
  2348. appG := app.Gin{C: c}
  2349. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2350. fsion := gofasion.NewFasion(string(dataByte))
  2351. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2352. pastureid := fsion.Get("pastureid").ValueStr()
  2353. content := fsion.Get("content").Json()
  2354. var mapResult map[string]interface{}
  2355. err1 := json.Unmarshal([]byte(content), &mapResult)
  2356. if err1 != nil {
  2357. fmt.Println("JsonToMapDemo err: ", err1)
  2358. }
  2359. layout := mapResult["layout"]
  2360. tx := restful.Engine.NewSession()
  2361. err := tx.Begin()
  2362. defer func() {
  2363. switch {
  2364. case err != nil:
  2365. logging.Error("tx.Begin 事务启动失败__error:", err)
  2366. if tx != nil {
  2367. tx.Rollback()
  2368. }
  2369. default:
  2370. if tx != nil {
  2371. err = tx.Commit()
  2372. }
  2373. }
  2374. if tx != nil {
  2375. tx.Close()
  2376. }
  2377. }()
  2378. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2379. if err != nil {
  2380. println("2", err.Error())
  2381. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2382. } else {
  2383. if exec != nil {
  2384. if exec[0]["content"] == nil {
  2385. mapR := make(map[string]interface{})
  2386. mapR["layout"] = layout
  2387. mjson, _ := json.Marshal(mapR)
  2388. mString := string(mjson)
  2389. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2390. if err3 != nil {
  2391. println("3", err3.Error())
  2392. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2393. } else {
  2394. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2395. }
  2396. } else {
  2397. var mapR map[string]interface{}
  2398. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2399. if err1 != nil {
  2400. fmt.Println("JsonToMapDemo err: ", err2)
  2401. }
  2402. mapR["layout"] = layout
  2403. mjson, _ := json.Marshal(mapR)
  2404. mString := string(mjson)
  2405. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2406. if err3 != nil {
  2407. println("3", err3.Error())
  2408. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2409. } else {
  2410. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2411. }
  2412. }
  2413. } else {
  2414. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2415. }
  2416. }
  2417. }
  2418. func ExecSQL(c *gin.Context) {
  2419. appG := app.Gin{C: c}
  2420. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2421. fsion := gofasion.NewFasion(string(dataByte))
  2422. content := fsion.Get("content").Json()
  2423. pastureid := fsion.Get("pastureid").ValueStr()
  2424. var mapResult map[string]interface{}
  2425. err1 := json.Unmarshal([]byte(content), &mapResult)
  2426. if err1 != nil {
  2427. fmt.Println("JsonToMapDemo err: ", err1)
  2428. }
  2429. sqlstr := "select "
  2430. groupstr := " GROUP BY "
  2431. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2432. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2433. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2434. }
  2435. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2436. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2437. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2438. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2439. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2440. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2441. sqlstr = sqlstr + tem + ","
  2442. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2443. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2444. sqlstr = sqlstr + tem + ","
  2445. } else {
  2446. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2447. sqlstr = sqlstr + tem + ","
  2448. }
  2449. }
  2450. if _, ok := mapResult["selectedCalcul2"]; ok {
  2451. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2452. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2453. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2454. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2455. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2456. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2457. sqlstr = sqlstr + tem + ","
  2458. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2459. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2460. sqlstr = sqlstr + tem + ","
  2461. } else {
  2462. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2463. sqlstr = sqlstr + tem + ","
  2464. }
  2465. }
  2466. }
  2467. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2468. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2469. sqlstr = sqlstr + " where pastureid=" + pastureid
  2470. if len(mapResult["filters"].([]interface{})) > 0 {
  2471. sqlstr = sqlstr + " and "
  2472. }
  2473. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2474. for _, value := range mapResult["filters"].([]interface{}) {
  2475. switch value.(map[string]interface{})["filterOperator"].(string) {
  2476. case ">", "=", "<", ">=", "<=", "!=", "like":
  2477. 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 "
  2478. case "IN":
  2479. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2480. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2481. sqlstr = sqlstr + value1.(string) + ","
  2482. }
  2483. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2484. sqlstr = sqlstr + ")" + " AND "
  2485. case "BETWEEN":
  2486. 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 "
  2487. }
  2488. }
  2489. if len(mapResult["filters"].([]interface{})) > 0 {
  2490. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2491. }
  2492. //
  2493. groupstr = groupstr[0 : len(groupstr)-1]
  2494. sqlstr = sqlstr + groupstr + " "
  2495. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2496. sqlstr = sqlstr + " order by "
  2497. }
  2498. //
  2499. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2500. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2501. sqlstr = sqlstr + value.(string) + " "
  2502. } else {
  2503. sqlstr = sqlstr + value.(string) + ","
  2504. }
  2505. }
  2506. //
  2507. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2508. tx := restful.Engine.NewSession()
  2509. err := tx.Begin()
  2510. defer func() {
  2511. switch {
  2512. case err != nil:
  2513. logging.Error("tx.Begin 事务启动失败__error:", err)
  2514. if tx != nil {
  2515. tx.Rollback()
  2516. }
  2517. default:
  2518. if tx != nil {
  2519. err = tx.Commit()
  2520. }
  2521. }
  2522. if tx != nil {
  2523. tx.Close()
  2524. }
  2525. }()
  2526. exec, err := tx.SQL(sqlstr).Query().List()
  2527. if err != nil {
  2528. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2529. } else {
  2530. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2531. }
  2532. }
  2533. func Dashboards(c *gin.Context) {
  2534. appG := app.Gin{C: c}
  2535. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2536. fsion := gofasion.NewFasion(string(dataByte))
  2537. sqlnamestr := fsion.Get("name").ValueStr()
  2538. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2539. offset := fsion.Get("offset").ValueDefaultInt(0)
  2540. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2541. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2542. month := fsion.Get("month").ValueDefaultStr("map")
  2543. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2544. tx := restful.Engine.NewSession()
  2545. err := tx.Begin()
  2546. defer func() {
  2547. switch {
  2548. case err != nil:
  2549. if tx != nil {
  2550. tx.Rollback()
  2551. }
  2552. default:
  2553. if tx != nil {
  2554. err = tx.Commit()
  2555. }
  2556. }
  2557. if tx != nil {
  2558. tx.Close()
  2559. }
  2560. }()
  2561. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2562. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2563. if sql != "" {
  2564. s_params := make([]interface{}, 0)
  2565. if fsion.HasKey("parammaps") {
  2566. parammaps := fsion.Get("parammaps")
  2567. paramslist := strings.Split(p, ",")
  2568. if len(paramslist) > 0 && p != "" {
  2569. for _, value := range paramslist {
  2570. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2571. if tempv, exists := c.Get("jwt_username"); exists {
  2572. s_params = append(s_params, tempv.(string))
  2573. } else {
  2574. s_params = append(s_params, "")
  2575. }
  2576. } else {
  2577. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2578. }
  2579. }
  2580. }
  2581. }
  2582. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2583. if err != nil {
  2584. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2585. } else {
  2586. //paramslist1 := strings.Split(p1, ",")
  2587. dids := make([]interface{}, 0)
  2588. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2589. var mapResult map[string]interface{}
  2590. dids = append(dids, value["dashboard_id"])
  2591. if value["content"] != nil {
  2592. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2593. if err1 != nil {
  2594. println("JsonToMapDemo1 err: ", err1)
  2595. }
  2596. temap := make(map[string]interface{})
  2597. tem := mapResult["layout"].([]interface{})
  2598. if v, ok := value["chartids"]; ok {
  2599. chartids := strings.Split(v.(string), ",")
  2600. for _, va := range chartids {
  2601. a := false
  2602. for _, v2 := range tem {
  2603. if v2.(map[string]interface{})["id"].(string) == va {
  2604. a = true
  2605. //println("va1======",va)
  2606. }
  2607. }
  2608. if !a {
  2609. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2610. va + "\",\"id\":\"" + va +
  2611. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2612. var mapTem map[string]interface{}
  2613. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2614. if err1 != nil {
  2615. println("JsonToMapDemo err: ", err1)
  2616. }
  2617. tem = append(tem, mapTem)
  2618. }
  2619. }
  2620. temap["layout"] = tem
  2621. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2622. }
  2623. } else {
  2624. temap := make(map[string]interface{})
  2625. tem := make([]interface{}, 0)
  2626. if v, ok := value["chartids"]; ok {
  2627. chartids := strings.Split(v.(string), ",")
  2628. for _, va := range chartids {
  2629. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2630. va + "\",\"id\":\"" + va +
  2631. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2632. var mapTem map[string]interface{}
  2633. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2634. if err1 != nil {
  2635. println("JsonToMapDemo err: ", err1)
  2636. }
  2637. tem = append(tem, mapTem)
  2638. }
  2639. temap["layout"] = tem
  2640. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2641. }
  2642. }
  2643. }
  2644. queryData.(map[string]interface{})["order"] = dids
  2645. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2646. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2647. }
  2648. } else {
  2649. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2650. }
  2651. }
  2652. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2653. fsion := gofasion.NewFasion(parammaps)
  2654. sqlnamestr := fsion.Get("name").ValueStr()
  2655. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2656. offset := fsion.Get("offset").ValueDefaultInt(0)
  2657. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2658. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2659. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2660. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2661. body := []byte("")
  2662. if sql != "" {
  2663. s_params := make([]interface{}, 0)
  2664. if fsion.HasKey("parammaps") {
  2665. parammaps := fsion.Get("parammaps")
  2666. paramslist := strings.Split(p, ",")
  2667. if len(paramslist) > 0 && p != "" {
  2668. for _, value := range paramslist {
  2669. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2670. }
  2671. }
  2672. }
  2673. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2674. if err != nil {
  2675. } else {
  2676. paramslist1 := strings.Split(p1, ",")
  2677. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2678. s_params1 := make([]interface{}, 0)
  2679. if len(paramslist1) > 0 && p1 != "" {
  2680. for _, v := range paramslist1 {
  2681. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2682. }
  2683. }
  2684. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2685. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2686. body, _ = json.Marshal(queryData)
  2687. }
  2688. }
  2689. }
  2690. bs := bytes.NewBuffer(body)
  2691. client := &http.Client{}
  2692. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2693. req, err := http.NewRequest(RequestMethod,
  2694. url,
  2695. bs,
  2696. )
  2697. if err != nil {
  2698. }
  2699. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2700. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2701. if err != nil {
  2702. // handle error
  2703. }
  2704. resp, err := client.Do(req)
  2705. if err != nil {
  2706. return ""
  2707. }
  2708. defer resp.Body.Close()
  2709. result_body, err := ioutil.ReadAll(resp.Body)
  2710. if err != nil {
  2711. return ""
  2712. }
  2713. fmt.Println(string(result_body))
  2714. return ""
  2715. }
  2716. func GetSummary(c *gin.Context) {
  2717. appG := app.Gin{C: c}
  2718. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2719. fsion := gofasion.NewFasion(string(dataByte))
  2720. offset := fsion.Get("offset").ValueDefaultInt(0)
  2721. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2722. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2723. parammaps := fsion.Get("parammaps")
  2724. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2725. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2726. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2727. tx := restful.Engine.NewSession()
  2728. defer tx.Close()
  2729. sqlnamestr := ""
  2730. if genre == "0" {
  2731. if status == "0" {
  2732. sqlnamestr = "getAccuracyJSY"
  2733. } else if status == "1" {
  2734. sqlnamestr = "getAccuracyHFT"
  2735. } else if status == "2" {
  2736. sqlnamestr = "getAccuracyHNS"
  2737. } else if status == "3" {
  2738. sqlnamestr = "getAccuracyHSC"
  2739. } else if status == "4" {
  2740. sqlnamestr = "getAccuracyHCC"
  2741. } else if status == "5" {
  2742. sqlnamestr = "getAccuracyMC"
  2743. } else if status == "6" {
  2744. sqlnamestr = "getAccuracyFeedHL"
  2745. } else if status == "7" {
  2746. sqlnamestr = "getAccuracyRT"
  2747. }
  2748. } else {
  2749. if status == "0" {
  2750. sqlnamestr = "getAccuracySCCJSY"
  2751. } else if status == "1" {
  2752. sqlnamestr = "getAccuracySFT"
  2753. } else if status == "2" {
  2754. sqlnamestr = "getAccuracySNS"
  2755. } else if status == "3" {
  2756. sqlnamestr = "getAccuracySSC"
  2757. } else if status == "4" {
  2758. sqlnamestr = "getAccuracySCC"
  2759. } else if status == "5" {
  2760. sqlnamestr = "getAccuracySLCL"
  2761. } else if status == "7" {
  2762. sqlnamestr = "getAccuracySCCRT"
  2763. }
  2764. }
  2765. if isDate == "1" {
  2766. sqlnamestr += "Date"
  2767. }
  2768. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2769. // fmt.Println(sqlnamestr, sql)
  2770. if sql != "" {
  2771. s_params := make([]interface{}, 0)
  2772. // if fsion.HasKey("parammaps") {
  2773. fmt.Println(s_params, "222", p)
  2774. paramslist := strings.Split(p, ",")
  2775. if len(paramslist) > 0 && p != "" {
  2776. for _, value := range paramslist {
  2777. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2778. if tempv, exists := c.Get("jwt_username"); exists {
  2779. s_params = append(s_params, tempv.(string))
  2780. } else {
  2781. s_params = append(s_params, "")
  2782. }
  2783. } else {
  2784. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2785. }
  2786. }
  2787. }
  2788. if returntype == "xlsx" {
  2789. var xlsxfile *xlsx.File
  2790. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2791. //c.File("c:/dd.xlsx")
  2792. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2793. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2794. c.Header("Content-Transfer-Encoding", "binary")
  2795. _ = xlsxfile.Write(c.Writer)
  2796. } else {
  2797. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2798. if err != nil {
  2799. logging.Error("GetDataByName err: ", err)
  2800. msg := geterrmsg(err.Error())
  2801. appG.Response(http.StatusOK, e.ERROR, msg)
  2802. } else {
  2803. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2804. }
  2805. }
  2806. } else {
  2807. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2808. }
  2809. }
  2810. // type lpplanStruct struct {
  2811. // Id int64 `xorm:"id"`
  2812. // Tmrname string `xorm:"tmrname"`
  2813. // Tmrid int64 `xorm:"tmrid"`
  2814. // Sort int64 `xorm:"sort"`
  2815. // Sel int64 `xorm:"sel"`
  2816. // Times int64 `xorm:"times"`
  2817. // Ftname string `xorm:"ftname"`
  2818. // Ftid int64 `xorm:"ftid"`
  2819. // Maxweight float64 `xorm:"maxweight"`
  2820. // Sumweight float64 `xorm:"sumweight"`
  2821. // Sumcowcount int64 `xorm:"sumcowcount"`
  2822. // Pastureid string `xorm:"pastureid"`
  2823. // Display string `xorm:"display"`
  2824. // Issplit int64 `xorm:"issplit"`
  2825. // BeginTime string `xorm:"begintime"`
  2826. // }
  2827. func UpdateFTdetail(c *gin.Context) {
  2828. appG := app.Gin{C: c}
  2829. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2830. tempval_ := make(map[string]interface{})
  2831. tempCommon := make(map[string]interface{})
  2832. tempval := make([]map[string]interface{}, 0)
  2833. fTChange := make(map[string]interface{}, 0)
  2834. // fpdOldDataList := make([]map[string]interface{}, 0)
  2835. // fpdDataList := make([]map[string]interface{}, 0)
  2836. fsion := gofasion.NewFasion(string(dataByte))
  2837. // parammaps := fsion.Get("parammaps")
  2838. createdate := time.Now().Format("2006-01-02 15:04:05")
  2839. err := json.Unmarshal(dataByte, &tempval_)
  2840. if err != nil {
  2841. appG.Response(http.StatusOK, e.ERROR, false)
  2842. return
  2843. }
  2844. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2845. tx := restful.Engine.NewSession()
  2846. if v, ok := tempval_["data"].([]interface{}); ok {
  2847. for _, Tvalue := range v {
  2848. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2849. if v1["name"] == "updateFPbyFTChange" {
  2850. fTChange = v1
  2851. continue
  2852. }
  2853. tempval = append(tempval, v1)
  2854. }
  2855. }
  2856. }
  2857. parammaps := fTChange["parammaps"].(map[string]interface{})
  2858. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2859. // if err != nil {
  2860. // logs.Error(err)
  2861. // appG.Response(http.StatusOK, e.ERROR, false)
  2862. // return
  2863. // }
  2864. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2865. // if err != nil {
  2866. // logs.Error(err)
  2867. // appG.Response(http.StatusOK, e.ERROR, false)
  2868. // return
  2869. // }
  2870. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2871. // if err != nil {
  2872. // logs.Error(err)
  2873. // appG.Response(http.StatusOK, e.ERROR, false)
  2874. // return
  2875. // }
  2876. err = tx.Begin()
  2877. if err != nil {
  2878. logging.Error("tx.Begin 事务启动失败__error:", err)
  2879. }
  2880. defer func() {
  2881. if err != nil {
  2882. if tx != nil {
  2883. tx.Rollback()
  2884. }
  2885. }
  2886. if tx != nil {
  2887. tx.Close()
  2888. }
  2889. }()
  2890. if err != nil {
  2891. } else {
  2892. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2893. tempCommon = v
  2894. }
  2895. // 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 ,
  2896. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2897. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2898. // UNION
  2899. // 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 ,
  2900. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2901. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2902. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2903. if err == nil {
  2904. if tempv, exists := c.Get("jwt_username"); exists {
  2905. tempCommon["jwt_username"] = tempv.(string)
  2906. }
  2907. for _, paramvalue := range tempval {
  2908. if _, ok := paramvalue["resultname"]; !ok {
  2909. paramvalue["resultname"] = paramvalue["name"]
  2910. }
  2911. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2912. if err != nil {
  2913. logging.Error("ExecDataParam error:", err)
  2914. break
  2915. }
  2916. }
  2917. if err != nil {
  2918. msg := geterrmsg(err.Error())
  2919. appG.Response(http.StatusOK, e.ERROR, msg)
  2920. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2921. }
  2922. }
  2923. }
  2924. tx.Commit()
  2925. // go func() {
  2926. if fTChange != nil {
  2927. parammaps := fTChange["parammaps"].(map[string]interface{})
  2928. if parammaps["type"].(float64) == 1 {
  2929. _, err = tx.SQL(`UPDATE feedp fp
  2930. set
  2931. ccountratio = ccount *(ratio /100 ),
  2932. fp.ftweight= IFNULL(IF(
  2933. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2934. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2935. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2936. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2937. ),0),fp.feedweight = IFNULL(IF(
  2938. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2939. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2940. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2941. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2942. ),0) +ifnull(fp.supplyweight,0)
  2943. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2944. _, err = tx.SQL(`UPDATE fpdetail fpd
  2945. INNER JOIN feedp fp
  2946. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2947. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2948. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2949. } else {
  2950. _, err = tx.SQL(`UPDATE feedp fp
  2951. SET ccountratio = ccount *(ratio /100 ),
  2952. fp.supplyweight= IFNULL(IF(
  2953. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2954. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2955. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2956. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2957. ),0),fp.feedweight = IFNULL(IF(
  2958. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2959. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2960. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2961. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2962. ),0) +ifnull(fp.supplyweight,0)
  2963. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2964. _, err = tx.SQL(`UPDATE fpdetail fpd
  2965. INNER JOIN feedp fp
  2966. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2967. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2968. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2969. }
  2970. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  2971. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  2972. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  2973. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  2974. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  2975. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  2976. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  2977. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  2978. join feedtemplet ft on ft.id = fp.ftid where ft.id = ?`, parammaps["ftid"]).QueryString()
  2979. // fmt.Println(ftId)
  2980. FpdBatchEditGrfd(fmt.Sprintf("%v", parammaps["pastureid"]), values1)
  2981. // 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 ,
  2982. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2983. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2984. // UNION
  2985. // 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 ,
  2986. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2987. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2988. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2989. // lpplanList := make([]*lpplanStruct, 0)
  2990. // err = tx.SQL(`select id,times,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpplan.pastureid ) = 0 ,
  2991. // ifnull((select maxstirfeed from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),100000),(select ifnull(volume,0) from tmr where id = lpplan.tmrid ) *
  2992. // (select ifnull(volume,0) from feedtemplet where id = lpplan.ftid) ) maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2993. // if err != nil {
  2994. // logs.Error(err, 1)
  2995. // return
  2996. // }
  2997. // lppidlist := []string{}
  2998. // for _, lpp := range lpplanList {
  2999. // lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  3000. // }
  3001. // if len(lppidlist) <= 0 {
  3002. // appG.Response(http.StatusOK, e.SUCCESS, true)
  3003. // return
  3004. // }
  3005. // lpplandtl1AllList := make([]*lpplandtl1, 0)
  3006. // err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  3007. // order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  3008. // if err != nil {
  3009. // // tx.Rollback()
  3010. // logs.Error(err, 2, parammaps["pastureid"])
  3011. // return
  3012. // }
  3013. // for _, lpp := range lpplandtl1AllList {
  3014. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  3015. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  3016. // if err != nil {
  3017. // logs.Error(err)
  3018. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3019. // return
  3020. // }
  3021. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3022. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  3023. // if err != nil {
  3024. // logs.Error(err)
  3025. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3026. // return
  3027. // }
  3028. // }
  3029. // var wg sync.WaitGroup
  3030. // for _, old := range fpdOldDataList {
  3031. // for _, fpd := range fpdDataList {
  3032. // wg.Add(1)
  3033. // go func(old, fpd map[string]interface{}) {
  3034. // updateLppandList := make([]*lpplandtl1, 0)
  3035. // defer wg.Done()
  3036. // if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3037. // fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3038. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3039. // oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3040. // // if weight > oldweight {
  3041. // // return
  3042. // // }
  3043. // var w float64
  3044. // var status int
  3045. // if weight < oldweight {
  3046. // if weight >= 0 {
  3047. // return
  3048. // }
  3049. // w = weight
  3050. // status = 0
  3051. // } else {
  3052. // if oldweight > 0 {
  3053. // return
  3054. // }
  3055. // w = weight
  3056. // status = 1
  3057. // }
  3058. // // fweight = w
  3059. // for _, lpp := range lpplanList {
  3060. // var fweight float64
  3061. // var lweight float64
  3062. // lpplandtl1List := make([]*lpplandtl1, 0)
  3063. // fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3064. // for _, lppland := range lpplandtl1AllList {
  3065. // if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3066. // lpplandtl1List = append(lpplandtl1List, lppland)
  3067. // }
  3068. // }
  3069. // if len(lpplandtl1List) == 0 {
  3070. // continue
  3071. // }
  3072. // for _, lppland := range lpplandtl1List {
  3073. // lweight += lppland.Lweight
  3074. // }
  3075. // if status == 0 {
  3076. // if lweight <= 0 {
  3077. // continue
  3078. // }
  3079. // } else {
  3080. // if lpp.Maxweight <= lweight {
  3081. // continue
  3082. // }
  3083. // }
  3084. // for _, lppland := range lpplandtl1List {
  3085. // if fpdid == lppland.Fpdid {
  3086. // if status == 1 {
  3087. // // if w <= lppland.Lweight {
  3088. // if lpp.Maxweight <= lweight {
  3089. // continue
  3090. // }
  3091. // if w+lweight <= lpp.Maxweight {
  3092. // lppland.Lweight += w
  3093. // lweight += w
  3094. // fweight += w
  3095. // w = 0
  3096. // } else {
  3097. // w = w - (lpp.Maxweight - lweight)
  3098. // n := (lpp.Maxweight - lweight)
  3099. // lppland.Lweight = lppland.Lweight + n
  3100. // lweight += n
  3101. // fweight += n
  3102. // }
  3103. // } else {
  3104. // if lppland.Lweight == 0 {
  3105. // continue
  3106. // }
  3107. // if w+lppland.Lweight >= 0 {
  3108. // lppland.Lweight = lppland.Lweight + w
  3109. // lweight = lweight + w
  3110. // fweight = fweight + w
  3111. // w = 0
  3112. // } else {
  3113. // w = w + lppland.Lweight
  3114. // lweight = lweight - lppland.Lweight
  3115. // fweight = fweight - lppland.Lweight
  3116. // lppland.Lweight = 0
  3117. // }
  3118. // }
  3119. // updateLppandList = append(updateLppandList, lppland)
  3120. // break
  3121. // }
  3122. // }
  3123. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3124. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3125. // WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3126. // if err != nil {
  3127. // // tx.Rollback()
  3128. // logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3129. // return
  3130. // }
  3131. // for _, lppland := range updateLppandList {
  3132. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3133. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3134. // if err != nil {
  3135. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3136. // // tx.Rollback()
  3137. // logs.Error(err, 3)
  3138. // return
  3139. // }
  3140. // // defer wg.Done()
  3141. // }
  3142. // updateLppandList = []*lpplandtl1{}
  3143. // if w == 0 {
  3144. // break
  3145. // }
  3146. // }
  3147. // }
  3148. // }(old, fpd)
  3149. // }
  3150. // }
  3151. // wg.Wait()
  3152. }
  3153. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3154. if err != nil {
  3155. logs.Error(err)
  3156. appG.Response(http.StatusOK, e.ERROR, false)
  3157. return
  3158. }
  3159. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3160. if err != nil {
  3161. logs.Error(err)
  3162. appG.Response(http.StatusOK, e.ERROR, false)
  3163. return
  3164. }
  3165. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3166. if err != nil {
  3167. logs.Error(err)
  3168. appG.Response(http.StatusOK, e.ERROR, false)
  3169. return
  3170. }
  3171. now := createdate
  3172. // for _, oldFpd := range oldFpdDataList {
  3173. for _, newFpd := range newFpdDataList {
  3174. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3175. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3176. // go func() {
  3177. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3178. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3179. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3180. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3181. if err != nil {
  3182. logs.Error(err)
  3183. appG.Response(http.StatusOK, e.ERROR, false)
  3184. return
  3185. }
  3186. // }()
  3187. }
  3188. // break
  3189. // }
  3190. // }
  3191. // }
  3192. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3193. for _, newLpplandtl1 := range newLpplandtl1List {
  3194. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3195. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3196. // go func() {
  3197. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3198. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3199. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3200. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3201. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3202. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3203. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3204. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3205. if err != nil {
  3206. logs.Error(err)
  3207. appG.Response(http.StatusOK, e.ERROR, false)
  3208. return
  3209. }
  3210. // }()
  3211. // }
  3212. // break
  3213. // }
  3214. // }
  3215. }
  3216. // for _, oldFeedp := range oldFeedpList {
  3217. for _, newFeedp := range newFeedpList {
  3218. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3219. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3220. // go func() {
  3221. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3222. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3223. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3224. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3225. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3226. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3227. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3228. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3229. if err != nil {
  3230. logs.Error(err)
  3231. appG.Response(http.StatusOK, e.ERROR, false)
  3232. return
  3233. }
  3234. }
  3235. // ,,parammaps["ftid"])
  3236. // surplus, surplusId, id, pastureId string
  3237. // FtdetailSurplusFt(parammaps["ftid"].)
  3238. ftList1, err := tx.SQL(` SELECT
  3239. f.id,
  3240. f.surplus surplusId,
  3241. f.pastureid,
  3242. s.surplus
  3243. FROM
  3244. feedtemplet f
  3245. JOIN surplus s ON s.id = f.surplus
  3246. WHERE
  3247. f.id = ?`, parammaps["ftid"]).QueryString()
  3248. for _, ft := range ftList1 {
  3249. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3250. }
  3251. appG.Response(http.StatusOK, e.SUCCESS, true)
  3252. }
  3253. type lpplandtlInfo struct {
  3254. Id int64 `xorm:"id"`
  3255. Pastureid int64 `xorm:"pastureid"`
  3256. Lppid int64 `xorm:"lppid"`
  3257. Barid int64 `xorm:"barid"`
  3258. Barname string `xorm:"barname"`
  3259. Fpdid int64 `xorm:"fpdid"`
  3260. Fttype int64 `xorm:"fttype"`
  3261. Lweight float64 `xorm:"lweight"`
  3262. Sort int64 `xorm:"sort"`
  3263. Tmrid int64 `xorm:"tmrid"`
  3264. Tmrname string `xorm:"tmrname"`
  3265. Cowcount int64 `xorm:"cowcount"`
  3266. Ccountradio float64 `xorm:"ccountradio"`
  3267. Background string `xorm:"background"`
  3268. Lweighthis float64 `xorm:"lweighthis"`
  3269. Maxweight float64 `xorm:"maxweight"`
  3270. }
  3271. func UpdateFpdetailBar(c *gin.Context) {
  3272. appG := app.Gin{C: c}
  3273. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3274. fsion := gofasion.NewFasion(string(dataByte))
  3275. pastureid := fsion.Get("pastureid").ValueStr()
  3276. id := fsion.Get("id").ValueStr()
  3277. tx := restful.Engine.NewSession()
  3278. tx.Begin()
  3279. 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 `,
  3280. pastureid, id).Query().List()
  3281. if err != nil {
  3282. logs.Error(err)
  3283. }
  3284. for _, fpd := range fpdList {
  3285. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3286. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3287. pastureid, fpd["id"]).Query().List()
  3288. if err != nil {
  3289. tx.Rollback()
  3290. logs.Error(err)
  3291. appG.Response(http.StatusOK, e.ERROR, false)
  3292. return
  3293. }
  3294. var lweight float64
  3295. for _, lppland := range lpplandList {
  3296. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3297. lweight += lweight1
  3298. }
  3299. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3300. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3301. if fpdweight >= ptuse && lweight == ptuse {
  3302. continue
  3303. } else {
  3304. if lweight <= fpdweight {
  3305. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3306. if err != nil {
  3307. tx.Rollback()
  3308. logs.Error(err)
  3309. appG.Response(http.StatusOK, e.ERROR, false)
  3310. return
  3311. }
  3312. } else {
  3313. weight := fpdweight - lweight
  3314. for _, lppland := range lpplandList {
  3315. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3316. if weight >= lpplandlweight {
  3317. weight = weight - lpplandlweight
  3318. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3319. if err != nil {
  3320. tx.Rollback()
  3321. logs.Error(err)
  3322. appG.Response(http.StatusOK, e.ERROR, false)
  3323. return
  3324. }
  3325. } else {
  3326. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3327. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3328. // if err != nil {
  3329. // tx.Rollback()
  3330. // logs.Error(err)
  3331. // appG.Response(http.StatusOK, e.ERROR, false)
  3332. // return
  3333. // }
  3334. weight = 0
  3335. break
  3336. }
  3337. }
  3338. }
  3339. }
  3340. }
  3341. fsionData := fsion.Get("data").Array()
  3342. for _, list := range fsionData {
  3343. ftmap := make(map[string]interface{})
  3344. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3345. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3346. ftmap["times"] = list.Get("times").ValueInt64()
  3347. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3348. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3349. // fmt.Println(ftmap)
  3350. // /*
  3351. count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3352. and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3353. if count == 1 {
  3354. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3355. and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3356. if err != nil {
  3357. tx.Rollback()
  3358. logs.Error(err)
  3359. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3360. return
  3361. }
  3362. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3363. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3364. if err != nil {
  3365. tx.Rollback()
  3366. logs.Error(err)
  3367. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3368. return
  3369. }
  3370. }
  3371. // */
  3372. fpdDataList, err := tx.SQL(`
  3373. 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 ,
  3374. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3375. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3376. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3377. if err != nil {
  3378. tx.Rollback()
  3379. logs.Error(err)
  3380. }
  3381. for _, fpd := range fpdDataList {
  3382. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3383. fttype := -1
  3384. if fpd["fttype"].(string) == "1" {
  3385. fttype = 1
  3386. }
  3387. var fweight float64
  3388. var lweight float64
  3389. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3390. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  3391. t.maxstirfeed,(select ifnull(volume,0) from tmr where id = lpp.tmrid ) *
  3392. (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  3393. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3394. join tmr t on t.id = lpp.tmrid
  3395. where lppland.fpdid =?
  3396. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3397. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3398. if err != nil {
  3399. tx.Rollback()
  3400. logs.Error(err)
  3401. }
  3402. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3403. var w float64
  3404. var status int
  3405. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3406. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3407. if weight >= 0 {
  3408. continue
  3409. }
  3410. w = weight
  3411. status = 0
  3412. } else {
  3413. // continue
  3414. if weight <= 0 {
  3415. continue
  3416. }
  3417. w = weight
  3418. status = 1
  3419. }
  3420. // for _, lppland := range lpplandtl1List {
  3421. // lweight += lppland.Lweight
  3422. // }
  3423. for _, lppland := range lpplandtl1List {
  3424. lpplandInfo := new(lpplandtlInfo)
  3425. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3426. lweight = lpplandInfo.Lweight
  3427. if status == 1 {
  3428. // if w <= lppland.Lweight {
  3429. if lppland.Maxweight <= lweight {
  3430. continue
  3431. }
  3432. if w+lweight <= lppland.Maxweight {
  3433. lppland.Lweight += w
  3434. lweight += w
  3435. fweight += w
  3436. w = 0
  3437. } else {
  3438. w = w - (lppland.Maxweight - lweight)
  3439. n := (lppland.Maxweight - lweight)
  3440. lppland.Lweight = lppland.Lweight + n
  3441. lweight += n
  3442. fweight += n
  3443. }
  3444. } else {
  3445. if lppland.Lweight == 0 {
  3446. continue
  3447. }
  3448. if w+lppland.Lweight >= 0 {
  3449. lppland.Lweight = lppland.Lweight + w
  3450. lweight = lweight + w
  3451. fweight = fweight + w
  3452. w = 0
  3453. } else {
  3454. w = w + lppland.Lweight
  3455. lweight = lweight - lppland.Lweight
  3456. fweight = fweight - lppland.Lweight
  3457. lppland.Lweight = 0
  3458. }
  3459. }
  3460. if lppland.Lweight > 0 {
  3461. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3462. if err != nil {
  3463. tx.Rollback()
  3464. logs.Error(err)
  3465. return
  3466. }
  3467. } else {
  3468. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3469. if err != nil {
  3470. tx.Rollback()
  3471. logs.Error(err)
  3472. return
  3473. }
  3474. }
  3475. if w == 0 {
  3476. break
  3477. }
  3478. // break
  3479. }
  3480. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3481. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3482. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3483. if err != nil {
  3484. tx.Rollback()
  3485. logs.Error(err)
  3486. }
  3487. if w == 0 {
  3488. break
  3489. }
  3490. }
  3491. }
  3492. }
  3493. tx.Commit()
  3494. now := time.Now()
  3495. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3496. if err != nil {
  3497. logs.Error(err)
  3498. appG.Response(http.StatusOK, e.ERROR, false)
  3499. return
  3500. }
  3501. for _, newLpplandtl1 := range newLpplandtl1List {
  3502. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3503. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3504. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3505. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3506. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3507. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3508. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3509. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3510. if err != nil {
  3511. logs.Error(err)
  3512. appG.Response(http.StatusOK, e.ERROR, false)
  3513. return
  3514. }
  3515. }
  3516. appG.Response(http.StatusOK, e.SUCCESS, true)
  3517. }
  3518. func GetProcessAnalysis(c *gin.Context) {
  3519. appG := app.Gin{C: c}
  3520. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3521. fsion := gofasion.NewFasion(string(dataByte))
  3522. sqlnamestr := fsion.Get("name").ValueStr()
  3523. offset := fsion.Get("offset").ValueDefaultInt(0)
  3524. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3525. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3526. parammaps := fsion.Get("parammaps")
  3527. tx := restful.Engine.NewSession()
  3528. err := tx.Begin()
  3529. defer func() {
  3530. switch {
  3531. case err != nil:
  3532. logging.Error("tx.Begin 事务启动失败__error:", err)
  3533. if tx != nil {
  3534. tx.Rollback()
  3535. }
  3536. default:
  3537. if tx != nil {
  3538. err = tx.Commit()
  3539. }
  3540. }
  3541. if tx != nil {
  3542. tx.Close()
  3543. }
  3544. }()
  3545. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3546. s_params := make([]interface{}, 0)
  3547. paramslist := strings.Split(p, ",")
  3548. if len(paramslist) > 0 && p != "" {
  3549. for _, value := range paramslist {
  3550. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3551. if tempv, exists := c.Get("jwt_username"); exists {
  3552. s_params = append(s_params, tempv.(string))
  3553. } else {
  3554. s_params = append(s_params, "")
  3555. }
  3556. } else {
  3557. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3558. }
  3559. }
  3560. }
  3561. tmrtnameStr := ""
  3562. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3563. if len(tmrtnameStr) == 0 {
  3564. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3565. } else {
  3566. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3567. }
  3568. }
  3569. if len(tmrtnameStr) > 0 {
  3570. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3571. }
  3572. sql += " ORDER BY d.intime"
  3573. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3574. if err != nil {
  3575. logging.Error("GetDataByName err: ", err)
  3576. msg := geterrmsg(err.Error())
  3577. appG.Response(http.StatusOK, e.ERROR, msg)
  3578. } else {
  3579. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3580. }
  3581. }
  3582. func UpdateFeedtempletStatus(c *gin.Context) {
  3583. appG := app.Gin{C: c}
  3584. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3585. fsion := gofasion.NewFasion(string(dataByte))
  3586. parammaps := fsion.Get("parammaps")
  3587. tx := restful.Engine.NewSession()
  3588. tx.Begin()
  3589. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3590. if err != nil {
  3591. tx.Rollback()
  3592. logs.Error(err)
  3593. appG.Response(http.StatusOK, e.ERROR, err)
  3594. return
  3595. }
  3596. tx.Commit()
  3597. appG.Response(http.StatusOK, e.SUCCESS, true)
  3598. }
  3599. func AddFtdry(c *gin.Context) {
  3600. appG := app.Gin{C: c}
  3601. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3602. fsion := gofasion.NewFasion(string(dataByte))
  3603. sqlnamestr := fsion.Get("name").ValueStr()
  3604. s_params := make([]interface{}, 0)
  3605. tx := restful.Engine.NewSession()
  3606. err := tx.Begin()
  3607. defer func() {
  3608. switch {
  3609. case err != nil:
  3610. if tx != nil {
  3611. tx.Rollback()
  3612. }
  3613. default:
  3614. if tx != nil {
  3615. err = tx.Commit()
  3616. }
  3617. }
  3618. if tx != nil {
  3619. tx.Close()
  3620. }
  3621. }()
  3622. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3623. if sql != "" {
  3624. parammaps := fsion.Get("parammaps")
  3625. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3626. paramslist := strings.Split(p, ",")
  3627. if len(paramslist) > 0 && p != "" {
  3628. for _, value := range paramslist {
  3629. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3630. if tempv, exists := c.Get("jwt_username"); exists {
  3631. s_params = append(s_params, tempv.(string))
  3632. } else {
  3633. s_params = append(s_params, "")
  3634. }
  3635. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3636. ids, err := setting.SnowIds.NextId()
  3637. if err != nil {
  3638. ids = time.Now().UnixNano()
  3639. logging.Info("create SnowIds err", err)
  3640. }
  3641. s_params = append(s_params, ids)
  3642. } else {
  3643. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3644. }
  3645. }
  3646. }
  3647. var actweight float64
  3648. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3649. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3650. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3651. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3652. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3653. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3654. 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()
  3655. if err != nil {
  3656. logging.Error("AddFtdry err: ", err)
  3657. msg := geterrmsg(err.Error())
  3658. appG.Response(http.StatusOK, e.ERROR, msg)
  3659. }
  3660. if len(actweightList) > 0 {
  3661. for _, item := range actweightList {
  3662. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3663. if err != nil {
  3664. logging.Error("AddFtdry err: ", err)
  3665. msg := geterrmsg(err.Error())
  3666. appG.Response(http.StatusOK, e.ERROR, msg)
  3667. }
  3668. actweight = fl
  3669. }
  3670. } else {
  3671. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3672. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3673. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3674. if err != nil {
  3675. logging.Error("AddFtdry err: ", err)
  3676. msg := geterrmsg(err.Error())
  3677. appG.Response(http.StatusOK, e.ERROR, msg)
  3678. }
  3679. for _, item := range dryList {
  3680. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3681. if err != nil {
  3682. logging.Error("AddFtdry err: ", err)
  3683. msg := geterrmsg(err.Error())
  3684. appG.Response(http.StatusOK, e.ERROR, msg)
  3685. }
  3686. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3687. }
  3688. }
  3689. if sqlnamestr == "insertFtdry" {
  3690. s_params = append(s_params, actweight)
  3691. } else if sqlnamestr == "updateFtdry" {
  3692. sql = fmt.Sprintf(sql, actweight)
  3693. }
  3694. queryData, err := execDataBySqlT(sql, s_params, tx)
  3695. if err != nil {
  3696. logging.Error("AddFtdry err: ", err)
  3697. msg := geterrmsg(err.Error())
  3698. appG.Response(http.StatusOK, e.ERROR, msg)
  3699. } else {
  3700. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3701. }
  3702. } else {
  3703. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3704. }
  3705. }
  3706. func CheckDates(c *gin.Context) {
  3707. tx := restful.Engine.NewSession()
  3708. defer tx.Close()
  3709. appG := app.Gin{C: c}
  3710. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3711. tempval_ := make(map[string]interface{})
  3712. tempCommon := make(map[string]interface{})
  3713. tempval := make([]map[string]interface{}, 0)
  3714. err := json.Unmarshal(dataByte, &tempval_)
  3715. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3716. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3717. if err != nil {
  3718. } else {
  3719. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3720. tempCommon = v
  3721. }
  3722. if v, ok := tempval_["data"].([]interface{}); ok {
  3723. for _, Tvalue := range v {
  3724. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3725. tempval = append(tempval, v1)
  3726. }
  3727. }
  3728. }
  3729. if err == nil {
  3730. if tempv, exists := c.Get("jwt_username"); exists {
  3731. tempCommon["jwt_username"] = tempv.(string)
  3732. }
  3733. for _, paramvalue := range tempval {
  3734. if _, ok := paramvalue["resultname"]; !ok {
  3735. paramvalue["resultname"] = paramvalue["name"]
  3736. }
  3737. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3738. if err != nil {
  3739. logging.Error("ExecDataParam error:", err)
  3740. }
  3741. }
  3742. if err == nil {
  3743. vmsg := ""
  3744. for _, item := range tempval {
  3745. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3746. for _, childrenList := range list.([]interface{}) {
  3747. for k, children := range childrenList.(map[string]interface{}) {
  3748. if k != "children" {
  3749. continue
  3750. }
  3751. for _, v := range children.([]map[string]interface{}) {
  3752. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3753. if k1 == "list" {
  3754. for _, v2 := range v1.([]map[string]interface{}) {
  3755. if v2["vmsg"].(string) != "1" {
  3756. if len(vmsg) == 0 {
  3757. vmsg = v2["vmsg"].(string)
  3758. } else {
  3759. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3760. }
  3761. }
  3762. }
  3763. }
  3764. }
  3765. }
  3766. }
  3767. }
  3768. }
  3769. }
  3770. if len(vmsg) > 0 {
  3771. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3772. } else {
  3773. appG.Response(http.StatusOK, e.SUCCESS, true)
  3774. }
  3775. } else {
  3776. msg := geterrmsg(err.Error())
  3777. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3778. }
  3779. }
  3780. }
  3781. if err != nil {
  3782. msg := geterrmsg(err.Error())
  3783. appG.Response(http.StatusOK, e.ERROR, msg)
  3784. }
  3785. }
  3786. 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) {
  3787. sqlname := fasion["name"].(string)
  3788. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3789. if v, ok := fasion["type"]; ok {
  3790. sqltype = v.(string)
  3791. }
  3792. sql := ""
  3793. p := ""
  3794. s_params := make([]interface{}, 0)
  3795. if sqltype != "" {
  3796. sql, p = restful.GetSqlByName(sqlname, tx)
  3797. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3798. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3799. paramslist := strings.Split(p, ",")
  3800. if len(paramslist) > 0 && p != "" {
  3801. for _, value := range paramslist {
  3802. ss := ""
  3803. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3804. ids, err := setting.SnowIds.NextId()
  3805. if err != nil {
  3806. ids = time.Now().UnixNano()
  3807. logging.Info("create SnowIds err", err)
  3808. }
  3809. s_params = append(s_params, ids)
  3810. } else {
  3811. if ss == "" && CommonParamMap != nil {
  3812. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3813. ss = valuestring
  3814. tempstrb := strings.IndexAny(valuestring, "@")
  3815. tempstre := strings.IndexAny(valuestring, ".")
  3816. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3817. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3818. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3819. }
  3820. } else {
  3821. ss = ""
  3822. }
  3823. }
  3824. }
  3825. if ss == "" && ParentParamMap != nil {
  3826. ss = getParamValue_(v, value, ParentParamMap)
  3827. }
  3828. if ss == "" && sameParamMap != nil {
  3829. ss = getParamValue(v, value, sameParamMap)
  3830. }
  3831. if ss == "" && ParamMap != nil {
  3832. ss = getParamValue(v, value, ParamMap)
  3833. }
  3834. s_params = append(s_params, ss)
  3835. }
  3836. }
  3837. }
  3838. }
  3839. }
  3840. if sql == "" {
  3841. sqltype = ""
  3842. }
  3843. if sql != "" {
  3844. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3845. if err != nil {
  3846. return nil, err
  3847. }
  3848. // fmt.Println(tempValParam)
  3849. return tempValParam.(map[string]interface{}), nil
  3850. } else {
  3851. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3852. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3853. if err != nil {
  3854. return nil, err
  3855. }
  3856. return nil, err
  3857. }
  3858. }
  3859. return nil, nil
  3860. }
  3861. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3862. var err error
  3863. subarray, ok := fasion["children"]
  3864. if ok {
  3865. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3866. tempVal_arrary := make([]map[string]interface{}, 0)
  3867. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3868. tempVal_ := make(map[string]interface{})
  3869. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3870. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3871. } else {
  3872. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3873. }
  3874. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3875. if err != nil {
  3876. return err
  3877. }
  3878. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3879. }
  3880. v.(map[string]interface{})["children"] = tempVal_arrary
  3881. }
  3882. }
  3883. return nil
  3884. }
  3885. func FpdImportExcel(c *gin.Context) {
  3886. appG := app.Gin{C: c}
  3887. inputdata := ""
  3888. c.Request.ParseForm()
  3889. params := c.Request.Form
  3890. file, _, err := c.Request.FormFile("file")
  3891. if err != nil {
  3892. appG.Response(http.StatusOK, e.ERROR, err)
  3893. return
  3894. }
  3895. sqlnamestrs := params.Get("name")
  3896. sheetname := params.Get("sheetname")
  3897. pastureid := params.Get("pastureid")
  3898. // importParams := params.Get("importParams")
  3899. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3900. // 必输项参数 (字符串格式 "field1,field2,field3")
  3901. requiredParams := params.Get("requiredParams")
  3902. // 日期参数
  3903. dateParams := params.Get("dateParams")
  3904. // 数字参数
  3905. numParams := params.Get("numParams")
  3906. //将字符串分割开
  3907. dateParamslist := strings.Split(dateParams, ",")
  3908. requiredParamslist := strings.Split(requiredParams, ",")
  3909. numParamslist := strings.Split(numParams, ",")
  3910. queryData := make([]interface{}, 0)
  3911. sqlslist := strings.Split(sqlnamestrs, ",")
  3912. xlsx1, err := excelize.OpenReader(file)
  3913. if err != nil {
  3914. fmt.Println(err)
  3915. return
  3916. }
  3917. ok := 0
  3918. error := 0
  3919. isdone := true
  3920. tx := restful.Engine.NewSession()
  3921. defer tx.Close()
  3922. languageStatus := GetLanguageStatus()
  3923. if languageStatus == "0" {
  3924. 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
  3925. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3926. if err != nil {
  3927. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3928. return
  3929. }
  3930. rows := xlsx1.GetRows(sheetname)
  3931. // 限制10000条,多余的截取掉
  3932. if len(rows) > 10000 {
  3933. rows = rows[:10000]
  3934. }
  3935. dataList := make(map[string][]*upFpdetail, 0)
  3936. for i, row := range rows {
  3937. if i > 0 {
  3938. entry := make(map[string]interface{})
  3939. outentry := make(map[string]interface{})
  3940. for j, colCell := range rows[0] {
  3941. for k, colCell1 := range row {
  3942. if j == k {
  3943. outentry[colCell] = colCell1
  3944. entry[colCell] = colCell1
  3945. }
  3946. }
  3947. }
  3948. inputdata = ""
  3949. a := ""
  3950. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3951. //校验日期格式
  3952. for _, v := range dateParamslist {
  3953. if v == "" {
  3954. continue
  3955. }
  3956. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3957. dtime, err := TransfTime(d.(string))
  3958. if err != nil {
  3959. a = strings.Trim(v, " ")
  3960. break
  3961. }
  3962. outentry[strings.Trim(v, " ")] = dtime
  3963. }
  3964. }
  3965. if a != "" {
  3966. outentry["error_msg"] = a + " 格式错误"
  3967. error++
  3968. queryData = append(queryData, outentry)
  3969. continue
  3970. }
  3971. a = ""
  3972. //校验必填格式
  3973. for _, v := range requiredParamslist {
  3974. if v == "" {
  3975. continue
  3976. }
  3977. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3978. a = strings.Trim(v, " ")
  3979. break
  3980. }
  3981. }
  3982. if a != "" {
  3983. outentry["error_msg"] = a + " 未填或格式错误"
  3984. error++
  3985. queryData = append(queryData, outentry)
  3986. continue
  3987. }
  3988. a = ""
  3989. //校验数字格式
  3990. for _, v := range numParamslist {
  3991. if v == "" {
  3992. continue
  3993. }
  3994. d, ok := outentry[strings.Trim(v, " ")]
  3995. if !ok || d == "" {
  3996. outentry[strings.Trim(v, " ")] = 0
  3997. } else {
  3998. var fl float64
  3999. switch d.(type) {
  4000. case string:
  4001. fl, err = strconv.ParseFloat(d.(string), 64)
  4002. }
  4003. if err != nil || fl < 0 {
  4004. a = strings.Trim(v, " ")
  4005. break
  4006. }
  4007. }
  4008. }
  4009. if a != "" {
  4010. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  4011. error++
  4012. queryData = append(queryData, outentry)
  4013. continue
  4014. }
  4015. errExist := false
  4016. for _, sqlnamestr := range sqlslist {
  4017. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4018. paramslist := strings.Split(paramslists, ",")
  4019. if len(paramslist) > 0 {
  4020. s_params := make([]interface{}, 0)
  4021. for _, value := range paramslist {
  4022. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4023. if tempv, exists := c.Get("jwt_username"); exists {
  4024. s_params = append(s_params, tempv.(string))
  4025. } else {
  4026. s_params = append(s_params, "")
  4027. }
  4028. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4029. s_params = append(s_params, pastureid)
  4030. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4031. ids, err := setting.SnowIds.NextId()
  4032. if err != nil {
  4033. ids = time.Now().UnixNano()
  4034. logging.Info("create SnowIds err", err)
  4035. }
  4036. s_params = append(s_params, ids)
  4037. } else {
  4038. if outentry[strings.Trim(value, " ")] == nil {
  4039. s_params = append(s_params, "")
  4040. } else {
  4041. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4042. }
  4043. }
  4044. }
  4045. outentry["input"] = inputdata
  4046. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4047. if err != nil {
  4048. errExist = true
  4049. // if tx != nil {
  4050. // tx.Rollback()
  4051. // }
  4052. // if tx != nil {
  4053. // tx.Close()
  4054. // }
  4055. msg := geterrmsg(err.Error())
  4056. outentry["error_msg"] = msg
  4057. error++
  4058. queryData = append(queryData, outentry)
  4059. isdone = true
  4060. break
  4061. } else {
  4062. if len(returnmsgmap1) > 0 {
  4063. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4064. // if tx != nil {
  4065. // tx.Rollback()
  4066. // }
  4067. // if tx != nil {
  4068. // tx.Close()
  4069. // }
  4070. msg := geterrmsg(va.(string))
  4071. outentry["error_msg"] = msg
  4072. error++
  4073. queryData = append(queryData, outentry)
  4074. isdone = true
  4075. break
  4076. }
  4077. }
  4078. isdone = false
  4079. }
  4080. }
  4081. }
  4082. fmt.Println(outentry["栏舍名称"])
  4083. if !errExist {
  4084. dataexcel := make(map[string]interface{}, 0)
  4085. if _, ok := outentry["栏舍名称"]; ok {
  4086. dataexcel["barname"] = outentry["栏舍名称"]
  4087. }
  4088. if _, ok := outentry["实际牛头数"]; ok {
  4089. dataexcel["ccount"] = outentry["实际牛头数"]
  4090. }
  4091. // if _, ok := outentry["实际羊只数"]; ok {
  4092. // dataexcel["ccount"] = outentry["实际羊只数"]
  4093. // }
  4094. if _, ok := outentry["系数(%)"]; ok {
  4095. dataexcel["ratio"] = outentry["系数(%)"]
  4096. }
  4097. if _, ok := outentry["配方模板"]; ok {
  4098. dataexcel["ftname"] = outentry["配方模板"]
  4099. }
  4100. if _, ok := outentry["补料配方"]; ok {
  4101. dataexcel["ptsfname"] = outentry["补料配方"]
  4102. }
  4103. if _, ok := outentry["第一班比例(%)"]; ok {
  4104. dataexcel["1"] = outentry["第一班比例(%)"]
  4105. if fmt.Sprintf("%v", dataexcel["1"]) == "" {
  4106. dataexcel["1"] = 0
  4107. }
  4108. } else {
  4109. dataexcel["1"] = 0
  4110. }
  4111. if _, ok := outentry["第二班比例(%)"]; ok {
  4112. dataexcel["2"] = outentry["第二班比例(%)"]
  4113. if fmt.Sprintf("%v", dataexcel["2"]) == "" {
  4114. dataexcel["2"] = 0
  4115. }
  4116. } else {
  4117. dataexcel["2"] = 0
  4118. }
  4119. if _, ok := outentry["第三班比例(%)"]; ok {
  4120. dataexcel["3"] = outentry["第三班比例(%)"]
  4121. if fmt.Sprintf("%v", dataexcel["3"]) == "" {
  4122. dataexcel["3"] = 0
  4123. }
  4124. } else {
  4125. dataexcel["3"] = 0
  4126. }
  4127. if _, ok := outentry["第四班比例(%)"]; ok {
  4128. dataexcel["4"] = outentry["第四班比例(%)"]
  4129. if fmt.Sprintf("%v", dataexcel["4"]) == "" {
  4130. dataexcel["4"] = 0
  4131. }
  4132. } else {
  4133. dataexcel["4"] = 0
  4134. }
  4135. if _, ok := outentry["第五班比例(%)"]; ok {
  4136. dataexcel["5"] = outentry["第五班比例(%)"]
  4137. if fmt.Sprintf("%v", dataexcel["5"]) == "" {
  4138. dataexcel["5"] = 0
  4139. }
  4140. } else {
  4141. dataexcel["5"] = 0
  4142. }
  4143. if _, ok := outentry["第六班比例(%)"]; ok {
  4144. dataexcel["6"] = outentry["第六班比例(%)"]
  4145. if fmt.Sprintf("%v", dataexcel["6"]) == "" {
  4146. dataexcel["6"] = 0
  4147. }
  4148. } else {
  4149. dataexcel["6"] = 0
  4150. }
  4151. dataWeight := new(models.FpdetailEdit)
  4152. // dataWeightMap := make(map[string]interface{}, 0)
  4153. if _, ok := outentry["第一班重量"]; ok {
  4154. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4155. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4156. }
  4157. if _, ok := outentry["第二班重量"]; ok {
  4158. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4159. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4160. }
  4161. if _, ok := outentry["第三班重量"]; ok {
  4162. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4163. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4164. }
  4165. if _, ok := outentry["第四班重量"]; ok {
  4166. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4167. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4168. }
  4169. if _, ok := outentry["第五班重量"]; ok {
  4170. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4171. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4172. }
  4173. if _, ok := outentry["第六班重量"]; ok {
  4174. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4175. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4176. }
  4177. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4178. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4179. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4180. // fmt.Println(err)
  4181. if fmt.Sprintf("%v", dataexcel["ccount"]) == "0" {
  4182. dataWeight.Weight1 = 0
  4183. dataWeight.Weight2 = 0
  4184. dataWeight.Weight3 = 0
  4185. dataWeight.Weight4 = 0
  4186. dataWeight.Weight5 = 0
  4187. dataWeight.Weight6 = 0
  4188. }
  4189. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4190. if weight > 0 {
  4191. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4192. if err != nil {
  4193. logs.Error(err)
  4194. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4195. return
  4196. }
  4197. if !existbar {
  4198. continue
  4199. }
  4200. _, 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()
  4201. if err != nil {
  4202. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4203. return
  4204. }
  4205. _, 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()
  4206. if err != nil {
  4207. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4208. return
  4209. }
  4210. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4211. if err != nil {
  4212. logs.Error(err)
  4213. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4214. return
  4215. }
  4216. if !existft {
  4217. continue
  4218. }
  4219. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4220. if err != nil {
  4221. logs.Error(err)
  4222. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4223. return
  4224. }
  4225. if !ftexist {
  4226. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4227. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4228. if err != nil {
  4229. logs.Error(err)
  4230. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4231. return
  4232. }
  4233. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4234. if err != nil {
  4235. logs.Error(err)
  4236. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4237. return
  4238. }
  4239. }
  4240. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4241. if err != nil {
  4242. logs.Error(err)
  4243. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4244. return
  4245. }
  4246. if !exist {
  4247. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4248. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4249. if err != nil {
  4250. logs.Error(err)
  4251. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4252. return
  4253. }
  4254. }
  4255. var feedpargs []interface{}
  4256. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4257. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4258. if _, ok := dataexcel["ftname"]; ok {
  4259. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4260. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4261. // upFeedpSql += `,ftweight = ? `
  4262. // feedpargs = append(feedpargs, weight)
  4263. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4264. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4265. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4266. } else {
  4267. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4268. }
  4269. if _, ok := dataexcel["ptsfname"]; ok {
  4270. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4271. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4272. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4273. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4274. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4275. } else {
  4276. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4277. }
  4278. upFeedpSql += " where barname = ? and pastureid = ? "
  4279. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4280. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4281. if err != nil {
  4282. logs.Error(err)
  4283. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4284. return
  4285. }
  4286. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4287. if err != nil {
  4288. logs.Error(err)
  4289. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4290. return
  4291. }
  4292. if !exist1 {
  4293. _, 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) `,
  4294. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4295. if err != nil {
  4296. logs.Error(err)
  4297. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4298. return
  4299. }
  4300. }
  4301. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4302. if err != nil {
  4303. logs.Error(err)
  4304. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4305. return
  4306. }
  4307. if !exist2 {
  4308. _, 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) `,
  4309. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4310. if err != nil {
  4311. logs.Error(err)
  4312. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4313. return
  4314. }
  4315. }
  4316. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4317. if err != nil {
  4318. logs.Error(err)
  4319. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4320. return
  4321. }
  4322. if !exist3 {
  4323. _, 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) `,
  4324. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4325. if err != nil {
  4326. logs.Error(err)
  4327. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4328. return
  4329. }
  4330. }
  4331. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4332. if err != nil {
  4333. logs.Error(err)
  4334. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4335. return
  4336. }
  4337. if !exist4 {
  4338. _, 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) `,
  4339. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4340. if err != nil {
  4341. logs.Error(err)
  4342. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4343. return
  4344. }
  4345. }
  4346. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4347. if err != nil {
  4348. logs.Error(err)
  4349. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4350. return
  4351. }
  4352. if !exist5 {
  4353. _, 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) `,
  4354. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4355. if err != nil {
  4356. logs.Error(err)
  4357. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4358. return
  4359. }
  4360. }
  4361. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4362. if err != nil {
  4363. logs.Error(err)
  4364. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4365. return
  4366. }
  4367. if !exist6 {
  4368. _, 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) `,
  4369. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4370. if err != nil {
  4371. logs.Error(err)
  4372. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4373. return
  4374. }
  4375. }
  4376. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4377. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4378. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4379. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4380. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4381. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4382. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4383. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4384. and pastureid = ? and times = ?`
  4385. var fpdargs1 []interface{}
  4386. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4387. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4388. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4389. if err != nil {
  4390. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4391. return
  4392. }
  4393. var fpdargs2 []interface{}
  4394. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4395. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4396. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4397. if err != nil {
  4398. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4399. return
  4400. }
  4401. var fpdargs3 []interface{}
  4402. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4403. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4404. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4405. if err != nil {
  4406. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4407. return
  4408. }
  4409. var fpdargs4 []interface{}
  4410. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4411. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4412. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4413. if err != nil {
  4414. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4415. return
  4416. }
  4417. var fpdargs5 []interface{}
  4418. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4419. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4420. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4421. if err != nil {
  4422. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4423. return
  4424. }
  4425. var fpdargs6 []interface{}
  4426. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4427. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4428. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4429. if err != nil {
  4430. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4431. return
  4432. }
  4433. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4434. 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()
  4435. if err != nil {
  4436. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4437. return
  4438. }
  4439. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4440. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4441. upFpdetailList := make([]*upFpdetail, 0)
  4442. for _, newfpd := range newList {
  4443. for _, oldfpd := range oldFpdList {
  4444. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4445. var oldweight, newweight float64
  4446. if oldfpd["weight"] != nil {
  4447. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4448. }
  4449. if newfpd["weight"] != nil {
  4450. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4451. }
  4452. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4453. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4454. Old: oldweight,
  4455. New: newweight,
  4456. Times: newfpd["times"].(int64),
  4457. Ptid: newfpd["ptid"].(int64),
  4458. Fweight: fweight,
  4459. Id: oldfpd["id"].(int64),
  4460. })
  4461. break
  4462. }
  4463. }
  4464. }
  4465. // fmt.Println(dataexcel["barname"])
  4466. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4467. } else {
  4468. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4469. if err != nil {
  4470. logs.Error(err)
  4471. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4472. return
  4473. }
  4474. if !existbar {
  4475. continue
  4476. }
  4477. _, 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()
  4478. if err != nil {
  4479. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4480. return
  4481. }
  4482. _, 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()
  4483. if err != nil {
  4484. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4485. return
  4486. }
  4487. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4488. if err != nil {
  4489. logs.Error(err)
  4490. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4491. return
  4492. }
  4493. if !existft {
  4494. continue
  4495. }
  4496. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4497. if err != nil {
  4498. logs.Error(err)
  4499. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4500. return
  4501. }
  4502. if !ftexist {
  4503. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4504. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4505. if err != nil {
  4506. logs.Error(err)
  4507. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4508. return
  4509. }
  4510. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4511. if err != nil {
  4512. logs.Error(err)
  4513. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4514. return
  4515. }
  4516. }
  4517. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4518. if err != nil {
  4519. logs.Error(err)
  4520. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4521. return
  4522. }
  4523. if !exist {
  4524. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4525. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4526. if err != nil {
  4527. logs.Error(err)
  4528. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4529. return
  4530. }
  4531. }
  4532. var feedpargs []interface{}
  4533. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4534. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4535. if _, ok := dataexcel["ftname"]; ok {
  4536. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4537. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4538. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4539. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4540. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4541. } else {
  4542. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4543. }
  4544. if _, ok := dataexcel["ptsfname"]; ok {
  4545. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4546. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4547. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4548. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4549. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4550. } else {
  4551. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4552. }
  4553. upFeedpSql += " where barname = ? and pastureid = ? "
  4554. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4555. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4556. if err != nil {
  4557. logs.Error(err)
  4558. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4559. return
  4560. }
  4561. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4562. if err != nil {
  4563. logs.Error(err)
  4564. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4565. return
  4566. }
  4567. if !exist1 {
  4568. _, 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) `,
  4569. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4570. if err != nil {
  4571. logs.Error(err)
  4572. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4573. return
  4574. }
  4575. }
  4576. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4577. if err != nil {
  4578. logs.Error(err)
  4579. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4580. return
  4581. }
  4582. if !exist2 {
  4583. _, 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) `,
  4584. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4585. if err != nil {
  4586. logs.Error(err)
  4587. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4588. return
  4589. }
  4590. }
  4591. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4592. if err != nil {
  4593. logs.Error(err)
  4594. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4595. return
  4596. }
  4597. if !exist3 {
  4598. _, 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) `,
  4599. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4600. if err != nil {
  4601. logs.Error(err)
  4602. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4603. return
  4604. }
  4605. }
  4606. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4607. if err != nil {
  4608. logs.Error(err)
  4609. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4610. return
  4611. }
  4612. if !exist4 {
  4613. _, 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) `,
  4614. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4615. if err != nil {
  4616. logs.Error(err)
  4617. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4618. return
  4619. }
  4620. }
  4621. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4622. if err != nil {
  4623. logs.Error(err)
  4624. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4625. return
  4626. }
  4627. if !exist5 {
  4628. _, 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) `,
  4629. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4630. if err != nil {
  4631. logs.Error(err)
  4632. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4633. return
  4634. }
  4635. }
  4636. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4637. if err != nil {
  4638. logs.Error(err)
  4639. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4640. return
  4641. }
  4642. if !exist6 {
  4643. _, 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) `,
  4644. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4645. if err != nil {
  4646. logs.Error(err)
  4647. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4648. return
  4649. }
  4650. }
  4651. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4652. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4653. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4654. and pastureid = ? and times = ?`
  4655. var fpdargs1 []interface{}
  4656. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4657. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4658. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4659. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4660. if err != nil {
  4661. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4662. return
  4663. }
  4664. var fpdargs2 []interface{}
  4665. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4666. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4667. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4668. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4669. if err != nil {
  4670. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4671. return
  4672. }
  4673. var fpdargs3 []interface{}
  4674. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4675. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4676. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4677. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4678. if err != nil {
  4679. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4680. return
  4681. }
  4682. var fpdargs4 []interface{}
  4683. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4684. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4685. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4686. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4687. if err != nil {
  4688. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4689. return
  4690. }
  4691. var fpdargs5 []interface{}
  4692. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4693. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4694. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4695. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4696. if err != nil {
  4697. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4698. return
  4699. }
  4700. var fpdargs6 []interface{}
  4701. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4702. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4703. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4704. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4705. if err != nil {
  4706. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4707. return
  4708. }
  4709. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4710. 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()
  4711. if err != nil {
  4712. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4713. return
  4714. }
  4715. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4716. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4717. upFpdetailList := make([]*upFpdetail, 0)
  4718. for _, newfpd := range newList {
  4719. for _, oldfpd := range oldFpdList {
  4720. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4721. var oldweight, newweight float64
  4722. if oldfpd["weight"] != nil {
  4723. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4724. }
  4725. if newfpd["weight"] != nil {
  4726. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4727. }
  4728. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4729. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4730. Old: oldweight,
  4731. New: newweight,
  4732. Times: newfpd["times"].(int64),
  4733. Ptid: newfpd["ptid"].(int64),
  4734. Fweight: fweight,
  4735. Id: oldfpd["id"].(int64),
  4736. })
  4737. break
  4738. }
  4739. }
  4740. }
  4741. // fmt.Println(dataexcel["barname"])
  4742. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4743. }
  4744. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4745. }
  4746. }
  4747. if !isdone {
  4748. ok++
  4749. isdone = true
  4750. }
  4751. }
  4752. for barname, v := range dataList {
  4753. // for _, v1 := range v {
  4754. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4755. // and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4756. // if count == 1 {
  4757. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4758. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4759. // if err != nil {
  4760. // logs.Error(err)
  4761. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4762. // return
  4763. // }
  4764. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4765. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4766. // if err != nil {
  4767. // logs.Error(err)
  4768. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4769. // return
  4770. // }
  4771. // }
  4772. // }
  4773. /*
  4774. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  4775. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  4776. if err != nil {
  4777. logs.Error(err)
  4778. return
  4779. }
  4780. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4781. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  4782. if err != nil {
  4783. logs.Error(err)
  4784. return
  4785. }
  4786. */
  4787. updateFpdetailByBar(pastureid, barname, v)
  4788. }
  4789. } else {
  4790. 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
  4791. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4792. if err != nil {
  4793. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4794. return
  4795. }
  4796. rows := xlsx1.GetRows(sheetname)
  4797. // 限制10000条,多余的截取掉
  4798. if len(rows) > 10000 {
  4799. rows = rows[:10000]
  4800. }
  4801. dataList := make(map[string][]*upFpdetail, 0)
  4802. for i, row := range rows {
  4803. if i > 0 {
  4804. entry := make(map[string]interface{})
  4805. outentry := make(map[string]interface{})
  4806. for j, colCell := range rows[0] {
  4807. for k, colCell1 := range row {
  4808. if j == k {
  4809. outentry[colCell] = colCell1
  4810. entry[colCell] = colCell1
  4811. }
  4812. }
  4813. }
  4814. inputdata = ""
  4815. a := ""
  4816. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4817. //校验日期格式
  4818. for _, v := range dateParamslist {
  4819. if v == "" {
  4820. continue
  4821. }
  4822. if d, ok := outentry[v]; ok {
  4823. dtime, err := TransfTime(d.(string))
  4824. if err != nil {
  4825. a = v
  4826. break
  4827. }
  4828. outentry[v] = dtime
  4829. }
  4830. }
  4831. if a != "" {
  4832. outentry["error_msg"] = a + " format error"
  4833. error++
  4834. queryData = append(queryData, outentry)
  4835. continue
  4836. }
  4837. a = ""
  4838. //校验必填格式
  4839. for _, v := range requiredParamslist {
  4840. if v == "" {
  4841. continue
  4842. }
  4843. if d, ok := outentry[v]; !ok || d == "" {
  4844. a = v
  4845. break
  4846. }
  4847. }
  4848. if a != "" {
  4849. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4850. error++
  4851. queryData = append(queryData, outentry)
  4852. continue
  4853. }
  4854. a = ""
  4855. //校验数字格式
  4856. for _, v := range numParamslist {
  4857. if v == "" {
  4858. continue
  4859. }
  4860. d, ok := outentry[v]
  4861. if !ok || d == "" {
  4862. outentry[v] = 0
  4863. } else {
  4864. var fl float64
  4865. switch d.(type) {
  4866. case string:
  4867. fl, err = strconv.ParseFloat(d.(string), 64)
  4868. }
  4869. if err != nil || fl < 0 {
  4870. a = v
  4871. break
  4872. }
  4873. }
  4874. }
  4875. if a != "" {
  4876. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4877. error++
  4878. queryData = append(queryData, outentry)
  4879. continue
  4880. }
  4881. errExist := false
  4882. for _, sqlnamestr := range sqlslist {
  4883. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4884. paramslist := strings.Split(paramslists, ",")
  4885. if len(paramslist) > 0 {
  4886. s_params := make([]interface{}, 0)
  4887. for _, value := range paramslist {
  4888. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4889. if tempv, exists := c.Get("jwt_username"); exists {
  4890. s_params = append(s_params, tempv.(string))
  4891. } else {
  4892. s_params = append(s_params, "")
  4893. }
  4894. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4895. s_params = append(s_params, pastureid)
  4896. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4897. ids, err := setting.SnowIds.NextId()
  4898. if err != nil {
  4899. ids = time.Now().UnixNano()
  4900. logging.Info("create SnowIds err", err)
  4901. }
  4902. s_params = append(s_params, ids)
  4903. } else {
  4904. if outentry[strings.Trim(value, " ")] == nil {
  4905. s_params = append(s_params, "")
  4906. } else {
  4907. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4908. }
  4909. }
  4910. }
  4911. outentry["input"] = inputdata
  4912. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4913. if err != nil {
  4914. errExist = true
  4915. // if tx != nil {
  4916. // tx.Rollback()
  4917. // }
  4918. // if tx != nil {
  4919. // tx.Close()
  4920. // }
  4921. msg := geterrmsg(err.Error())
  4922. outentry["error_msg"] = msg
  4923. error++
  4924. queryData = append(queryData, outentry)
  4925. isdone = true
  4926. break
  4927. } else {
  4928. if len(returnmsgmap1) > 0 {
  4929. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4930. // if tx != nil {
  4931. // tx.Rollback()
  4932. // }
  4933. // if tx != nil {
  4934. // tx.Close()
  4935. // }
  4936. msg := geterrmsg(va.(string))
  4937. outentry["error_msg"] = msg
  4938. error++
  4939. queryData = append(queryData, outentry)
  4940. isdone = true
  4941. break
  4942. }
  4943. }
  4944. isdone = false
  4945. }
  4946. }
  4947. }
  4948. if !errExist {
  4949. dataexcel := make(map[string]interface{}, 0)
  4950. if _, ok := outentry["Pen Name"]; ok {
  4951. dataexcel["barname"] = outentry["Pen Name"]
  4952. }
  4953. if _, ok := outentry["Actual Cattle Number"]; ok {
  4954. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4955. }
  4956. if _, ok := outentry["Coefficient(%)"]; ok {
  4957. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4958. }
  4959. if _, ok := outentry["Formula Template"]; ok {
  4960. dataexcel["ftname"] = outentry["Formula Template"]
  4961. }
  4962. if _, ok := outentry["Supplement Formula"]; ok {
  4963. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4964. }
  4965. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4966. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4967. }
  4968. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4969. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4970. }
  4971. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4972. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4973. }
  4974. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4975. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4976. }
  4977. if _, ok := outentry["Fifth Shift Ratio(%)"]; ok {
  4978. dataexcel["5"] = outentry["Fifth Shift Ratio(%)"]
  4979. }
  4980. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4981. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4982. }
  4983. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4984. if err != nil {
  4985. logs.Error(err)
  4986. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4987. return
  4988. }
  4989. if !existbar {
  4990. continue
  4991. }
  4992. _, 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()
  4993. if err != nil {
  4994. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4995. return
  4996. }
  4997. _, 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()
  4998. if err != nil {
  4999. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5000. return
  5001. }
  5002. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  5003. if err != nil {
  5004. logs.Error(err)
  5005. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  5006. return
  5007. }
  5008. if !existft {
  5009. continue
  5010. }
  5011. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  5012. if err != nil {
  5013. logs.Error(err)
  5014. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5015. return
  5016. }
  5017. if !ftexist {
  5018. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  5019. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5020. if err != nil {
  5021. logs.Error(err)
  5022. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5023. return
  5024. }
  5025. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5026. if err != nil {
  5027. logs.Error(err)
  5028. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5029. return
  5030. }
  5031. }
  5032. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5033. if err != nil {
  5034. logs.Error(err)
  5035. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5036. return
  5037. }
  5038. if !exist {
  5039. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  5040. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  5041. if err != nil {
  5042. logs.Error(err)
  5043. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5044. return
  5045. }
  5046. }
  5047. var feedpargs []interface{}
  5048. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  5049. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  5050. if _, ok := dataexcel["ftname"]; ok {
  5051. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  5052. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  5053. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  5054. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  5055. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5056. } else {
  5057. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  5058. }
  5059. if _, ok := dataexcel["ptsfname"]; ok {
  5060. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  5061. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  5062. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  5063. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  5064. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5065. } else {
  5066. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  5067. }
  5068. upFeedpSql += " where barname = ? and pastureid = ? "
  5069. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  5070. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  5071. if err != nil {
  5072. logs.Error(err)
  5073. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5074. return
  5075. }
  5076. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  5077. if err != nil {
  5078. logs.Error(err)
  5079. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5080. return
  5081. }
  5082. if !exist1 {
  5083. _, 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) `,
  5084. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5085. if err != nil {
  5086. logs.Error(err)
  5087. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5088. return
  5089. }
  5090. }
  5091. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5092. if err != nil {
  5093. logs.Error(err)
  5094. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5095. return
  5096. }
  5097. if !exist2 {
  5098. _, 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) `,
  5099. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5100. if err != nil {
  5101. logs.Error(err)
  5102. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5103. return
  5104. }
  5105. }
  5106. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5107. if err != nil {
  5108. logs.Error(err)
  5109. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5110. return
  5111. }
  5112. if !exist3 {
  5113. _, 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) `,
  5114. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5115. if err != nil {
  5116. logs.Error(err)
  5117. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5118. return
  5119. }
  5120. }
  5121. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5122. if err != nil {
  5123. logs.Error(err)
  5124. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5125. return
  5126. }
  5127. if !exist4 {
  5128. _, 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) `,
  5129. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5130. if err != nil {
  5131. logs.Error(err)
  5132. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5133. return
  5134. }
  5135. }
  5136. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5137. if err != nil {
  5138. logs.Error(err)
  5139. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5140. return
  5141. }
  5142. if !exist5 {
  5143. _, 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) `,
  5144. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5145. if err != nil {
  5146. logs.Error(err)
  5147. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5148. return
  5149. }
  5150. }
  5151. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5152. if err != nil {
  5153. logs.Error(err)
  5154. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5155. return
  5156. }
  5157. if !exist6 {
  5158. _, 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) `,
  5159. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5160. if err != nil {
  5161. logs.Error(err)
  5162. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5163. return
  5164. }
  5165. }
  5166. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5167. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5168. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5169. and pastureid = ? and times = ?`
  5170. var fpdargs1 []interface{}
  5171. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5172. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5173. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5174. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5175. if err != nil {
  5176. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5177. return
  5178. }
  5179. var fpdargs2 []interface{}
  5180. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5181. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5182. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5183. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5184. if err != nil {
  5185. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5186. return
  5187. }
  5188. var fpdargs3 []interface{}
  5189. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5190. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5191. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5192. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5193. if err != nil {
  5194. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5195. return
  5196. }
  5197. var fpdargs4 []interface{}
  5198. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5199. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5200. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5201. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5202. if err != nil {
  5203. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5204. return
  5205. }
  5206. var fpdargs5 []interface{}
  5207. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5208. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5209. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5210. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5211. if err != nil {
  5212. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5213. return
  5214. }
  5215. var fpdargs6 []interface{}
  5216. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5217. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5218. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5219. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5220. if err != nil {
  5221. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5222. return
  5223. }
  5224. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5225. 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()
  5226. if err != nil {
  5227. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5228. return
  5229. }
  5230. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5231. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5232. upFpdetailList := make([]*upFpdetail, 0)
  5233. for _, newfpd := range newList {
  5234. for _, oldfpd := range oldFpdList {
  5235. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5236. var oldweight, newweight float64
  5237. if oldfpd["weight"] != nil {
  5238. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5239. }
  5240. if newfpd["weight"] != nil {
  5241. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5242. }
  5243. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5244. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5245. Old: oldweight,
  5246. New: newweight,
  5247. Times: newfpd["times"].(int64),
  5248. Ptid: newfpd["ptid"].(int64),
  5249. Fweight: fweight,
  5250. Id: oldfpd["id"].(int64),
  5251. })
  5252. break
  5253. }
  5254. }
  5255. }
  5256. // fmt.Println(dataexcel["barname"])
  5257. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5258. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5259. }
  5260. }
  5261. if !isdone {
  5262. ok++
  5263. isdone = true
  5264. }
  5265. }
  5266. for barname, v := range dataList {
  5267. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5268. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5269. if err != nil {
  5270. logs.Error(err)
  5271. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5272. return
  5273. }
  5274. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5275. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5276. if err != nil {
  5277. logs.Error(err)
  5278. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5279. return
  5280. }
  5281. updateFpdetailByBar(pastureid, barname, v)
  5282. }
  5283. }
  5284. data := make(map[string]interface{})
  5285. data["result"] = queryData
  5286. data["success"] = ok
  5287. data["err_count"] = error
  5288. appG.Response(http.StatusOK, e.SUCCESS, data)
  5289. }
  5290. type upFpdetail struct {
  5291. Old float64
  5292. New float64
  5293. Times int64
  5294. Ptid int64
  5295. Fweight float64
  5296. Id int64
  5297. // Ptsid string
  5298. }
  5299. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5300. tx := restful.Engine.NewSession()
  5301. defer tx.Close()
  5302. tx.Begin()
  5303. 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 `,
  5304. pastureid, barname).Query().List()
  5305. if err != nil {
  5306. logs.Error(err)
  5307. }
  5308. for _, fpd := range fpdList {
  5309. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5310. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5311. pastureid, fpd["id"], fpd["times"]).Query().List()
  5312. if err != nil {
  5313. tx.Rollback()
  5314. logs.Error(err)
  5315. return err
  5316. }
  5317. var lweight float64
  5318. for _, lppland := range lpplandList {
  5319. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5320. lweight += lweight1
  5321. }
  5322. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5323. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5324. if fpdweight >= ptuse && lweight == ptuse {
  5325. continue
  5326. } else {
  5327. if lweight <= fpdweight {
  5328. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5329. if err != nil {
  5330. tx.Rollback()
  5331. logs.Error(err)
  5332. return err
  5333. }
  5334. } else {
  5335. weight := lweight - fpdweight
  5336. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5337. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5338. if err != nil {
  5339. tx.Rollback()
  5340. logs.Error(err)
  5341. return err
  5342. }
  5343. for _, lppland := range lpplandList {
  5344. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5345. if weight >= lpplandlweight {
  5346. weight = weight - lpplandlweight
  5347. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5348. if err != nil {
  5349. tx.Rollback()
  5350. logs.Error(err)
  5351. return err
  5352. }
  5353. } else {
  5354. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5355. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5356. if err != nil {
  5357. tx.Rollback()
  5358. logs.Error(err)
  5359. return err
  5360. }
  5361. weight = 0
  5362. break
  5363. }
  5364. }
  5365. }
  5366. }
  5367. }
  5368. for _, list := range dataList {
  5369. ftmap := make(map[string]interface{})
  5370. ftmap["old"] = list.Old
  5371. ftmap["new"] = list.New
  5372. ftmap["times"] = list.Times
  5373. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5374. ftmap["ptsid"] = ""
  5375. // fmt.Println(ftmap)
  5376. // 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 ,
  5377. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5378. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5379. // UNION
  5380. fpdDataList, err := tx.SQL(`
  5381. 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 ,
  5382. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5383. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5384. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5385. if err != nil {
  5386. tx.Rollback()
  5387. logs.Error(err)
  5388. }
  5389. for _, fpd := range fpdDataList {
  5390. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5391. // fttype := -1
  5392. // if fpd["fttype"].(string) == "1" {
  5393. fttype := 1
  5394. // }
  5395. var fweight float64
  5396. var lweight float64
  5397. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5398. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  5399. t.maxstirfeed,t.volume * (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  5400. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5401. join tmr t on t.id = lpp.tmrid
  5402. where lppland.fpdid =?
  5403. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5404. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5405. if err != nil {
  5406. tx.Rollback()
  5407. logs.Error(err)
  5408. }
  5409. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5410. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5411. // 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
  5412. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5413. var w float64
  5414. var status int
  5415. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5416. if weight >= 0 {
  5417. continue
  5418. }
  5419. w = weight
  5420. status = 0
  5421. } else {
  5422. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5423. // continue
  5424. // }
  5425. w = weight
  5426. status = 1
  5427. }
  5428. // for _, lppland := range lpplandtl1List {
  5429. // lweight += lppland.Lweight
  5430. // }
  5431. for _, lppland := range lpplandtl1List {
  5432. lpplandInfo := new(lpplandtlInfo)
  5433. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5434. lweight = lpplandInfo.Lweight
  5435. if status == 1 {
  5436. // if w <= lppland.Lweight {
  5437. if lppland.Maxweight <= lweight {
  5438. continue
  5439. }
  5440. if w+lweight <= lppland.Maxweight {
  5441. lppland.Lweight += w
  5442. lweight += w
  5443. fweight += w
  5444. w = 0
  5445. } else {
  5446. w = w - (lppland.Maxweight - lweight)
  5447. n := (lppland.Maxweight - lweight)
  5448. lppland.Lweight = lppland.Lweight + n
  5449. lweight += n
  5450. fweight += n
  5451. }
  5452. } else {
  5453. if lppland.Lweight == 0 {
  5454. continue
  5455. }
  5456. if w+lppland.Lweight >= 0 {
  5457. lppland.Lweight = lppland.Lweight + w
  5458. lweight = lweight + w
  5459. fweight = fweight + w
  5460. w = 0
  5461. } else {
  5462. w = w + lppland.Lweight
  5463. lweight = lweight - lppland.Lweight
  5464. fweight = fweight - lppland.Lweight
  5465. lppland.Lweight = 0
  5466. }
  5467. }
  5468. if lppland.Lweight > 0 {
  5469. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5470. if err != nil {
  5471. tx.Rollback()
  5472. logs.Error(err)
  5473. return err
  5474. }
  5475. } else {
  5476. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5477. if err != nil {
  5478. tx.Rollback()
  5479. logs.Error(err)
  5480. return err
  5481. }
  5482. }
  5483. if w == 0 {
  5484. break
  5485. }
  5486. }
  5487. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5488. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5489. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5490. if err != nil {
  5491. tx.Rollback()
  5492. logs.Error(err)
  5493. }
  5494. if w == 0 {
  5495. break
  5496. }
  5497. }
  5498. }
  5499. }
  5500. err = tx.Commit()
  5501. if err != nil {
  5502. logs.Error(err)
  5503. tx.Rollback()
  5504. return err
  5505. }
  5506. now := time.Now()
  5507. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5508. if err != nil {
  5509. logs.Error(err)
  5510. return nil
  5511. }
  5512. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5513. if err != nil {
  5514. logs.Error(err)
  5515. return nil
  5516. }
  5517. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5518. if err != nil {
  5519. logs.Error(err)
  5520. return nil
  5521. }
  5522. for _, newLpplandtl1 := range newLpplandtl1List {
  5523. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5524. background,cowcount,ccountradio,lweighthis,createdate)
  5525. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5526. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5527. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5528. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5529. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5530. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5531. if err != nil {
  5532. logs.Error(err)
  5533. // appG.Response(http.StatusOK, e.ERROR, false)
  5534. return err
  5535. }
  5536. }
  5537. for _, newFpd := range newFpdDataList {
  5538. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5539. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5540. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5541. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5542. if err != nil {
  5543. logs.Error(err)
  5544. // appG.Response(http.StatusOK, e.ERROR, false)
  5545. return err
  5546. }
  5547. }
  5548. for _, newFeedp := range newFeedpList {
  5549. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5550. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5551. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5552. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5553. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5554. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5555. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5556. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5557. if err != nil {
  5558. logs.Error(err)
  5559. // appG.Response(http.StatusOK, e.ERROR, false)
  5560. return err
  5561. }
  5562. }
  5563. return nil
  5564. }
  5565. func DeleteFTdetail(c *gin.Context) {
  5566. appG := app.Gin{C: c}
  5567. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5568. fsion := gofasion.NewFasion(string(dataByte))
  5569. parammaps := fsion.Get("parammaps")
  5570. pastureid := parammaps.Get("pastureid").ValueStr()
  5571. ftid := parammaps.Get("ftid").ValueStr()
  5572. tx := restful.Engine.NewSession()
  5573. defer tx.Close()
  5574. tx.Begin()
  5575. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5576. if err != nil {
  5577. tx.Rollback()
  5578. logs.Error(err)
  5579. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5580. return
  5581. }
  5582. if parammaps.Get("type").ValueStr() == "1" {
  5583. _, err := tx.SQL(`UPDATE feedp fp
  5584. set
  5585. fp.ftweight= IFNULL(IF(
  5586. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5587. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5588. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5589. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5590. ),0),fp.feedweight = IFNULL(IF(
  5591. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5592. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5593. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5594. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5595. ),0) +ifnull(fp.supplyweight,0)
  5596. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5597. if err != nil {
  5598. tx.Rollback()
  5599. logs.Error(err)
  5600. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5601. return
  5602. }
  5603. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5604. _, err = tx.SQL(`
  5605. UPDATE fpdetail fpd
  5606. INNER JOIN feedp fp
  5607. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5608. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5609. ptuse= 0
  5610. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5611. if err != nil {
  5612. tx.Rollback()
  5613. logs.Error(err)
  5614. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5615. return
  5616. }
  5617. } else {
  5618. _, err := tx.SQL(`UPDATE feedp fp
  5619. SET
  5620. fp.supplyweight= IFNULL(IF(
  5621. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5622. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5623. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5624. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5625. ),0),fp.feedweight = IFNULL(IF(
  5626. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5627. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5628. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5629. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5630. ),0) + ifnull(fp.supplyweight,0)
  5631. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5632. if err != nil {
  5633. tx.Rollback()
  5634. logs.Error(err)
  5635. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5636. return
  5637. }
  5638. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5639. _, err = tx.SQL(`
  5640. UPDATE fpdetail fpd
  5641. INNER JOIN feedp fp
  5642. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5643. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5644. ptsrate = 0
  5645. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5646. if err != nil {
  5647. tx.Rollback()
  5648. logs.Error(err)
  5649. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5650. return
  5651. }
  5652. }
  5653. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5654. if err != nil {
  5655. tx.Rollback()
  5656. logs.Error(err)
  5657. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5658. return
  5659. }
  5660. err = tx.Commit()
  5661. if err != nil {
  5662. tx.Rollback()
  5663. logs.Error(err)
  5664. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5665. return
  5666. }
  5667. appG.Response(http.StatusOK, e.SUCCESS, true)
  5668. }
  5669. func DeleteSpillageAll(c *gin.Context) {
  5670. appG := app.Gin{C: c}
  5671. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5672. fsion := gofasion.NewFasion(string(dataByte))
  5673. parammaps := fsion.Get("parammaps")
  5674. pastureid := parammaps.Get("pastureid").ValueStr()
  5675. times := parammaps.Get("times").ValueStr()
  5676. barid := parammaps.Get("barid").ValueStr()
  5677. tx := restful.Engine.NewSession()
  5678. defer tx.Close()
  5679. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5680. if err != nil {
  5681. logs.Error(err)
  5682. appG.Response(http.StatusOK, e.ERROR, false)
  5683. return
  5684. }
  5685. now := time.Now()
  5686. for _, item := range lpplandtl1List {
  5687. go func(item map[string]interface{}) {
  5688. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5689. background,cowcount,ccountradio,lweighthis,createdate)
  5690. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5691. item["pastureid"], item["lppid"], item["barid"],
  5692. item["barname"], item["fpdid"], item["fttype"],
  5693. item["lweight"], item["sort"], item["tmrid"],
  5694. item["tmrname"], item["background"], item["cowcount"],
  5695. item["ccountradio"], item["lweighthis"], now).Execute()
  5696. if err != nil {
  5697. logs.Error(err)
  5698. appG.Response(http.StatusOK, e.ERROR, false)
  5699. return
  5700. }
  5701. }(item)
  5702. }
  5703. tx.Begin()
  5704. _, 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()
  5705. if err != nil {
  5706. tx.Rollback()
  5707. logs.Error(err)
  5708. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5709. return
  5710. }
  5711. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5712. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5713. if err != nil {
  5714. tx.Rollback()
  5715. logs.Error(err)
  5716. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5717. return
  5718. }
  5719. err = tx.Commit()
  5720. if err != nil {
  5721. tx.Rollback()
  5722. logs.Error(err)
  5723. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5724. return
  5725. }
  5726. appG.Response(http.StatusOK, e.SUCCESS, true)
  5727. }
  5728. func GetTMRListEnableTypeAll(c *gin.Context) {
  5729. appG := app.Gin{C: c}
  5730. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5731. fsion := gofasion.NewFasion(string(dataByte))
  5732. parammaps := fsion.Get("parammaps")
  5733. pastureid := parammaps.Get("pastureid").ValueStr()
  5734. tx := restful.Engine.NewSession()
  5735. defer tx.Close()
  5736. dataList, err := tx.SQL(`SELECT
  5737. eqcode,
  5738. tname,
  5739. datacaptureno,
  5740. trim(tclassid) tclassid,
  5741. concat(tname,' / ',eqcode) tmrmix,
  5742. d.label tclassname,
  5743. maxstirfeed,
  5744. remark,
  5745. tmr.enable,
  5746. TRIM(tmr.id) id,
  5747. TRIM(tmr.pastureid)pastureid
  5748. FROM
  5749. tmr
  5750. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5751. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5752. ORDER BY id DESC`, pastureid).Query().List()
  5753. if err != nil {
  5754. logs.Error(err)
  5755. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5756. return
  5757. }
  5758. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5759. if err != nil {
  5760. logs.Error(err)
  5761. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5762. return
  5763. }
  5764. var carNum int64
  5765. for _, sysopt := range sysoptData {
  5766. if sysopt["inforvalue"] == nil {
  5767. carNum = 1
  5768. } else {
  5769. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5770. }
  5771. }
  5772. id := 200
  5773. n := 0
  5774. for i := carNum; i > 0; i-- {
  5775. id++
  5776. n++
  5777. data := make(map[string]interface{}, 0)
  5778. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5779. data["tname"] = fmt.Sprintf("任意车%d", n)
  5780. data["datacaptureno"] = -2
  5781. data["tclassid"] = -2
  5782. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5783. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5784. data["maxstirfeed"] = 100000
  5785. data["remark"] = fmt.Sprintf("任意车%d", n)
  5786. data["enable"] = 1
  5787. data["id"] = fmt.Sprintf("%d", id)
  5788. data["pastureid"] = pastureid
  5789. // data := make(map[string]interface{}, 0)
  5790. // data["eqcode"] = fmt.Sprintf("AnyCar%d", n)
  5791. // data["tname"] = fmt.Sprintf("AnyCar%d", n)
  5792. // data["datacaptureno"] = -2
  5793. // data["tclassid"] = -2
  5794. // data["tmrmix"] = fmt.Sprintf("AnyCar%d", n)
  5795. // data["tclassname"] = fmt.Sprintf("AnyCar%d", n)
  5796. // data["maxstirfeed"] = 100000
  5797. // data["remark"] = fmt.Sprintf("AnyCar%d", n)
  5798. // data["enable"] = 1
  5799. // data["id"] = fmt.Sprintf("%d", id)
  5800. // data["pastureid"] = pastureid
  5801. dataList = append(dataList, data)
  5802. }
  5803. // UNION ALL
  5804. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5805. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5806. }
  5807. func GetFeedpHistory(c *gin.Context) {
  5808. appG := app.Gin{C: c}
  5809. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5810. fsion := gofasion.NewFasion(string(dataByte))
  5811. // parammaps := fsion.Get("parammaps")
  5812. bar := fsion.Get("barname").ValueStr()
  5813. startDate := fsion.Get("startDate").ValueStr()
  5814. endDate := fsion.Get("endDate").ValueStr()
  5815. tx := restful.Engine.NewSession()
  5816. defer tx.Close()
  5817. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5818. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5819. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5820. if err != nil {
  5821. logs.Error(err)
  5822. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5823. return
  5824. }
  5825. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5826. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5827. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5828. if err != nil {
  5829. logs.Error(err)
  5830. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5831. return
  5832. }
  5833. for _, feedp := range feedpList {
  5834. // LastftList, err := tx.SQL(` select tname ,id
  5835. // from feedtemplethistory where id = ?
  5836. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5837. // if err != nil {
  5838. // logs.Error(err)
  5839. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5840. // return
  5841. // }
  5842. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5843. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5844. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5845. if err != nil {
  5846. logs.Error(err)
  5847. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5848. return
  5849. }
  5850. var ftname interface{}
  5851. ftnamestatus := 0
  5852. ftname = feedp["ftname"]
  5853. var lastftid int64
  5854. if len(nextfeedpList) > 0 {
  5855. for _, ft := range nextfeedpList {
  5856. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5857. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5858. lastftid = ft["ftid"].(int64)
  5859. ftnamestatus = 1
  5860. break
  5861. }
  5862. }
  5863. }
  5864. for i, fpd := range fpdList {
  5865. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5866. fpd["weightstatus"] = 0
  5867. fpd["tratiostatus"] = 0
  5868. fpd["ftnamestatus"] = ftnamestatus
  5869. for k, fpd2 := range fpdList {
  5870. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5871. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5872. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5873. fpd["weightstatus"] = 1
  5874. }
  5875. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5876. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5877. fpd["tratiostatus"] = 1
  5878. }
  5879. break
  5880. }
  5881. }
  5882. fpd["barid"] = feedp["barid"]
  5883. fpd["barname"] = feedp["barname"]
  5884. fpd["ccount"] = feedp["ccount"]
  5885. fpd["ratio"] = feedp["ratio"]
  5886. fpd["ccountratio"] = feedp["ccountratio"]
  5887. fpd["ftid"] = feedp["ftid"]
  5888. fpd["ftname"] = ftname
  5889. fpd["ccountstatus"] = 0
  5890. fpd["ccountratiostatus"] = 0
  5891. fpd["ratiostatus"] = 0
  5892. fpd["ftnamestatus"] = 0
  5893. fpd["lastftid"] = lastftid
  5894. for _, next := range nextfeedpList {
  5895. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5896. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5897. fpd["ccountstatus"] = 1
  5898. }
  5899. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5900. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5901. fpd["ccountratiostatus"] = 1
  5902. }
  5903. if next["ratio"].(string) != fpd["ratio"].(string) {
  5904. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5905. fpd["ratiostatus"] = 1
  5906. }
  5907. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5908. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5909. // fpd["ftnamestatus"] = 1
  5910. // }
  5911. }
  5912. }
  5913. }
  5914. }
  5915. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5916. }
  5917. // func GetLpplandtl1History(c *gin.Context) {
  5918. // appG := app.Gin{C: c}
  5919. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5920. // fsion := gofasion.NewFasion(string(dataByte))
  5921. // // parammaps := fsion.Get("parammaps")
  5922. // barid := fsion.Get("barid").ValueStr()
  5923. // startDate := fsion.Get("startDate").ValueStr()
  5924. // endDate := fsion.Get("endDate").ValueStr()
  5925. // tx := restful.Engine.NewSession()
  5926. // defer tx.Close()
  5927. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5928. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5929. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5930. // // if err != nil {
  5931. // // logs.Error(err)
  5932. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5933. // // return
  5934. // // }
  5935. // // for _, feedp := range feedpList {
  5936. // // fmt.Println(feedp)
  5937. // // for i, fpd := range fpdList {
  5938. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5939. // // for k, fpd2 := range fpdList {
  5940. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5941. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5942. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5943. // // }
  5944. // // break
  5945. // // }
  5946. // // }
  5947. // // fpd["barid"] = feedp["barid"]
  5948. // // fpd["barname"] = feedp["barname"]
  5949. // // fpd["ccount"] = feedp["ccount"]
  5950. // // fpd["ratio"] = feedp["ratio"]
  5951. // // fpd["ccountratio"] = feedp["ccountratio"]
  5952. // // fpd["ftid"] = feedp["ftid"]
  5953. // // fpd["ftname"] = feedp["ftname"]
  5954. // // }
  5955. // // }
  5956. // // }
  5957. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5958. // }
  5959. func GetRemind(c *gin.Context) {
  5960. appG := app.Gin{C: c}
  5961. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5962. fsion := gofasion.NewFasion(string(dataByte))
  5963. parammaps := fsion.Get("parammaps")
  5964. pastureid := parammaps.Get("pastureid").ValueStr()
  5965. tx := restful.Engine.NewSession()
  5966. defer tx.Close()
  5967. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5968. if err != nil {
  5969. logs.Error(err)
  5970. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5971. return
  5972. }
  5973. // pastureid = "3"
  5974. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5975. if err != nil {
  5976. logs.Error(err)
  5977. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5978. return
  5979. }
  5980. defer resp.Body.Close()
  5981. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5982. buf.ReadFrom(resp.Body)
  5983. fmt.Println(string(buf.Bytes()))
  5984. respMap := make(map[string]interface{}, 0)
  5985. err = json.Unmarshal(buf.Bytes(), &respMap)
  5986. if err != nil {
  5987. logs.Error(err)
  5988. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5989. return
  5990. }
  5991. for _, data := range dataList {
  5992. r := make(map[string]interface{}, 0)
  5993. r["sys_name"] = ""
  5994. r["service_id"] = ""
  5995. r["pasture_id"] = ""
  5996. r["type_name"] = ""
  5997. r["remind_type_id"] = ""
  5998. r["remind_type"] = ""
  5999. r["push_date"] = ""
  6000. r["push_time"] = ""
  6001. r["interval_time"] = ""
  6002. r["push_limit"] = ""
  6003. r["template_id"] = ""
  6004. r["roles_id"] = ""
  6005. r["users_id"] = ""
  6006. r["date_type"] = ""
  6007. r["cycle_type"] = ""
  6008. data["data"] = r
  6009. for _, resp := range respMap["data"].([]interface{}) {
  6010. resp1 := resp.(map[string]interface{})
  6011. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  6012. if resp1["push_time"] == nil {
  6013. resp1["push_time"] = ""
  6014. }
  6015. data["data"] = resp1
  6016. break
  6017. }
  6018. }
  6019. }
  6020. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  6021. }
  6022. type NoticeMsgtype struct {
  6023. SysName string `json:"sys_name"`
  6024. PastureId int64 `json:"pasture_id"`
  6025. ServiceId int64 `json:"service_id"`
  6026. TypeName string `json:"type_name"`
  6027. RemindType int64 `json:"remind_type"`
  6028. PushDate int64 `json:"push_date"`
  6029. PushTime string `json:"push_time"`
  6030. IntervalTime int64 `json:"interval_time"`
  6031. PushLimit int64 `json:"push_limit"`
  6032. TemplateId string `json:"template_id"`
  6033. UsersId string `json:"users_id"`
  6034. DateType int64 `json:"date_type"`
  6035. CycleType int64 `json:"cycle_type"`
  6036. DelayTime int64 `json:"delay_time"`
  6037. Status int64 `json:"status"`
  6038. }
  6039. func UpdateRemind(c *gin.Context) {
  6040. appG := app.Gin{C: c}
  6041. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6042. parammaps := gofasion.NewFasion(string(dataByte))
  6043. // parammaps := fsion.Get("parammaps")
  6044. // user := parammaps.Get("user").ValueStr()
  6045. id := parammaps.Get("id").ValueInt64()
  6046. noticeMsgtype := new(NoticeMsgtype)
  6047. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  6048. noticeMsgtype.ServiceId = id
  6049. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  6050. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  6051. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  6052. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  6053. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  6054. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  6055. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  6056. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  6057. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  6058. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  6059. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  6060. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  6061. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  6062. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  6063. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  6064. //TODO
  6065. noticeMsgtype.SysName = "tmrWatch"
  6066. userList := parammaps.Get("user").Array()
  6067. var userstr []string
  6068. for _, user := range userList {
  6069. userstr = append(userstr, user.ValueStr())
  6070. }
  6071. tx := restful.Engine.NewSession()
  6072. defer tx.Close()
  6073. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  6074. if err != nil {
  6075. logs.Error(err)
  6076. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6077. return
  6078. }
  6079. // var jsonStr = []byte(noticeMsgtype
  6080. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  6081. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  6082. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  6083. req.Header.Set("Content-Type", "application/json")
  6084. client := &http.Client{}
  6085. resp, err := client.Do(req)
  6086. if err != nil {
  6087. logs.Error(err)
  6088. }
  6089. defer resp.Body.Close()
  6090. body, _ := ioutil.ReadAll(resp.Body)
  6091. fmt.Println("response Body:", string(body))
  6092. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  6093. if err != nil {
  6094. logs.Error(err)
  6095. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6096. return
  6097. }
  6098. defer getresp.Body.Close()
  6099. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6100. buf.ReadFrom(getresp.Body)
  6101. // fmt.Println(string(buf.Bytes()))
  6102. respMap := make(map[string]interface{}, 0)
  6103. err = json.Unmarshal(buf.Bytes(), &respMap)
  6104. if err != nil {
  6105. logs.Error(err)
  6106. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6107. return
  6108. }
  6109. for _, resp := range respMap["data"].([]interface{}) {
  6110. resp1 := resp.(map[string]interface{})
  6111. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6112. if err != nil {
  6113. logs.Error(err)
  6114. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6115. return
  6116. }
  6117. }
  6118. appG.Response(http.StatusOK, e.SUCCESS, true)
  6119. }
  6120. func GetSpillageallHistory(c *gin.Context) {
  6121. appG := app.Gin{C: c}
  6122. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6123. parammaps := gofasion.NewFasion(string(dataByte))
  6124. barname := parammaps.Get("barname").ValueStr()
  6125. pastureid := parammaps.Get("pastureid").ValueStr()
  6126. startdate := parammaps.Get("startDate").ValueStr()
  6127. enddate := parammaps.Get("endDate").ValueStr()
  6128. tx := restful.Engine.NewSession()
  6129. defer tx.Close()
  6130. 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
  6131. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6132. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6133. if err != nil {
  6134. logs.Error(err)
  6135. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6136. return
  6137. }
  6138. respMap := make([]map[string]interface{}, 0)
  6139. data := make(map[interface{}]interface{})
  6140. for _, history := range historyList {
  6141. data[history["createdate"]] = history["createdate"]
  6142. }
  6143. createList := []string{}
  6144. for _, v := range data {
  6145. createList = append(createList, v.(string))
  6146. }
  6147. // sort.Sort()
  6148. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6149. sort.Slice(createList, func(i, j int) bool {
  6150. return createList[i] > createList[j]
  6151. })
  6152. for _, v := range createList {
  6153. a := make(map[string]interface{})
  6154. a["createdate"] = data[v]
  6155. // createList = append(createList, v.(string))
  6156. respMap = append(respMap, a)
  6157. }
  6158. number := 0
  6159. dataMap := make([]interface{}, 0)
  6160. for k, resp := range respMap {
  6161. createdate := resp["createdate"].(string)
  6162. var nextcreatedate string
  6163. if len(respMap) > k+1 {
  6164. nextcreatedate = respMap[k+1]["createdate"].(string)
  6165. }
  6166. // dataList := make(map[string][]interface{})
  6167. // list := make(map[string]interface{})
  6168. times := make(map[interface{}]int)
  6169. for _, history := range historyList {
  6170. // List := make(map[interface{}][]interface{})
  6171. i := 0
  6172. if history["createdate"].(string) == createdate {
  6173. times[history["times"]]++
  6174. data := make(map[string]interface{})
  6175. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6176. // exist := false
  6177. if nextcreatedate != "" {
  6178. for _, history1 := range historyList {
  6179. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6180. history1["times"].(int64) == history["times"].(int64) {
  6181. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6182. break
  6183. // exist = true
  6184. }
  6185. }
  6186. }
  6187. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6188. i++
  6189. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6190. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6191. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6192. // resp["times"] = history["times"]
  6193. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6194. data1 := make(map[string]interface{})
  6195. data1["times"] = history["times"]
  6196. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6197. data1["createdate"] = resp["createdate"]
  6198. // fmt.Println(dataList)
  6199. dataMap = append(dataMap, data1)
  6200. }
  6201. if i > number {
  6202. number = i
  6203. }
  6204. // respMap = append(respMap, dataList)
  6205. }
  6206. // for k, data := range dataList {
  6207. // resp[k] = data
  6208. // }
  6209. // resp["data"] = dataList
  6210. }
  6211. // resp := make(map[string]interface{})
  6212. // sort.Strings(createList)
  6213. //
  6214. // for _, create := range createList {
  6215. // for _, r := range respMap {
  6216. // if create == r["createdate"].(string) {
  6217. // resp[create] = r
  6218. // break
  6219. // }
  6220. // }
  6221. // }
  6222. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6223. var trainsList []interface{}
  6224. for i := 0; i < number; i++ {
  6225. trains := make(map[string]interface{})
  6226. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6227. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6228. trainsList = append(trainsList, trains)
  6229. }
  6230. respdata := make(map[string]interface{})
  6231. respdata["data"] = dataMap
  6232. respdata["trains"] = trainsList
  6233. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6234. }
  6235. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6236. appG := app.Gin{C: c}
  6237. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6238. parammaps := gofasion.NewFasion(string(dataByte))
  6239. ftid := parammaps.Get("ftid").ValueInt64()
  6240. lastftid := parammaps.Get("lastftid").ValueInt64()
  6241. pastureid := parammaps.Get("pastureid").ValueInt64()
  6242. // createdate := parammaps.Get("createdate").ValueStr()
  6243. tx := restful.Engine.NewSession()
  6244. defer tx.Close()
  6245. data := make(map[string]interface{})
  6246. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6247. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6248. if err != nil {
  6249. logs.Error(err)
  6250. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6251. return
  6252. }
  6253. feedtemplet := make(map[string]interface{})
  6254. for _, f := range feedtempletList {
  6255. feedtemplet = f
  6256. }
  6257. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  6258. if err != nil {
  6259. logs.Error(err)
  6260. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6261. return
  6262. }
  6263. feedtemplet["fit"] = fitList
  6264. data["current"] = feedtemplet
  6265. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6266. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6267. if err != nil {
  6268. logs.Error(err)
  6269. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6270. return
  6271. }
  6272. lastfeedtemplet := make(map[string]interface{})
  6273. for _, f := range lastfeedtempletList {
  6274. lastfeedtemplet = f
  6275. }
  6276. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  6277. if err != nil {
  6278. logs.Error(err)
  6279. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6280. return
  6281. }
  6282. lastfeedtemplet["fit"] = lastfitList
  6283. data["last"] = lastfeedtemplet
  6284. appG.Response(http.StatusOK, e.SUCCESS, data)
  6285. }
  6286. func GetFeedtempletHistory(c *gin.Context) {
  6287. appG := app.Gin{C: c}
  6288. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6289. parammaps := gofasion.NewFasion(string(dataByte))
  6290. ftid := parammaps.Get("ftid").ValueStr()
  6291. pastureid := parammaps.Get("pastureid").ValueInt64()
  6292. start := parammaps.Get("startdate").ValueStr()
  6293. end := parammaps.Get("enddate").ValueStr()
  6294. tx := restful.Engine.NewSession()
  6295. defer tx.Close()
  6296. 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 ?
  6297. and id = ? and pastureid = ? order by createdate desc `,
  6298. start, end, ftid, pastureid).Query().List()
  6299. if err != nil {
  6300. logs.Error(err)
  6301. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6302. return
  6303. }
  6304. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6305. ftid, pastureid).Query().List()
  6306. if err != nil {
  6307. logs.Error(err)
  6308. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6309. return
  6310. }
  6311. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6312. for i, ft := range ftList {
  6313. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6314. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6315. (select empname from user where id = fit.userId) empname,
  6316. 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
  6317. where fit.fitid = ?
  6318. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6319. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6320. if err != nil {
  6321. logs.Error(err)
  6322. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6323. return
  6324. }
  6325. ft["createdate"] = ft["createdate1"]
  6326. // data["tname"] = ft["tname"]
  6327. // data["tcode"] = ft["tcode"]
  6328. // data["tcolor"] = ft["tcolor"]
  6329. // data["fttype"] = ft["fttype"]
  6330. // data["ccname"] = ft["ccname"]
  6331. // data["source"] = ft["source"]
  6332. // data["version"] = ft["version"]
  6333. // data["remark"] = ft["remark"]
  6334. for n, ft2 := range ftList {
  6335. if i < n {
  6336. if ft["tname"].(string) != ft2["tname"].(string) {
  6337. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6338. }
  6339. if _, ok := ft["tcode"]; ok {
  6340. if _, ok := ft2["tcode"]; ok {
  6341. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6342. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6343. }
  6344. }
  6345. }
  6346. if _, ok := ft["tcolor"]; ok {
  6347. if _, ok := ft2["tcolor"]; ok {
  6348. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6349. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6350. }
  6351. }
  6352. }
  6353. if _, ok := ft["fttype"]; ok {
  6354. if _, ok := ft2["fttype"]; ok {
  6355. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6356. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6357. }
  6358. }
  6359. }
  6360. if _, ok := ft["ccname"]; ok {
  6361. if _, ok := ft2["ccname"]; ok {
  6362. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6363. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6364. }
  6365. }
  6366. }
  6367. if _, ok := ft["source"]; ok {
  6368. if _, ok := ft2["source"]; ok {
  6369. if ft["source"].(string) != ft2["source"].(string) {
  6370. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6371. }
  6372. }
  6373. }
  6374. if _, ok := ft["version"]; ok {
  6375. if _, ok := ft2["version"]; ok {
  6376. if ft["version"].(int64) != ft2["version"].(int64) {
  6377. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6378. }
  6379. }
  6380. }
  6381. if _, ok := ft["remark"]; ok {
  6382. if _, ok := ft2["remark"]; ok {
  6383. if ft["remark"].(string) != ft2["remark"].(string) {
  6384. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6385. }
  6386. }
  6387. }
  6388. break
  6389. }
  6390. }
  6391. dataList := make([]map[string]interface{}, 0)
  6392. if len(fithisList) > 0 {
  6393. for _, fit := range fithisList {
  6394. data := make(map[string]interface{})
  6395. data["feedgroup"] = fit["feedgroup"]
  6396. data["fname"] = fit["fname"]
  6397. data["empname"] = fit["empname"]
  6398. if fit["Eweight"] != nil {
  6399. if fit["Eweight"].(string) != fit["weight"].(string) {
  6400. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6401. } else {
  6402. data["fweight"] = fit["Eweight"]
  6403. }
  6404. data["fweightstatus"] = 1
  6405. } else {
  6406. data["fweight"] = fit["weight"]
  6407. data["fweightstatus"] = 0
  6408. }
  6409. data["autosecond"] = fit["autosecond"]
  6410. // data["tname"] = ft["tname"]
  6411. // data["tcode"] = ft["tcode"]
  6412. // data["tcolor"] = ft["tcolor"]
  6413. // data["fttype"] = ft["fttype"]
  6414. // data["ccname"] = ft["ccname"]
  6415. // data["source"] = ft["source"]
  6416. // data["version"] = ft["version"]
  6417. // data["remark"] = ft["remark"]
  6418. // data["createdate"] = ft["createdate1"]
  6419. // ft["fit"] = data
  6420. dataList = append(dataList, data)
  6421. }
  6422. } else {
  6423. for _, fit := range ftdetailList {
  6424. data := make(map[string]interface{})
  6425. data["feedgroup"] = fit["feedgroup"]
  6426. data["fname"] = fit["fname"]
  6427. // if fit["Eweight"] != nil {
  6428. // data["weight"] = fit["Eweight"]
  6429. // } else {
  6430. data["fweight"] = fit["fweight"]
  6431. // }
  6432. data["autosecond"] = fit["autosecond"]
  6433. // ft["fit"] = data
  6434. dataList = append(dataList, data)
  6435. }
  6436. }
  6437. ft["fit"] = dataList
  6438. }
  6439. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6440. }
  6441. func UpdateMaterialTMR(c *gin.Context) {
  6442. appG := app.Gin{C: c}
  6443. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6444. parammaps := gofasion.NewFasion(string(dataByte))
  6445. tmrid := parammaps.Get("tmrid").ValueStr()
  6446. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6447. lppid := parammaps.Get("lppid").ValueStr()
  6448. times := parammaps.Get("times").ValueStr()
  6449. pastureid := parammaps.Get("pastureid").ValueStr()
  6450. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6451. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6452. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6453. tx := restful.Engine.NewSession()
  6454. defer tx.Close()
  6455. tx.Begin()
  6456. if tmrid != "1000" {
  6457. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6458. if err != nil {
  6459. logs.Error(err)
  6460. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6461. return
  6462. }
  6463. var maxstirfeed float64
  6464. for _, tmr := range tmrList {
  6465. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6466. }
  6467. if status == 0 {
  6468. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6469. if err != nil {
  6470. tx.Rollback()
  6471. logs.Error(err)
  6472. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6473. return
  6474. }
  6475. var lweight float64
  6476. for _, item := range lpplandtl1List {
  6477. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6478. lweight += fl
  6479. }
  6480. if lweight > maxstirfeed {
  6481. lweight = lweight - maxstirfeed
  6482. } else {
  6483. lweight = 0
  6484. }
  6485. if lweight > 0 {
  6486. lweight1 := lweight / float64(len(lpplandtl1List))
  6487. number := 0
  6488. for _, item := range lpplandtl1List {
  6489. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6490. if lweight1 >= fl {
  6491. number++
  6492. }
  6493. }
  6494. lweight := lweight / float64((len(lpplandtl1List) - number))
  6495. for _, item := range lpplandtl1List {
  6496. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6497. if lweight1 >= fl {
  6498. continue
  6499. }
  6500. if tmrtype == "1" {
  6501. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6502. if err != nil {
  6503. tx.Rollback()
  6504. logs.Error(err)
  6505. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6506. return
  6507. }
  6508. } else if tmrtype == "2" {
  6509. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6510. if err != nil {
  6511. tx.Rollback()
  6512. logs.Error(err)
  6513. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6514. return
  6515. }
  6516. }
  6517. if item["fttype"].(int64) == 0 {
  6518. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6519. if err != nil {
  6520. tx.Rollback()
  6521. logs.Error(err)
  6522. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6523. return
  6524. }
  6525. } else {
  6526. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6527. if err != nil {
  6528. tx.Rollback()
  6529. logs.Error(err)
  6530. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6531. return
  6532. }
  6533. }
  6534. }
  6535. } else {
  6536. for _, item := range lpplandtl1List {
  6537. // 自走式
  6538. if tmrtype == "1" {
  6539. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6540. if err != nil {
  6541. logs.Error(err)
  6542. tx.Rollback()
  6543. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6544. return
  6545. }
  6546. } else if tmrtype == "2" {
  6547. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6548. if err != nil {
  6549. logs.Error(err)
  6550. tx.Rollback()
  6551. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6552. return
  6553. }
  6554. }
  6555. }
  6556. }
  6557. } else if status == 1 {
  6558. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6559. if err != nil {
  6560. logs.Error(err)
  6561. tx.Rollback()
  6562. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6563. return
  6564. }
  6565. var lweight float64
  6566. for _, item := range lpplandtl1List {
  6567. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6568. lweight += fl
  6569. }
  6570. if lweight > maxstirfeed {
  6571. lweight = lweight - maxstirfeed
  6572. } else {
  6573. lweight = 0
  6574. }
  6575. for _, item := range lpplandtl1List {
  6576. if lweight > 0 {
  6577. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6578. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6579. if fl >= lweight {
  6580. item["lweight"] = fl - lweight
  6581. lweight = 0
  6582. if tmrtype == "1" {
  6583. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6584. if err != nil {
  6585. logs.Error(err)
  6586. tx.Rollback()
  6587. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6588. return
  6589. }
  6590. } else if tmrtype == "2" {
  6591. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6592. if err != nil {
  6593. logs.Error(err)
  6594. tx.Rollback()
  6595. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6596. return
  6597. }
  6598. }
  6599. if item["fttype"].(int64) == 0 {
  6600. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6601. if err != nil {
  6602. logs.Error(err)
  6603. tx.Rollback()
  6604. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6605. return
  6606. }
  6607. } else {
  6608. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6609. if err != nil {
  6610. logs.Error(err)
  6611. tx.Rollback()
  6612. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6613. return
  6614. }
  6615. }
  6616. } else {
  6617. lweight = lweight - fl
  6618. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6619. if err != nil {
  6620. logs.Error(err)
  6621. tx.Rollback()
  6622. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6623. return
  6624. }
  6625. if item["fttype"].(int64) == 0 {
  6626. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6627. if err != nil {
  6628. logs.Error(err)
  6629. tx.Rollback()
  6630. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6631. return
  6632. }
  6633. } else {
  6634. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6635. if err != nil {
  6636. logs.Error(err)
  6637. tx.Rollback()
  6638. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6639. return
  6640. }
  6641. }
  6642. }
  6643. } else {
  6644. // 自走式
  6645. if tmrtype == "1" {
  6646. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6647. if err != nil {
  6648. logs.Error(err)
  6649. tx.Rollback()
  6650. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6651. return
  6652. }
  6653. } else if tmrtype == "2" {
  6654. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6655. if err != nil {
  6656. logs.Error(err)
  6657. tx.Rollback()
  6658. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6659. return
  6660. }
  6661. }
  6662. }
  6663. }
  6664. } else {
  6665. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6666. if err != nil {
  6667. logs.Error(err)
  6668. tx.Rollback()
  6669. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6670. return
  6671. }
  6672. for _, item := range lpplandtl1List {
  6673. if item["fttype"].(int64) == 0 {
  6674. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6675. if err != nil {
  6676. logs.Error(err)
  6677. tx.Rollback()
  6678. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6679. return
  6680. }
  6681. } else {
  6682. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6683. if err != nil {
  6684. logs.Error(err)
  6685. tx.Rollback()
  6686. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6687. return
  6688. }
  6689. }
  6690. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6691. if err != nil {
  6692. logs.Error(err)
  6693. tx.Rollback()
  6694. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6695. return
  6696. }
  6697. }
  6698. }
  6699. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6700. if err != nil {
  6701. logs.Error(err)
  6702. tx.Rollback()
  6703. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6704. return
  6705. }
  6706. } else {
  6707. if status == 2 {
  6708. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6709. if err != nil {
  6710. logs.Error(err)
  6711. tx.Rollback()
  6712. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6713. return
  6714. }
  6715. for _, item := range lpplandtl1List {
  6716. if item["fttype"].(int64) == 0 {
  6717. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6718. if err != nil {
  6719. logs.Error(err)
  6720. tx.Rollback()
  6721. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6722. return
  6723. }
  6724. } else {
  6725. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6726. if err != nil {
  6727. logs.Error(err)
  6728. tx.Rollback()
  6729. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6730. return
  6731. }
  6732. }
  6733. }
  6734. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6735. if err != nil {
  6736. logs.Error(err)
  6737. tx.Rollback()
  6738. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6739. return
  6740. }
  6741. } else {
  6742. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6743. if err != nil {
  6744. logs.Error(err)
  6745. tx.Rollback()
  6746. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6747. return
  6748. }
  6749. }
  6750. }
  6751. err := tx.Commit()
  6752. if err != nil {
  6753. logs.Error(err)
  6754. tx.Rollback()
  6755. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6756. return
  6757. }
  6758. appG.Response(http.StatusOK, e.SUCCESS, true)
  6759. }
  6760. func UpdateMaterialTMRDate(c *gin.Context) {
  6761. appG := app.Gin{C: c}
  6762. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6763. parammaps := gofasion.NewFasion(string(dataByte))
  6764. tmrid := parammaps.Get("tmrid").ValueStr()
  6765. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6766. lppid := parammaps.Get("lppid").ValueStr()
  6767. times := parammaps.Get("times").ValueStr()
  6768. pastureid := parammaps.Get("pastureid").ValueStr()
  6769. date := parammaps.Get("date").ValueStr()
  6770. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6771. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6772. tx := restful.Engine.NewSession()
  6773. defer tx.Close()
  6774. tx.Begin()
  6775. if tmrid != "1000" {
  6776. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6777. if err != nil {
  6778. logs.Error(err)
  6779. tx.Rollback()
  6780. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6781. return
  6782. }
  6783. var maxstirfeed float64
  6784. for _, tmr := range tmrList {
  6785. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6786. }
  6787. if status == 0 {
  6788. 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()
  6789. if err != nil {
  6790. logs.Error(err)
  6791. tx.Rollback()
  6792. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6793. return
  6794. }
  6795. var lweight float64
  6796. for _, item := range lpplandtl1List {
  6797. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6798. lweight += fl
  6799. }
  6800. if lweight > maxstirfeed {
  6801. lweight = lweight - maxstirfeed
  6802. } else {
  6803. lweight = 0
  6804. }
  6805. if lweight > 0 {
  6806. lweight1 := lweight / float64(len(lpplandtl1List))
  6807. number := 0
  6808. for _, item := range lpplandtl1List {
  6809. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6810. if lweight1 >= fl {
  6811. number++
  6812. }
  6813. }
  6814. lweight := lweight / float64((len(lpplandtl1List) - number))
  6815. for _, item := range lpplandtl1List {
  6816. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6817. if lweight1 >= fl {
  6818. continue
  6819. }
  6820. if tmrtype == "1" {
  6821. _, 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()
  6822. if err != nil {
  6823. logs.Error(err)
  6824. tx.Rollback()
  6825. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6826. return
  6827. }
  6828. } else if tmrtype == "2" {
  6829. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6830. if err != nil {
  6831. logs.Error(err)
  6832. tx.Rollback()
  6833. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6834. return
  6835. }
  6836. }
  6837. if item["fttype"].(int64) == 0 {
  6838. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], 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. } else {
  6846. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", 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. }
  6854. }
  6855. } else {
  6856. for _, item := range lpplandtl1List {
  6857. // 自走式
  6858. if tmrtype == "1" {
  6859. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6860. if err != nil {
  6861. logs.Error(err)
  6862. tx.Rollback()
  6863. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6864. return
  6865. }
  6866. } else if tmrtype == "2" {
  6867. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6868. if err != nil {
  6869. logs.Error(err)
  6870. tx.Rollback()
  6871. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6872. return
  6873. }
  6874. }
  6875. }
  6876. }
  6877. } else if status == 1 {
  6878. 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()
  6879. if err != nil {
  6880. logs.Error(err)
  6881. tx.Rollback()
  6882. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6883. return
  6884. }
  6885. var lweight float64
  6886. for _, item := range lpplandtl1List {
  6887. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6888. lweight += fl
  6889. }
  6890. if lweight > maxstirfeed {
  6891. lweight = lweight - maxstirfeed
  6892. } else {
  6893. lweight = 0
  6894. }
  6895. for _, item := range lpplandtl1List {
  6896. if lweight > 0 {
  6897. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6898. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6899. if fl >= lweight {
  6900. item["lweight"] = fl - lweight
  6901. lweight = 0
  6902. if tmrtype == "1" {
  6903. _, 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()
  6904. if err != nil {
  6905. logs.Error(err)
  6906. tx.Rollback()
  6907. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6908. return
  6909. }
  6910. } else if tmrtype == "2" {
  6911. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6912. if err != nil {
  6913. logs.Error(err)
  6914. tx.Rollback()
  6915. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6916. return
  6917. }
  6918. }
  6919. if item["fttype"].(int64) == 0 {
  6920. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6921. if err != nil {
  6922. logs.Error(err)
  6923. tx.Rollback()
  6924. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6925. return
  6926. }
  6927. } else {
  6928. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6929. if err != nil {
  6930. logs.Error(err)
  6931. tx.Rollback()
  6932. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6933. return
  6934. }
  6935. }
  6936. } else {
  6937. lweight = lweight - fl
  6938. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6939. if err != nil {
  6940. logs.Error(err)
  6941. tx.Rollback()
  6942. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6943. return
  6944. }
  6945. if item["fttype"].(int64) == 0 {
  6946. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6947. if err != nil {
  6948. logs.Error(err)
  6949. tx.Rollback()
  6950. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6951. return
  6952. }
  6953. } else {
  6954. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], 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. }
  6962. }
  6963. } else {
  6964. // 自走式
  6965. if tmrtype == "1" {
  6966. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6967. if err != nil {
  6968. logs.Error(err)
  6969. tx.Rollback()
  6970. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6971. return
  6972. }
  6973. } else if tmrtype == "2" {
  6974. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6975. if err != nil {
  6976. logs.Error(err)
  6977. tx.Rollback()
  6978. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6979. return
  6980. }
  6981. }
  6982. }
  6983. }
  6984. } else {
  6985. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6986. if err != nil {
  6987. logs.Error(err)
  6988. tx.Rollback()
  6989. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6990. return
  6991. }
  6992. for _, item := range lpplandtl1List {
  6993. if item["fttype"].(int64) == 0 {
  6994. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6995. if err != nil {
  6996. logs.Error(err)
  6997. tx.Rollback()
  6998. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6999. return
  7000. }
  7001. } else {
  7002. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7003. if err != nil {
  7004. logs.Error(err)
  7005. tx.Rollback()
  7006. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7007. return
  7008. }
  7009. }
  7010. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  7011. if err != nil {
  7012. logs.Error(err)
  7013. tx.Rollback()
  7014. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7015. return
  7016. }
  7017. }
  7018. }
  7019. _, 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()
  7020. if err != nil {
  7021. logs.Error(err)
  7022. tx.Rollback()
  7023. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7024. return
  7025. }
  7026. } else {
  7027. if status == 2 {
  7028. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  7029. if err != nil {
  7030. logs.Error(err)
  7031. tx.Rollback()
  7032. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7033. return
  7034. }
  7035. for _, item := range lpplandtl1List {
  7036. if item["fttype"].(int64) == 0 {
  7037. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7038. if err != nil {
  7039. logs.Error(err)
  7040. tx.Rollback()
  7041. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7042. return
  7043. }
  7044. } else {
  7045. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7046. if err != nil {
  7047. logs.Error(err)
  7048. tx.Rollback()
  7049. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7050. return
  7051. }
  7052. }
  7053. }
  7054. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  7055. if err != nil {
  7056. logs.Error(err)
  7057. tx.Rollback()
  7058. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7059. return
  7060. }
  7061. } else {
  7062. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  7063. if err != nil {
  7064. logs.Error(err)
  7065. tx.Rollback()
  7066. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7067. return
  7068. }
  7069. }
  7070. }
  7071. err := tx.Commit()
  7072. if err != nil {
  7073. logs.Error(err)
  7074. tx.Rollback()
  7075. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7076. return
  7077. }
  7078. appG.Response(http.StatusOK, e.SUCCESS, true)
  7079. }
  7080. func Decimal(value float64) float64 {
  7081. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  7082. return value
  7083. }
  7084. func UpdateDailyData(c *gin.Context) {
  7085. appG := app.Gin{C: c}
  7086. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7087. parammaps := gofasion.NewFasion(string(dataByte))
  7088. pid := parammaps.Get("pid").ValueDefaultStr("0")
  7089. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  7090. sort := parammaps.Get("sort").ValueDefaultStr("0")
  7091. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  7092. date := parammaps.Get("date").ValueStr()
  7093. tx := restful.Engine.NewSession()
  7094. defer tx.Close()
  7095. 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()
  7096. if err != nil {
  7097. logs.Error("UpdateDailyData-error-0:", err)
  7098. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7099. return
  7100. }
  7101. if count > 0 {
  7102. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7103. return
  7104. }
  7105. tx.Begin()
  7106. if location == 0 {
  7107. fid := parammaps.Get("fid").ValueStr()
  7108. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  7109. if err != nil {
  7110. logs.Error("UpdateDailyData-error-1:", err)
  7111. tx.Rollback()
  7112. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7113. return
  7114. }
  7115. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7116. if err != nil {
  7117. logs.Error("UpdateDailyData-error-1:", err)
  7118. tx.Rollback()
  7119. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7120. return
  7121. }
  7122. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7123. if err != nil {
  7124. fmt.Println("Error:", err)
  7125. return
  7126. }
  7127. actualWeight := weight - num
  7128. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7129. if err != nil {
  7130. logs.Error("UpdateDailyData-error-2:", err)
  7131. tx.Rollback()
  7132. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7133. return
  7134. }
  7135. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7136. if err != nil {
  7137. logs.Error("UpdateDailyData-error-3:", err)
  7138. tx.Rollback()
  7139. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7140. return
  7141. }
  7142. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7143. if err != nil {
  7144. logs.Error("UpdateDailyData-error-4:", err)
  7145. tx.Rollback()
  7146. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7147. return
  7148. }
  7149. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7150. if err != nil {
  7151. logs.Error("UpdateDailyData-error-5:", err)
  7152. tx.Rollback()
  7153. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7154. return
  7155. }
  7156. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7157. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7158. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7159. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7160. if err != nil {
  7161. fmt.Println("Error:", err)
  7162. return
  7163. }
  7164. // actual := actualWeight / float64(len(downloadedplanList))
  7165. for _, item := range downloadedplanList {
  7166. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7167. if err != nil {
  7168. fmt.Println("Error:", err)
  7169. return
  7170. }
  7171. actual := itemLweight / lweight * actualWeight
  7172. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7173. if err != nil {
  7174. logs.Error("UpdateDailyData-error-6:", 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 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7180. if err != nil {
  7181. logs.Error("UpdateDailyData-error-7:", err)
  7182. tx.Rollback()
  7183. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7184. return
  7185. }
  7186. _, 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()
  7187. if err != nil {
  7188. logs.Error("UpdateDailyData-error-8:", err)
  7189. tx.Rollback()
  7190. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7191. return
  7192. }
  7193. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7194. if err != nil {
  7195. logs.Error("UpdateDailyData-error-9:", err)
  7196. tx.Rollback()
  7197. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7198. return
  7199. }
  7200. }
  7201. } else {
  7202. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7203. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7204. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7205. // if err != nil {
  7206. // fmt.Println("Error:", err)
  7207. // return
  7208. // }
  7209. for _, item := range downloadedplanList {
  7210. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7211. if err != nil {
  7212. logs.Error("UpdateDailyData-error-6:", err)
  7213. tx.Rollback()
  7214. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7215. return
  7216. }
  7217. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7218. item["lweight"], actualWeight, item["id"]).Execute()
  7219. if err != nil {
  7220. logs.Error("UpdateDailyData-error-7:", err)
  7221. tx.Rollback()
  7222. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7223. return
  7224. }
  7225. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7226. where pid = ?`, item["id"]).Execute()
  7227. if err != nil {
  7228. logs.Error("UpdateDailyData-error-8:", err)
  7229. tx.Rollback()
  7230. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7231. return
  7232. }
  7233. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7234. if err != nil {
  7235. logs.Error("UpdateDailyData-error-9:", err)
  7236. tx.Rollback()
  7237. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7238. return
  7239. }
  7240. }
  7241. }
  7242. } else {
  7243. fbarid := parammaps.Get("fbarid").ValueStr()
  7244. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7245. if err != nil {
  7246. logs.Error("UpdateDailyData-error-10:", err)
  7247. tx.Rollback()
  7248. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7249. return
  7250. }
  7251. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7252. if err != nil {
  7253. logs.Error("UpdateDailyData-error-1:", err)
  7254. tx.Rollback()
  7255. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7256. return
  7257. }
  7258. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7259. if err != nil {
  7260. fmt.Println("Error:", err)
  7261. return
  7262. }
  7263. actualWeight := weight - num
  7264. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7265. if err != nil {
  7266. logs.Error("UpdateDailyData-error-11:", err)
  7267. tx.Rollback()
  7268. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7269. return
  7270. }
  7271. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  7272. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7273. if err != nil {
  7274. logs.Error("UpdateDailyData-error-12:", err)
  7275. tx.Rollback()
  7276. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7277. return
  7278. }
  7279. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7280. where pid = ? `, pid).Execute()
  7281. if err != nil {
  7282. logs.Error("UpdateDailyData-error-13:", err)
  7283. tx.Rollback()
  7284. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7285. return
  7286. }
  7287. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7288. if err != nil {
  7289. logs.Error("UpdateDailyData-error-14:", err)
  7290. tx.Rollback()
  7291. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7292. return
  7293. }
  7294. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7295. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7296. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7297. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7298. if err != nil {
  7299. fmt.Println("Error:", err)
  7300. return
  7301. }
  7302. for _, item := range downloadedplanList {
  7303. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7304. if err != nil {
  7305. fmt.Println("Error:", err)
  7306. return
  7307. }
  7308. actual := itemLweight / lweight * actualWeight
  7309. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7310. if err != nil {
  7311. logs.Error("UpdateDailyData-error-6:", err)
  7312. tx.Rollback()
  7313. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7314. return
  7315. }
  7316. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7317. if err != nil {
  7318. logs.Error("UpdateDailyData-error-7:", err)
  7319. tx.Rollback()
  7320. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7321. return
  7322. }
  7323. _, 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()
  7324. if err != nil {
  7325. logs.Error("UpdateDailyData-error-8:", err)
  7326. tx.Rollback()
  7327. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7328. return
  7329. }
  7330. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7331. if err != nil {
  7332. logs.Error("UpdateDailyData-error-9:", err)
  7333. tx.Rollback()
  7334. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7335. return
  7336. }
  7337. }
  7338. } else {
  7339. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7340. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7341. for _, item := range downloadedplanList {
  7342. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7343. // if err != nil {
  7344. // fmt.Println("Error:", err)
  7345. // return
  7346. // }
  7347. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7348. if err != nil {
  7349. logs.Error("UpdateDailyData-error-6:", err)
  7350. tx.Rollback()
  7351. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7352. return
  7353. }
  7354. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7355. item["lweight"], actualWeight, item["id"]).Execute()
  7356. if err != nil {
  7357. logs.Error("UpdateDailyData-error-7:", err)
  7358. tx.Rollback()
  7359. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7360. return
  7361. }
  7362. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7363. where pid = ?`, item["id"]).Execute()
  7364. if err != nil {
  7365. logs.Error("UpdateDailyData-error-8:", err)
  7366. tx.Rollback()
  7367. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7368. return
  7369. }
  7370. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7371. if err != nil {
  7372. logs.Error("UpdateDailyData-error-9:", err)
  7373. tx.Rollback()
  7374. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7375. return
  7376. }
  7377. }
  7378. }
  7379. }
  7380. err = tx.Commit()
  7381. if err != nil {
  7382. logs.Error("UpdateDailyData-error-20:", err)
  7383. tx.Rollback()
  7384. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7385. return
  7386. }
  7387. appG.Response(http.StatusOK, e.SUCCESS, true)
  7388. }
  7389. func GetFormulaStatistics(c *gin.Context) {
  7390. appG := app.Gin{C: c}
  7391. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7392. parammaps := gofasion.NewFasion(string(dataByte))
  7393. startTime := parammaps.Get("startTime").ValueStr()
  7394. endTime := parammaps.Get("endTime").ValueStr()
  7395. pastureId := parammaps.Get("pastureId").ValueStr()
  7396. tx := restful.Engine.NewSession()
  7397. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7398. if err != nil {
  7399. logs.Error("GetFormulaStatistics-error-1:", err)
  7400. tx.Rollback()
  7401. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7402. return
  7403. }
  7404. var feedtemplet, dateList []string
  7405. for _, f := range feedtempletList {
  7406. feedtemplet = append(feedtemplet, f["tname"].(string))
  7407. }
  7408. layout := "2006-01-02"
  7409. // s := "2023-05-01"
  7410. // e := "2023-05-23"
  7411. start, err := time.Parse(layout, startTime)
  7412. if err != nil {
  7413. fmt.Println(err)
  7414. return
  7415. }
  7416. end, err := time.Parse(layout, endTime)
  7417. if err != nil {
  7418. fmt.Println(err)
  7419. return
  7420. }
  7421. end = end.AddDate(0, 0, 1)
  7422. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7423. dateList = append(dateList, d.Format("2006-01-02"))
  7424. }
  7425. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7426. 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= ?
  7427. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7428. if err != nil {
  7429. logs.Error("GetFormulaStatistics-error-2:", err)
  7430. tx.Rollback()
  7431. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7432. return
  7433. }
  7434. var data2 [][]interface{}
  7435. for _, f := range feedtemplet {
  7436. var data1 []interface{}
  7437. for _, date := range dateList {
  7438. exist := false
  7439. for _, item := range downloadedplanList {
  7440. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7441. data1 = append(data1, item["total"])
  7442. exist = true
  7443. break
  7444. }
  7445. }
  7446. if !exist {
  7447. data1 = append(data1, 0)
  7448. }
  7449. }
  7450. data2 = append(data2, data1)
  7451. }
  7452. //前端让加的
  7453. feedtemplet = append(feedtemplet, "")
  7454. {
  7455. var data1 []interface{}
  7456. for _, f := range dateList {
  7457. // f = f + "\n"
  7458. fmt.Println(f)
  7459. data1 = append(data1, 0)
  7460. }
  7461. data2 = append(data2, data1)
  7462. }
  7463. resp := make(map[string]interface{}, 0)
  7464. resp["xdata"] = dateList
  7465. resp["data1"] = feedtemplet
  7466. resp["data2"] = data2
  7467. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7468. }
  7469. func GetPlanData(c *gin.Context) {
  7470. appG := app.Gin{C: c}
  7471. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7472. fsion := gofasion.NewFasion(string(dataByte))
  7473. sqlnamestr := fsion.Get("name").ValueStr()
  7474. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7475. offset := fsion.Get("offset").ValueDefaultInt(0)
  7476. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7477. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7478. month := fsion.Get("month").ValueDefaultStr("map")
  7479. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7480. tx := restful.Engine.NewSession()
  7481. err := tx.Begin()
  7482. defer func() {
  7483. switch {
  7484. case err != nil:
  7485. if tx != nil {
  7486. tx.Rollback()
  7487. }
  7488. default:
  7489. if tx != nil {
  7490. err = tx.Commit()
  7491. }
  7492. }
  7493. if tx != nil {
  7494. tx.Close()
  7495. }
  7496. }()
  7497. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7498. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7499. if sql != "" {
  7500. s_params := make([]interface{}, 0)
  7501. if fsion.HasKey("parammaps") {
  7502. parammaps := fsion.Get("parammaps")
  7503. paramslist := strings.Split(p, ",")
  7504. if len(paramslist) > 0 && p != "" {
  7505. for _, value := range paramslist {
  7506. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7507. if tempv, exists := c.Get("jwt_username"); exists {
  7508. s_params = append(s_params, tempv.(string))
  7509. } else {
  7510. s_params = append(s_params, "")
  7511. }
  7512. } else {
  7513. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7514. }
  7515. }
  7516. }
  7517. }
  7518. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7519. if err != nil {
  7520. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7521. } else {
  7522. paramslist1 := strings.Split(p1, ",")
  7523. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7524. s_params1 := make([]interface{}, 0)
  7525. if len(paramslist1) > 0 && p1 != "" {
  7526. for _, v := range paramslist1 {
  7527. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7528. }
  7529. }
  7530. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7531. for _, item := range arr {
  7532. trgaddressList := []string{}
  7533. if _, ok := item["trgaddress"]; ok {
  7534. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7535. for _, str := range trgaddressList1 {
  7536. if str != "" {
  7537. trgaddressList = append(trgaddressList, str)
  7538. }
  7539. }
  7540. }
  7541. item["trgaddressList"] = trgaddressList
  7542. }
  7543. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7544. }
  7545. // var wg sync.WaitGroup
  7546. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7547. // wg.Add(1)
  7548. // go func(value map[string]interface{}) {
  7549. // defer wg.Done()
  7550. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7551. // }(value)
  7552. // }
  7553. // wg.Wait()
  7554. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7555. }
  7556. } else {
  7557. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7558. }
  7559. }
  7560. func PostPlanData(c *gin.Context) {
  7561. appG := app.Gin{C: c}
  7562. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7563. fsion := gofasion.NewFasion(string(dataByte))
  7564. logging.Info("PostRJSBData err: ", string(dataByte))
  7565. s_params := make([]interface{}, 0)
  7566. tx := restful.Engine.NewSession()
  7567. err := tx.Begin()
  7568. defer func() {
  7569. switch {
  7570. case err != nil:
  7571. if tx != nil {
  7572. tx.Rollback()
  7573. }
  7574. default:
  7575. if tx != nil {
  7576. err = tx.Commit()
  7577. }
  7578. }
  7579. if tx != nil {
  7580. tx.Close()
  7581. }
  7582. }()
  7583. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7584. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7585. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7586. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7587. if !fsion.HasKey("parammaps") {
  7588. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7589. return
  7590. }
  7591. parammaps := fsion.Get("parammaps")
  7592. // paramslist := strings.Split(p, ",")
  7593. // if len(paramslist) > 0 && p != "" {
  7594. // for _, value := range paramslist {
  7595. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7596. // }
  7597. // }
  7598. // _, err = tx.SQL(sql, s_params...).Execute()
  7599. // if err != nil {
  7600. // logging.Error("PostRJSBData err: ", err)
  7601. // msg := geterrmsg(err.Error())
  7602. // appG.Response(http.StatusOK, e.ERROR, msg)
  7603. // return
  7604. // }
  7605. s_params = make([]interface{}, 0)
  7606. paramslist := strings.Split(p1, ",")
  7607. if len(paramslist) > 0 && p1 != "" {
  7608. for _, value := range paramslist {
  7609. // if value == "ID" {
  7610. // id := parammaps.Get("ID").ValueStr()
  7611. // pastureid := parammaps.Get("pastureid").ValueStr()
  7612. // 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
  7613. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7614. // if err != nil {
  7615. // logging.Error("PostRJSBData err: ", err)
  7616. // msg := geterrmsg(err.Error())
  7617. // appG.Response(http.StatusOK, e.ERROR, msg)
  7618. // return
  7619. // }
  7620. // for _, item := range datalist {
  7621. // id = item["id"]
  7622. // }
  7623. // s_params = append(s_params, id)
  7624. // } else {
  7625. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7626. // }
  7627. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7628. }
  7629. }
  7630. _, err = tx.SQL(sql1, s_params...).Execute()
  7631. if err != nil {
  7632. logging.Error("PostRJSBData1 err: ", err)
  7633. msg := geterrmsg(err.Error())
  7634. appG.Response(http.StatusOK, e.ERROR, msg)
  7635. return
  7636. }
  7637. s_params = make([]interface{}, 0)
  7638. paramslist = strings.Split(p2, ",")
  7639. if len(paramslist) > 0 && p2 != "" {
  7640. for _, value := range paramslist {
  7641. if value == "ID" {
  7642. id := parammaps.Get("ID").ValueStr()
  7643. pastureid := parammaps.Get("pastureid").ValueStr()
  7644. 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
  7645. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7646. if err != nil {
  7647. logging.Error("PostRJSBData err: ", err)
  7648. msg := geterrmsg(err.Error())
  7649. appG.Response(http.StatusOK, e.ERROR, msg)
  7650. return
  7651. }
  7652. for _, item := range datalist {
  7653. id = item["id"]
  7654. }
  7655. s_params = append(s_params, id)
  7656. } else {
  7657. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7658. }
  7659. }
  7660. }
  7661. _, err = tx.SQL(sql2, s_params...).Execute()
  7662. if err != nil {
  7663. logging.Error("PostRJSBData2 err: ", err)
  7664. msg := geterrmsg(err.Error())
  7665. appG.Response(http.StatusOK, e.ERROR, msg)
  7666. return
  7667. }
  7668. s_params = make([]interface{}, 0)
  7669. paramslist = strings.Split(p3, ",")
  7670. if len(paramslist) > 0 && p3 != "" {
  7671. for _, value := range paramslist {
  7672. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7673. }
  7674. }
  7675. _, err = tx.SQL(sql3, s_params...).Execute()
  7676. if err != nil {
  7677. logging.Error("PostRJSBData3 err: ", err)
  7678. msg := geterrmsg(err.Error())
  7679. appG.Response(http.StatusOK, e.ERROR, msg)
  7680. return
  7681. }
  7682. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7683. }
  7684. func CheckFeedTrgaddress(c *gin.Context) {
  7685. appG := app.Gin{C: c}
  7686. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7687. fsion := gofasion.NewFasion(string(dataByte))
  7688. fclassid := fsion.Get("fclassid").ValueStr()
  7689. feedId := fsion.Get("feedId").ValueStr()
  7690. backup1 := fsion.Get("backup1").ValueStr()
  7691. backup1List := strings.Split(backup1, ",")
  7692. tx := restful.Engine.NewSession()
  7693. defer tx.Close()
  7694. // if backup1 != "" {
  7695. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7696. for _, feed := range feedList {
  7697. if feed["backup1"] == "" {
  7698. continue
  7699. }
  7700. feedbackupList := strings.Split(feed["backup1"], ",")
  7701. for _, feedbackup := range feedbackupList {
  7702. for _, backup := range backup1List {
  7703. if feedbackup == backup {
  7704. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7705. return
  7706. }
  7707. }
  7708. }
  7709. }
  7710. // }
  7711. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7712. }
  7713. func ThiGetDataByName(c *gin.Context) {
  7714. appG := app.Gin{C: c}
  7715. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7716. fsion := gofasion.NewFasion(string(dataByte))
  7717. sqlnamestr := fsion.Get("name").ValueStr()
  7718. offset := fsion.Get("offset").ValueDefaultInt(0)
  7719. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7720. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7721. tx := restful.Engine.NewSession()
  7722. err := tx.Begin()
  7723. defer func() {
  7724. switch {
  7725. case err != nil:
  7726. logging.Error("tx.Begin 事务启动失败__error:", err)
  7727. if tx != nil {
  7728. tx.Rollback()
  7729. }
  7730. default:
  7731. if tx != nil {
  7732. err = tx.Commit()
  7733. }
  7734. }
  7735. if tx != nil {
  7736. tx.Close()
  7737. }
  7738. }()
  7739. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7740. if sql != "" {
  7741. s_params := make([]interface{}, 0)
  7742. if fsion.HasKey("parammaps") {
  7743. parammaps := fsion.Get("parammaps")
  7744. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7745. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7746. }
  7747. paramslist := strings.Split(p, ",")
  7748. if len(paramslist) > 0 && p != "" {
  7749. for _, value := range paramslist {
  7750. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7751. if tempv, exists := c.Get("jwt_username"); exists {
  7752. s_params = append(s_params, tempv.(string))
  7753. } else {
  7754. s_params = append(s_params, "")
  7755. }
  7756. } else {
  7757. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7758. }
  7759. }
  7760. }
  7761. } else if fsion.HasKey("params") {
  7762. params := fsion.Get("params").Array()
  7763. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7764. for _, v_params := range params {
  7765. s_params = append(s_params, v_params.ValueStr())
  7766. }
  7767. }
  7768. if returntype == "xlsx" {
  7769. var xlsxfile *xlsx.File
  7770. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7771. //c.File("c:/dd.xlsx")
  7772. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7773. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7774. c.Header("Content-Transfer-Encoding", "binary")
  7775. _ = xlsxfile.Write(c.Writer)
  7776. } else {
  7777. if sqlnamestr == "getHomepageStr" {
  7778. parammaps := fsion.Get("parammaps")
  7779. pastureid := parammaps.Get("pastureid").ValueStr()
  7780. var montimeList []float64
  7781. var montime float64
  7782. var wg sync.WaitGroup
  7783. now := time.Now()
  7784. for i := 0; i < 30; i++ {
  7785. wg.Add(1)
  7786. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7787. go func(nowstr string) {
  7788. defer wg.Done()
  7789. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7790. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7791. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7792. montimeList = append(montimeList, m)
  7793. }(nowstr)
  7794. }
  7795. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7796. if err != nil {
  7797. logging.Error("GetDataByName err: ", err)
  7798. msg := geterrmsg(err.Error())
  7799. appG.Response(http.StatusOK, e.ERROR, msg)
  7800. }
  7801. wg.Wait()
  7802. for _, m := range montimeList {
  7803. montime += m
  7804. }
  7805. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7806. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7807. return
  7808. }
  7809. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7810. if err != nil {
  7811. logging.Error("GetDataByName err: ", err)
  7812. msg := geterrmsg(err.Error())
  7813. appG.Response(http.StatusOK, e.ERROR, msg)
  7814. } else {
  7815. if sqlnamestr == "getFeedTrgaddressList" {
  7816. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7817. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7818. trgaddressList := []string{}
  7819. for _, str := range trgaddressList1 {
  7820. if str != "" {
  7821. trgaddressList = append(trgaddressList, str)
  7822. }
  7823. }
  7824. item["trgaddressList"] = trgaddressList
  7825. }
  7826. }
  7827. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7828. }
  7829. }
  7830. } else {
  7831. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7832. }
  7833. }
  7834. // func ToggleCcount(c *gin.Context) {
  7835. // appG := app.Gin{C: c}
  7836. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7837. // fsion := gofasion.NewFasion(string(dataByte))
  7838. // // 0 实际 1 软件
  7839. // status := fsion.Get("status").ValueDefaultInt64(0)
  7840. // pastureId := fsion.Get("pastureId").ValueStr()
  7841. // tx := restful.Engine.NewSession()
  7842. // err := tx.Begin()
  7843. // defer func() {
  7844. // switch {
  7845. // case err != nil:
  7846. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7847. // if tx != nil {
  7848. // tx.Rollback()
  7849. // }
  7850. // default:
  7851. // if tx != nil {
  7852. // err = tx.Commit()
  7853. // }
  7854. // }
  7855. // if tx != nil {
  7856. // tx.Close()
  7857. // }
  7858. // }()
  7859. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7860. // if err != nil {
  7861. // logs.Error(err)
  7862. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7863. // return
  7864. // }
  7865. // for _, bar := range barList {
  7866. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7867. // if err != nil {
  7868. // logs.Error(err)
  7869. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7870. // return
  7871. // }
  7872. // if !exist {
  7873. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7874. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7875. // if err != nil {
  7876. // logs.Error(err)
  7877. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7878. // return
  7879. // }
  7880. // }
  7881. // }
  7882. // if status == 0 {
  7883. // tx.Exec(`update feedp set ccount = actualcount `)
  7884. // }else{
  7885. // tx.Exec(`update feedp set ccount = softccount `)
  7886. // }
  7887. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7888. // if err != nil {
  7889. // logs.Error(err)
  7890. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7891. // return
  7892. // }
  7893. // for _, feedpData :=range feedpList{
  7894. // var feedpargs []interface{}
  7895. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7896. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7897. // if _, ok := feedpData["ftname"]; ok {
  7898. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7899. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7900. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7901. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7902. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7903. // } else {
  7904. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7905. // }
  7906. // if _, ok := feedpData["ptsfname"]; ok {
  7907. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7908. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7909. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7910. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7911. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7912. // } else {
  7913. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7914. // }
  7915. // upFeedpSql += " where barname = ? and pastureid = ? "
  7916. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7917. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7918. // if err != nil {
  7919. // logs.Error(err)
  7920. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7921. // return
  7922. // }
  7923. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7924. // if err != nil {
  7925. // logs.Error(err)
  7926. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7927. // return
  7928. // }
  7929. // if !exist1 {
  7930. // _, 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) `,
  7931. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7932. // if err != nil {
  7933. // logs.Error(err)
  7934. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7935. // return
  7936. // }
  7937. // }
  7938. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7939. // if err != nil {
  7940. // logs.Error(err)
  7941. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7942. // return
  7943. // }
  7944. // if !exist2 {
  7945. // _, 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) `,
  7946. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7947. // if err != nil {
  7948. // logs.Error(err)
  7949. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7950. // return
  7951. // }
  7952. // }
  7953. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7954. // if err != nil {
  7955. // logs.Error(err)
  7956. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7957. // return
  7958. // }
  7959. // if !exist3 {
  7960. // _, 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) `,
  7961. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7962. // if err != nil {
  7963. // logs.Error(err)
  7964. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7965. // return
  7966. // }
  7967. // }
  7968. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7969. // if err != nil {
  7970. // logs.Error(err)
  7971. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7972. // return
  7973. // }
  7974. // if !exist4 {
  7975. // _, 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) `,
  7976. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7977. // if err != nil {
  7978. // logs.Error(err)
  7979. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7980. // return
  7981. // }
  7982. // }
  7983. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7984. // if err != nil {
  7985. // logs.Error(err)
  7986. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7987. // return
  7988. // }
  7989. // if !exist5 {
  7990. // _, 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) `,
  7991. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7992. // if err != nil {
  7993. // logs.Error(err)
  7994. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7995. // return
  7996. // }
  7997. // }
  7998. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7999. // if err != nil {
  8000. // logs.Error(err)
  8001. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8002. // return
  8003. // }
  8004. // if !exist6 {
  8005. // _, 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) `,
  8006. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  8007. // if err != nil {
  8008. // logs.Error(err)
  8009. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8010. // return
  8011. // }
  8012. // }
  8013. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8014. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8015. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8016. // and pastureid = ? and times = ?`
  8017. // var fpdargs1 []interface{}
  8018. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8019. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8020. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8021. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8022. // if err != nil {
  8023. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8024. // return
  8025. // }
  8026. // var fpdargs2 []interface{}
  8027. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8028. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8029. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8030. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8031. // if err != nil {
  8032. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8033. // return
  8034. // }
  8035. // var fpdargs3 []interface{}
  8036. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8037. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8038. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8039. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8040. // if err != nil {
  8041. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8042. // return
  8043. // }
  8044. // var fpdargs4 []interface{}
  8045. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8046. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8047. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8048. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8049. // if err != nil {
  8050. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8051. // return
  8052. // }
  8053. // var fpdargs5 []interface{}
  8054. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8055. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8056. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8057. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8058. // if err != nil {
  8059. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8060. // return
  8061. // }
  8062. // var fpdargs6 []interface{}
  8063. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8064. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8065. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8066. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8067. // if err != nil {
  8068. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8069. // return
  8070. // }
  8071. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8072. // 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()
  8073. // if err != nil {
  8074. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8075. // return
  8076. // }
  8077. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8078. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8079. // upFpdetailList := make([]*upFpdetail, 0)
  8080. // for _, newfpd := range newList {
  8081. // for _, oldfpd := range oldFpdList {
  8082. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8083. // var oldweight, newweight float64
  8084. // if oldfpd["weight"] != nil {
  8085. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8086. // }
  8087. // if newfpd["weight"] != nil {
  8088. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8089. // }
  8090. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8091. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  8092. // Old: oldweight,
  8093. // New: newweight,
  8094. // Times: newfpd["times"].(int64),
  8095. // Ptid: newfpd["ptid"].(int64),
  8096. // Fweight: fweight,
  8097. // Id: oldfpd["id"].(int64),
  8098. // })
  8099. // break
  8100. // }
  8101. // }
  8102. // }
  8103. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8104. // }
  8105. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8106. // }
  8107. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8108. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8109. if err != nil {
  8110. return err
  8111. }
  8112. for _, item := range feedpList {
  8113. // if item["ftid"].(string) != data["ftid"].(string) {
  8114. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8115. if err != nil {
  8116. return err
  8117. }
  8118. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8119. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8120. if err != nil {
  8121. return err
  8122. }
  8123. // }
  8124. }
  8125. return nil
  8126. }
  8127. func PostPlanDatas(c *gin.Context) {
  8128. appG := app.Gin{C: c}
  8129. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8130. fsions := gofasion.NewFasion(string(dataByte))
  8131. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8132. tx := restful.Engine.NewSession()
  8133. err := tx.Begin()
  8134. defer func() {
  8135. switch {
  8136. case err != nil:
  8137. if tx != nil {
  8138. tx.Rollback()
  8139. }
  8140. default:
  8141. if tx != nil {
  8142. err = tx.Commit()
  8143. }
  8144. }
  8145. if tx != nil {
  8146. tx.Close()
  8147. }
  8148. }()
  8149. pastureId := fsions.Get("pastureid").ValueStr()
  8150. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8151. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8152. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8153. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8154. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8155. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8156. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8157. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8158. for _, parammaps := range fsions.Get("arrList").Array() {
  8159. fmt.Println(parammaps.Json())
  8160. if parammaps.Json() == "null" {
  8161. continue
  8162. }
  8163. // if !fsion.HasKey("arrList") {
  8164. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8165. // return
  8166. // continue
  8167. // }
  8168. // parammaps := fsion.Get("arrList")
  8169. s_params := make([]interface{}, 0)
  8170. // paramslist := strings.Split(p, ",")
  8171. // if len(paramslist) > 0 && p != "" {
  8172. // for _, value := range paramslist {
  8173. // if value == "pastureid" {
  8174. // s_params = append(s_params, pastureId)
  8175. // } else {
  8176. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8177. // }
  8178. // }
  8179. // }
  8180. // _, err = tx.SQL(sql, s_params...).Execute()
  8181. // if err != nil {
  8182. // logging.Error("PostRJSBData err: ", err)
  8183. // msg := geterrmsg(err.Error())
  8184. // appG.Response(http.StatusOK, e.ERROR, msg)
  8185. // return
  8186. // }
  8187. s_params = make([]interface{}, 0)
  8188. paramslist := strings.Split(p1, ",")
  8189. if len(paramslist) > 0 && p1 != "" {
  8190. for _, value := range paramslist {
  8191. // if value == "ID" {
  8192. // id := parammaps.Get("ID").ValueStr()
  8193. // pastureid := parammaps.Get("pastureid").ValueStr()
  8194. // 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
  8195. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8196. // if err != nil {
  8197. // logging.Error("PostRJSBData err: ", err)
  8198. // msg := geterrmsg(err.Error())
  8199. // appG.Response(http.StatusOK, e.ERROR, msg)
  8200. // return
  8201. // }
  8202. // for _, item := range datalist {
  8203. // id = item["id"]
  8204. // }
  8205. // s_params = append(s_params, id)
  8206. // } else {
  8207. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8208. // }
  8209. if value == "pastureid" {
  8210. s_params = append(s_params, pastureId)
  8211. } else {
  8212. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8213. }
  8214. }
  8215. }
  8216. _, err = tx.SQL(sql1, s_params...).Execute()
  8217. if err != nil {
  8218. logging.Error("PostRJSBData1 err: ", err)
  8219. msg := geterrmsg(err.Error())
  8220. appG.Response(http.StatusOK, e.ERROR, msg)
  8221. return
  8222. }
  8223. s_params = make([]interface{}, 0)
  8224. paramslist = strings.Split(p2, ",")
  8225. if len(paramslist) > 0 && p2 != "" {
  8226. for _, value := range paramslist {
  8227. if value == "ID" {
  8228. id := parammaps.Get("ID").ValueStr()
  8229. pastureid := parammaps.Get("pastureid").ValueStr()
  8230. 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
  8231. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8232. if err != nil {
  8233. logging.Error("PostRJSBData err: ", err)
  8234. msg := geterrmsg(err.Error())
  8235. appG.Response(http.StatusOK, e.ERROR, msg)
  8236. return
  8237. }
  8238. for _, item := range datalist {
  8239. id = item["id"]
  8240. }
  8241. s_params = append(s_params, id)
  8242. } else if value == "pastureid" {
  8243. s_params = append(s_params, pastureId)
  8244. } else {
  8245. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8246. }
  8247. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8248. }
  8249. }
  8250. _, err = tx.SQL(sql2, s_params...).Execute()
  8251. if err != nil {
  8252. logging.Error("PostRJSBData2 err: ", err)
  8253. msg := geterrmsg(err.Error())
  8254. appG.Response(http.StatusOK, e.ERROR, msg)
  8255. return
  8256. }
  8257. s_params = make([]interface{}, 0)
  8258. paramslist = strings.Split(p3, ",")
  8259. if len(paramslist) > 0 && p3 != "" {
  8260. for _, value := range paramslist {
  8261. if value == "pastureid" {
  8262. s_params = append(s_params, pastureId)
  8263. } else {
  8264. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8265. }
  8266. }
  8267. }
  8268. _, err = tx.SQL(sql3, s_params...).Execute()
  8269. if err != nil {
  8270. logging.Error("PostRJSBData3 err: ", err)
  8271. msg := geterrmsg(err.Error())
  8272. appG.Response(http.StatusOK, e.ERROR, msg)
  8273. return
  8274. }
  8275. }
  8276. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8277. }
  8278. func FpdBatchEdit(c *gin.Context) {
  8279. appG := app.Gin{C: c}
  8280. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8281. fsions := gofasion.NewFasion(string(dataByte))
  8282. barList := fsions.Get("barList").Array()
  8283. pastureid := fsions.Get("pastureId").ValueStr()
  8284. tx := restful.Engine.NewSession()
  8285. defer tx.Close()
  8286. 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
  8287. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8288. if err != nil {
  8289. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8290. return
  8291. }
  8292. for _, barFsions := range barList {
  8293. dataexcel := make(map[string]interface{}, 0)
  8294. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8295. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8296. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8297. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8298. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8299. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8300. continue
  8301. }
  8302. // /*
  8303. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8304. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8305. if err != nil {
  8306. logs.Error(err)
  8307. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8308. return
  8309. }
  8310. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8311. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8312. if err != nil {
  8313. logs.Error(err)
  8314. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8315. return
  8316. }
  8317. // */
  8318. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8319. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8320. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8321. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8322. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8323. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8324. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8325. if err != nil {
  8326. logs.Error(err)
  8327. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8328. return
  8329. }
  8330. if !ftexist {
  8331. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8332. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8333. if err != nil {
  8334. logs.Error(err)
  8335. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8336. return
  8337. }
  8338. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8339. if err != nil {
  8340. logs.Error(err)
  8341. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8342. return
  8343. }
  8344. }
  8345. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8346. if err != nil {
  8347. logs.Error(err)
  8348. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8349. return
  8350. }
  8351. if !exist {
  8352. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8353. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8354. if err != nil {
  8355. logs.Error(err)
  8356. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8357. return
  8358. }
  8359. }
  8360. var feedpargs []interface{}
  8361. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8362. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8363. if _, ok := dataexcel["ftname"]; ok {
  8364. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8365. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8366. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8367. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8368. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8369. } else {
  8370. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8371. }
  8372. if _, ok := dataexcel["ptsfname"]; ok {
  8373. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8374. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8375. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8376. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8377. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8378. } else {
  8379. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8380. }
  8381. upFeedpSql += " where barname = ? and pastureid = ? "
  8382. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8383. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8384. if err != nil {
  8385. logs.Error(err)
  8386. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8387. return
  8388. }
  8389. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8390. if err != nil {
  8391. logs.Error(err)
  8392. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8393. return
  8394. }
  8395. if !exist1 {
  8396. _, 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) `,
  8397. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8398. if err != nil {
  8399. logs.Error(err)
  8400. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8401. return
  8402. }
  8403. }
  8404. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8405. if err != nil {
  8406. logs.Error(err)
  8407. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8408. return
  8409. }
  8410. if !exist2 {
  8411. _, 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) `,
  8412. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8413. if err != nil {
  8414. logs.Error(err)
  8415. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8416. return
  8417. }
  8418. }
  8419. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8420. if err != nil {
  8421. logs.Error(err)
  8422. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8423. return
  8424. }
  8425. if !exist3 {
  8426. _, 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) `,
  8427. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8428. if err != nil {
  8429. logs.Error(err)
  8430. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8431. return
  8432. }
  8433. }
  8434. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8435. if err != nil {
  8436. logs.Error(err)
  8437. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8438. return
  8439. }
  8440. if !exist4 {
  8441. _, 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) `,
  8442. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8443. if err != nil {
  8444. logs.Error(err)
  8445. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8446. return
  8447. }
  8448. }
  8449. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8450. if err != nil {
  8451. logs.Error(err)
  8452. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8453. return
  8454. }
  8455. if !exist5 {
  8456. _, 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) `,
  8457. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8458. if err != nil {
  8459. logs.Error(err)
  8460. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8461. return
  8462. }
  8463. }
  8464. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8465. if err != nil {
  8466. logs.Error(err)
  8467. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8468. return
  8469. }
  8470. if !exist6 {
  8471. _, 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) `,
  8472. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8473. if err != nil {
  8474. logs.Error(err)
  8475. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8476. return
  8477. }
  8478. }
  8479. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8480. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8481. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8482. and pastureid = ? and times = ?`
  8483. var fpdargs1 []interface{}
  8484. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8485. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8486. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8487. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8488. if err != nil {
  8489. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8490. return
  8491. }
  8492. var fpdargs2 []interface{}
  8493. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8494. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8495. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8496. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8497. if err != nil {
  8498. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8499. return
  8500. }
  8501. var fpdargs3 []interface{}
  8502. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8503. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8504. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8505. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8506. if err != nil {
  8507. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8508. return
  8509. }
  8510. var fpdargs4 []interface{}
  8511. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8512. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8513. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8514. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8515. if err != nil {
  8516. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8517. return
  8518. }
  8519. var fpdargs5 []interface{}
  8520. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8521. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8522. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8523. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8524. if err != nil {
  8525. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8526. return
  8527. }
  8528. var fpdargs6 []interface{}
  8529. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8530. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8531. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8532. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8533. if err != nil {
  8534. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8535. return
  8536. }
  8537. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8538. 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()
  8539. if err != nil {
  8540. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8541. return
  8542. }
  8543. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8544. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8545. upFpdetailList := make([]*upFpdetail, 0)
  8546. for _, newfpd := range newList {
  8547. for _, oldfpd := range oldFpdList {
  8548. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8549. var oldweight, newweight float64
  8550. if oldfpd["weight"] != nil {
  8551. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8552. }
  8553. if newfpd["weight"] != nil {
  8554. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8555. }
  8556. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8557. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8558. Old: oldweight,
  8559. New: newweight,
  8560. Times: newfpd["times"].(int64),
  8561. Ptid: newfpd["ptid"].(int64),
  8562. Fweight: fweight,
  8563. Id: oldfpd["id"].(int64),
  8564. })
  8565. break
  8566. }
  8567. }
  8568. }
  8569. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8570. }
  8571. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8572. }
  8573. func UdBarSync(c *gin.Context) {
  8574. appG := app.Gin{C: c}
  8575. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8576. fsions := gofasion.NewFasion(string(dataByte))
  8577. pastureid := fsions.Get("pastureId").ValueStr()
  8578. tx := restful.Engine.NewSession()
  8579. defer tx.Close()
  8580. pastureinfo := new(udPastureInfo)
  8581. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8582. if err != nil {
  8583. logs.Error(err)
  8584. return
  8585. }
  8586. // gm.UdBarSync(pastureid, pastureinfo.Werks)
  8587. jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8588. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8589. }
  8590. func UdFeedSync(c *gin.Context) {
  8591. appG := app.Gin{C: c}
  8592. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8593. fsions := gofasion.NewFasion(string(dataByte))
  8594. pastureid := fsions.Get("pastureId").ValueStr()
  8595. tx := restful.Engine.NewSession()
  8596. defer tx.Close()
  8597. pastureinfo := new(udPastureInfo)
  8598. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8599. if err != nil {
  8600. logs.Error(err)
  8601. return
  8602. }
  8603. // gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8604. jpud.UdFeedSync(pastureid, pastureinfo.Werks)
  8605. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8606. }
  8607. func UdFeedtempletPush(c *gin.Context) {
  8608. appG := app.Gin{C: c}
  8609. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8610. fsions := gofasion.NewFasion(string(dataByte))
  8611. pastureid := fsions.Get("pastureId").ValueStr()
  8612. date := fsions.Get("date").ValueStr()
  8613. tx := restful.Engine.NewSession()
  8614. defer tx.Close()
  8615. pastureinfo := new(udPastureInfo)
  8616. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8617. if err != nil {
  8618. logs.Error(err)
  8619. return
  8620. }
  8621. // gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8622. jpud.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8623. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8624. }
  8625. func UdUtirPush(c *gin.Context) {
  8626. appG := app.Gin{C: c}
  8627. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8628. fsions := gofasion.NewFasion(string(dataByte))
  8629. pastureid := fsions.Get("pastureId").ValueStr()
  8630. date := fsions.Get("date").ValueStr()
  8631. tx := restful.Engine.NewSession()
  8632. defer tx.Close()
  8633. pastureinfo := new(udPastureInfo)
  8634. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8635. if err != nil {
  8636. logs.Error(err)
  8637. return
  8638. }
  8639. // gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8640. jpud.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8641. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8642. }
  8643. func UdBarFeedRemainPush(c *gin.Context) {
  8644. appG := app.Gin{C: c}
  8645. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8646. fsions := gofasion.NewFasion(string(dataByte))
  8647. pastureid := fsions.Get("pastureId").ValueStr()
  8648. date := fsions.Get("date").ValueStr()
  8649. tx := restful.Engine.NewSession()
  8650. defer tx.Close()
  8651. pastureinfo := new(udPastureInfo)
  8652. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8653. if err != nil {
  8654. logs.Error(err)
  8655. return
  8656. }
  8657. // gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8658. jpud.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8659. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8660. }
  8661. func UdMaterialIssuePush(c *gin.Context) {
  8662. appG := app.Gin{C: c}
  8663. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8664. fsions := gofasion.NewFasion(string(dataByte))
  8665. pastureid := fsions.Get("pastureId").ValueStr()
  8666. date := fsions.Get("date").ValueStr()
  8667. tx := restful.Engine.NewSession()
  8668. defer tx.Close()
  8669. pastureinfo := new(udPastureInfo)
  8670. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8671. if err != nil {
  8672. logs.Error(err)
  8673. return
  8674. }
  8675. // gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8676. jpud.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8677. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8678. }
  8679. //搅拌
  8680. func YmyUtirPush(c *gin.Context) {
  8681. appG := app.Gin{C: c}
  8682. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8683. fsions := gofasion.NewFasion(string(dataByte))
  8684. pastureid := fsions.Get("pastureId").ValueStr()
  8685. date := fsions.Get("date").ValueStr()
  8686. tx := restful.Engine.NewSession()
  8687. defer tx.Close()
  8688. pastureinfo := new(udPastureInfo)
  8689. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8690. if err != nil {
  8691. logs.Error(err)
  8692. return
  8693. }
  8694. ymy.YmyUtirPush(pastureid, pastureinfo.Werks, date)
  8695. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8696. }
  8697. //撒料
  8698. func YmyMaterialIssuePush(c *gin.Context) {
  8699. appG := app.Gin{C: c}
  8700. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8701. fsions := gofasion.NewFasion(string(dataByte))
  8702. pastureid := fsions.Get("pastureId").ValueStr()
  8703. date := fsions.Get("date").ValueStr()
  8704. tx := restful.Engine.NewSession()
  8705. defer tx.Close()
  8706. pastureinfo := new(udPastureInfo)
  8707. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8708. if err != nil {
  8709. logs.Error(err)
  8710. return
  8711. }
  8712. ymy.YmyMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8713. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8714. }
  8715. func YmyFeedtempletPush(c *gin.Context) {
  8716. appG := app.Gin{C: c}
  8717. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8718. fsions := gofasion.NewFasion(string(dataByte))
  8719. pastureid := fsions.Get("pastureId").ValueStr()
  8720. date := fsions.Get("date").ValueStr()
  8721. tx := restful.Engine.NewSession()
  8722. defer tx.Close()
  8723. pastureinfo := new(udPastureInfo)
  8724. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8725. if err != nil {
  8726. logs.Error(err)
  8727. return
  8728. }
  8729. ymy.YmyFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8730. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8731. }
  8732. //饲料
  8733. func YmySyncFeed(c *gin.Context) {
  8734. appG := app.Gin{C: c}
  8735. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8736. fsions := gofasion.NewFasion(string(dataByte))
  8737. pastureid := fsions.Get("pastureId").ValueStr()
  8738. // date := fsions.Get("date").ValueStr()
  8739. tx := restful.Engine.NewSession()
  8740. defer tx.Close()
  8741. ymy.YmySyncFeed(pastureid)
  8742. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8743. }
  8744. // 栏舍
  8745. func YmySyncBar(c *gin.Context) {
  8746. appG := app.Gin{C: c}
  8747. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8748. fsions := gofasion.NewFasion(string(dataByte))
  8749. pastureid := fsions.Get("pastureId").ValueStr()
  8750. // date := fsions.Get("date").ValueStr()
  8751. tx := restful.Engine.NewSession()
  8752. defer tx.Close()
  8753. pastureinfo := new(udPastureInfo)
  8754. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8755. if err != nil {
  8756. logs.Error(err)
  8757. return
  8758. }
  8759. ymy.YmySyncBar(pastureinfo.Werks, pastureid)
  8760. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8761. }
  8762. func DelFeedTemplet(c *gin.Context) {
  8763. appG := app.Gin{C: c}
  8764. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8765. fsions := gofasion.NewFasion(string(dataByte))
  8766. ftId := fsions.Get("ftId").ValueStr()
  8767. // userId := fsions.Get("userId").ValueStr()
  8768. tx := restful.Engine.NewSession()
  8769. defer tx.Close()
  8770. _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
  8771. if err != nil {
  8772. logs.Error(err)
  8773. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8774. return
  8775. }
  8776. /*
  8777. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8778. if err != nil {
  8779. logs.Error(err)
  8780. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8781. return
  8782. }
  8783. */
  8784. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8785. if err != nil {
  8786. logs.Error(err)
  8787. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8788. return
  8789. }
  8790. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8791. if err != nil {
  8792. logs.Error(err)
  8793. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8794. return
  8795. }
  8796. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8797. if count > 0 {
  8798. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8799. if err != nil {
  8800. logs.Error(err)
  8801. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8802. return
  8803. }
  8804. }
  8805. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8806. if err != nil {
  8807. logs.Error(err)
  8808. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8809. return
  8810. }
  8811. // var barIdStr []string
  8812. // for _, bar := range barIdList {
  8813. // barIdStr = append(barIdStr, bar["barid"])
  8814. // }
  8815. // if len(barIdStr) > 0 {
  8816. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8817. // if err != nil {
  8818. // logs.Error(err)
  8819. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8820. // return
  8821. // }
  8822. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8823. // if err != nil {
  8824. // logs.Error(err)
  8825. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8826. // return
  8827. // }
  8828. // now := time.Now()
  8829. // for _, newFpd := range newFpdDataList {
  8830. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8831. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8832. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8833. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8834. // if err != nil {
  8835. // logs.Error(err)
  8836. // appG.Response(http.StatusOK, e.ERROR, false)
  8837. // return
  8838. // }
  8839. // }
  8840. // for _, newFeedp := range newFeedpList {
  8841. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8842. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8843. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8844. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8845. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8846. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8847. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8848. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8849. // if err != nil {
  8850. // logs.Error(err)
  8851. // appG.Response(http.StatusOK, e.ERROR, false)
  8852. // return
  8853. // }
  8854. // }
  8855. // }
  8856. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8857. }
  8858. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8859. sysOpt := new(models.SysOpt)
  8860. tx.Table("sysopt").Where("inforname = ?", "separateVehicles").Get(sysOpt)
  8861. lweight := 0.0
  8862. if sysOpt.InforValue != "" {
  8863. lweight, _ = strconv.ParseFloat(sysOpt.InforValue, 64)
  8864. } else if sysOpt.InforValue == "" || sysOpt.InforValue == "0" {
  8865. return
  8866. }
  8867. fmt.Println(sysOpt)
  8868. data := fasion["parammaps"].(map[string]interface{})
  8869. // plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(2) ").Count()
  8870. downloadedplanList := make([]*models.DownloadedPlan, 0)
  8871. tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype = 2 ").Find(&downloadedplanList)
  8872. fmt.Println(lweight)
  8873. for _, downloadedplan := range downloadedplanList {
  8874. if downloadedplan.LWeight < lweight {
  8875. break
  8876. }
  8877. downloadplandtl1List := make([]*models.DownloadPlanDtl1, 0)
  8878. downloadplandtl1ExecList := make([]*models.DownloadPlanDtl1Exec, 0)
  8879. downloadplandtl2List := make([]*models.DownloadPlanDtl2, 0)
  8880. tx.Table("downloadplandtl1").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1List)
  8881. tx.Table("downloadplandtl2").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl2List)
  8882. tx.Table("downloadplandtl1_exec").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1ExecList)
  8883. lweightCount := math.Floor(downloadedplan.LWeight / lweight)
  8884. for i := 0; i <= int(lweightCount); i++ {
  8885. if i == 0 {
  8886. tx.Exec(` update downloadedplan set lweight = ? where id = ? `, lweight, downloadedplan.ID)
  8887. for _, downloadplandtl1 := range downloadplandtl1List {
  8888. tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl1.LWeight, downloadplandtl1.ID)
  8889. }
  8890. for _, downloadplandtl2 := range downloadplandtl2List {
  8891. tx.Exec(` update downloadplandtl2 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8892. }
  8893. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  8894. tx.Exec(` update downloadplandtl1_exec set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8895. }
  8896. // && downloadedplan.LWeight >lweight
  8897. } else if i < int(lweightCount) {
  8898. parts := strings.Split(downloadedplan.ProjName, ".")
  8899. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  8900. data := &models.DownloadedPlan{
  8901. PastureID: downloadedplan.PastureID,
  8902. MyDate: downloadedplan.MyDate,
  8903. ProjName: strings.Join(parts, "."),
  8904. DataCaptureNo: downloadedplan.DataCaptureNo,
  8905. TmrID: downloadedplan.TmrID,
  8906. TmrtName: downloadedplan.TmrtName,
  8907. HaveButton: downloadedplan.HaveButton,
  8908. InButtonType: downloadedplan.InButtonType,
  8909. PlanTime: downloadedplan.PlanTime,
  8910. InTime: downloadedplan.InTime,
  8911. CompletedTime: downloadedplan.CompletedTime,
  8912. IsCompleted: downloadedplan.IsCompleted,
  8913. LpPlanType: downloadedplan.LpPlanType,
  8914. Times: downloadedplan.Times,
  8915. Sort: downloadedplan.Sort,
  8916. Remark: downloadedplan.Remark,
  8917. ItemNum: downloadedplan.ItemNum,
  8918. OutItems: downloadedplan.OutItems,
  8919. FeedPName: downloadedplan.FeedPName,
  8920. FeedPCount: downloadedplan.FeedPCount,
  8921. Pid: downloadedplan.Pid,
  8922. TempID: downloadedplan.TempID,
  8923. TempletName: downloadedplan.TempletName,
  8924. PtsTempID: downloadedplan.PtsTempID,
  8925. PtsTempletName: downloadedplan.PtsTempletName,
  8926. ThoWeight: downloadedplan.ThoWeight,
  8927. FpWeight: downloadedplan.FpWeight,
  8928. LWeight: lweight,
  8929. IWeight: downloadedplan.IWeight,
  8930. OWeight: downloadedplan.OWeight,
  8931. TVersion: downloadedplan.TVersion,
  8932. PtVersion: downloadedplan.PtVersion,
  8933. Enable: downloadedplan.Enable,
  8934. IsUse: downloadedplan.IsUse,
  8935. OldTmrID: downloadedplan.OldTmrID,
  8936. DriverID: downloadedplan.DriverID,
  8937. Artificial: downloadedplan.Artificial,
  8938. }
  8939. _, err := tx.Insert(data)
  8940. fmt.Println(data, err)
  8941. for _, downloadplandtl1 := range downloadplandtl1List {
  8942. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8943. d1 := &models.DownloadPlanDtl1{
  8944. PastureID: downloadplandtl1.PastureID,
  8945. Pid: data.ID,
  8946. Flpid: downloadplandtl1.Flpid,
  8947. Fid: downloadplandtl1.Fid,
  8948. LWeight: lweight / downloadedplan.LWeight * downloadplandtl1.LWeight,
  8949. Sort: downloadplandtl1.Sort,
  8950. ButtonType: downloadplandtl1.ButtonType,
  8951. OptDevice: downloadplandtl1.OptDevice,
  8952. FeedCode: downloadplandtl1.FeedCode,
  8953. FName: downloadplandtl1.FName,
  8954. FeedSort: downloadplandtl1.FeedSort,
  8955. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  8956. StirDelay: downloadplandtl1.StirDelay,
  8957. FWeight: downloadplandtl1.FWeight,
  8958. TmrLoadName: downloadplandtl1.TmrLoadName,
  8959. DryFeed: downloadplandtl1.DryFeed,
  8960. PriceFeed: downloadplandtl1.PriceFeed,
  8961. OutWeight: downloadplandtl1.OutWeight,
  8962. ErrRatio: downloadplandtl1.ErrRatio,
  8963. Date: downloadplandtl1.Date,
  8964. ButtonSucc: downloadplandtl1.ButtonSucc,
  8965. Type: downloadplandtl1.Type,
  8966. Deviation: downloadplandtl1.Deviation,
  8967. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  8968. }
  8969. tx.Insert(d1)
  8970. }
  8971. for _, downloadplandtl2 := range downloadplandtl2List {
  8972. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8973. d2 := &models.DownloadPlanDtl2{
  8974. PastureID: downloadplandtl2.PastureID,
  8975. Pid: data.ID,
  8976. Flpid: downloadplandtl2.Flpid,
  8977. Fbarid: downloadplandtl2.Fbarid,
  8978. FName: downloadplandtl2.FName,
  8979. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8980. LWeightHis: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8981. RemainLeftW: downloadplandtl2.RemainLeftW,
  8982. AllowRW: downloadplandtl2.AllowRW,
  8983. Sort: downloadplandtl2.Sort,
  8984. HaveButton: downloadplandtl2.HaveButton,
  8985. BeginTag: downloadplandtl2.BeginTag,
  8986. EndTag: downloadplandtl2.EndTag,
  8987. ButtonType: downloadplandtl2.ButtonType,
  8988. OptDevice: downloadplandtl2.OptDevice,
  8989. CowCount: downloadplandtl2.CowCount,
  8990. CowClassID: downloadplandtl2.CowClassID,
  8991. CowClassName: downloadplandtl2.CowClassName,
  8992. BigCowName: downloadplandtl2.BigCowName,
  8993. PWeight: downloadplandtl2.PWeight,
  8994. CCountRatio: downloadplandtl2.CCountRatio,
  8995. SumRTime: downloadplandtl2.SumRTime,
  8996. FeedTempletID: downloadplandtl2.FeedTempletID,
  8997. FeedTempletName: downloadplandtl2.FeedTempletName,
  8998. DryWeight: downloadplandtl2.DryWeight,
  8999. SumWeight: downloadplandtl2.SumWeight,
  9000. PriceWeight: downloadplandtl2.PriceWeight,
  9001. // ProcessTime :downloadplandtl2.ProcessTime ,
  9002. Fpid: downloadplandtl2.Fpid,
  9003. UseInBarType: downloadplandtl2.UseInBarType,
  9004. Date: downloadplandtl2.Date,
  9005. AllowRatio: downloadplandtl2.AllowRatio,
  9006. ErrRatio: downloadplandtl2.ErrRatio,
  9007. ButtonSucc: downloadplandtl2.ButtonSucc,
  9008. Type: downloadplandtl2.Type,
  9009. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9010. XxwBarCode: downloadplandtl2.XxwBarCode,
  9011. }
  9012. _, err := tx.Insert(d2)
  9013. fmt.Println(err)
  9014. }
  9015. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9016. d2 := &models.DownloadPlanDtl1Exec{
  9017. PastureID: downloadplandtl2.PastureID,
  9018. Pid: data.ID,
  9019. Flpid: downloadplandtl2.Flpid,
  9020. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9021. HaveButton: downloadplandtl2.HaveButton,
  9022. ButtonType: downloadplandtl2.ButtonType,
  9023. OptDevice: downloadplandtl2.OptDevice,
  9024. Sort: downloadplandtl2.Sort,
  9025. FName: downloadplandtl2.FName,
  9026. FCount: downloadplandtl2.FCount,
  9027. TmrLoadName: downloadplandtl2.TmrLoadName,
  9028. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9029. StirDelay: downloadplandtl2.StirDelay,
  9030. ButtonSucc: downloadplandtl2.ButtonSucc,
  9031. ErrRatio: downloadplandtl2.ErrRatio,
  9032. Date: downloadplandtl2.Date,
  9033. Type: downloadplandtl2.Type,
  9034. Deviation: downloadplandtl2.Deviation,
  9035. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9036. }
  9037. _, err := tx.Insert(d2)
  9038. fmt.Println(err)
  9039. }
  9040. } else {
  9041. parts := strings.Split(downloadedplan.ProjName, ".")
  9042. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  9043. if downloadedplan.LWeight-float64(i)*lweight <= 0 {
  9044. continue
  9045. }
  9046. data := &models.DownloadedPlan{
  9047. PastureID: downloadedplan.PastureID,
  9048. MyDate: downloadedplan.MyDate,
  9049. ProjName: strings.Join(parts, "."),
  9050. DataCaptureNo: downloadedplan.DataCaptureNo,
  9051. TmrID: downloadedplan.TmrID,
  9052. TmrtName: downloadedplan.TmrtName,
  9053. HaveButton: downloadedplan.HaveButton,
  9054. InButtonType: downloadedplan.InButtonType,
  9055. PlanTime: downloadedplan.PlanTime,
  9056. InTime: downloadedplan.InTime,
  9057. CompletedTime: downloadedplan.CompletedTime,
  9058. IsCompleted: downloadedplan.IsCompleted,
  9059. LpPlanType: downloadedplan.LpPlanType,
  9060. Times: downloadedplan.Times,
  9061. Sort: downloadedplan.Sort,
  9062. Remark: downloadedplan.Remark,
  9063. ItemNum: downloadedplan.ItemNum,
  9064. OutItems: downloadedplan.OutItems,
  9065. FeedPName: downloadedplan.FeedPName,
  9066. FeedPCount: downloadedplan.FeedPCount,
  9067. Pid: downloadedplan.Pid,
  9068. TempID: downloadedplan.TempID,
  9069. TempletName: downloadedplan.TempletName,
  9070. PtsTempID: downloadedplan.PtsTempID,
  9071. PtsTempletName: downloadedplan.PtsTempletName,
  9072. ThoWeight: downloadedplan.ThoWeight,
  9073. FpWeight: downloadedplan.FpWeight,
  9074. LWeight: downloadedplan.LWeight - float64(i)*lweight,
  9075. IWeight: downloadedplan.IWeight,
  9076. OWeight: downloadedplan.OWeight,
  9077. TVersion: downloadedplan.TVersion,
  9078. PtVersion: downloadedplan.PtVersion,
  9079. Enable: downloadedplan.Enable,
  9080. IsUse: downloadedplan.IsUse,
  9081. OldTmrID: downloadedplan.OldTmrID,
  9082. DriverID: downloadedplan.DriverID,
  9083. Artificial: downloadedplan.Artificial,
  9084. }
  9085. _, err := tx.Insert(data)
  9086. fmt.Println(data, err)
  9087. for _, downloadplandtl1 := range downloadplandtl1List {
  9088. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9089. d1 := &models.DownloadPlanDtl1{
  9090. PastureID: downloadplandtl1.PastureID,
  9091. Pid: data.ID,
  9092. Flpid: downloadplandtl1.Flpid,
  9093. Fid: downloadplandtl1.Fid,
  9094. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl1.LWeight,
  9095. Sort: downloadplandtl1.Sort,
  9096. ButtonType: downloadplandtl1.ButtonType,
  9097. OptDevice: downloadplandtl1.OptDevice,
  9098. FeedCode: downloadplandtl1.FeedCode,
  9099. FName: downloadplandtl1.FName,
  9100. FeedSort: downloadplandtl1.FeedSort,
  9101. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  9102. StirDelay: downloadplandtl1.StirDelay,
  9103. FWeight: downloadplandtl1.FWeight,
  9104. TmrLoadName: downloadplandtl1.TmrLoadName,
  9105. DryFeed: downloadplandtl1.DryFeed,
  9106. PriceFeed: downloadplandtl1.PriceFeed,
  9107. OutWeight: downloadplandtl1.OutWeight,
  9108. ErrRatio: downloadplandtl1.ErrRatio,
  9109. Date: downloadplandtl1.Date,
  9110. ButtonSucc: downloadplandtl1.ButtonSucc,
  9111. Type: downloadplandtl1.Type,
  9112. Deviation: downloadplandtl1.Deviation,
  9113. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  9114. }
  9115. tx.Insert(d1)
  9116. }
  9117. for _, downloadplandtl2 := range downloadplandtl2List {
  9118. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9119. d2 := &models.DownloadPlanDtl2{
  9120. PastureID: downloadplandtl2.PastureID,
  9121. Pid: data.ID,
  9122. Flpid: downloadplandtl2.Flpid,
  9123. Fbarid: downloadplandtl2.Fbarid,
  9124. FName: downloadplandtl2.FName,
  9125. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9126. LWeightHis: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9127. RemainLeftW: downloadplandtl2.RemainLeftW,
  9128. AllowRW: downloadplandtl2.AllowRW,
  9129. Sort: downloadplandtl2.Sort,
  9130. HaveButton: downloadplandtl2.HaveButton,
  9131. BeginTag: downloadplandtl2.BeginTag,
  9132. EndTag: downloadplandtl2.EndTag,
  9133. ButtonType: downloadplandtl2.ButtonType,
  9134. OptDevice: downloadplandtl2.OptDevice,
  9135. CowCount: downloadplandtl2.CowCount,
  9136. CowClassID: downloadplandtl2.CowClassID,
  9137. CowClassName: downloadplandtl2.CowClassName,
  9138. BigCowName: downloadplandtl2.BigCowName,
  9139. PWeight: downloadplandtl2.PWeight,
  9140. CCountRatio: downloadplandtl2.CCountRatio,
  9141. SumRTime: downloadplandtl2.SumRTime,
  9142. FeedTempletID: downloadplandtl2.FeedTempletID,
  9143. FeedTempletName: downloadplandtl2.FeedTempletName,
  9144. DryWeight: downloadplandtl2.DryWeight,
  9145. SumWeight: downloadplandtl2.SumWeight,
  9146. PriceWeight: downloadplandtl2.PriceWeight,
  9147. // ProcessTime :downloadplandtl2.ProcessTime ,
  9148. Fpid: downloadplandtl2.Fpid,
  9149. UseInBarType: downloadplandtl2.UseInBarType,
  9150. Date: downloadplandtl2.Date,
  9151. AllowRatio: downloadplandtl2.AllowRatio,
  9152. ErrRatio: downloadplandtl2.ErrRatio,
  9153. ButtonSucc: downloadplandtl2.ButtonSucc,
  9154. Type: downloadplandtl2.Type,
  9155. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9156. XxwBarCode: downloadplandtl2.XxwBarCode,
  9157. }
  9158. _, err := tx.Insert(d2)
  9159. fmt.Println(err)
  9160. }
  9161. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9162. d2 := &models.DownloadPlanDtl1Exec{
  9163. PastureID: downloadplandtl2.PastureID,
  9164. Pid: data.ID,
  9165. Flpid: downloadplandtl2.Flpid,
  9166. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9167. HaveButton: downloadplandtl2.HaveButton,
  9168. ButtonType: downloadplandtl2.ButtonType,
  9169. OptDevice: downloadplandtl2.OptDevice,
  9170. Sort: downloadplandtl2.Sort,
  9171. FName: downloadplandtl2.FName,
  9172. FCount: downloadplandtl2.FCount,
  9173. TmrLoadName: downloadplandtl2.TmrLoadName,
  9174. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9175. StirDelay: downloadplandtl2.StirDelay,
  9176. ButtonSucc: downloadplandtl2.ButtonSucc,
  9177. ErrRatio: downloadplandtl2.ErrRatio,
  9178. Date: downloadplandtl2.Date,
  9179. Type: downloadplandtl2.Type,
  9180. Deviation: downloadplandtl2.Deviation,
  9181. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9182. }
  9183. fmt.Println(d2)
  9184. _, err := tx.Insert(d2)
  9185. fmt.Println(err)
  9186. }
  9187. }
  9188. }
  9189. }
  9190. downloadedplanSortList := make([]*models.DownloadedPlan, 0)
  9191. tx.SQL(`SELECT * FROM downloadedplan WHERE mydate = ? ORDER BY projname`, data["startTime"]).Find(&downloadedplanSortList)
  9192. for i, d := range downloadedplanSortList {
  9193. tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, d.ID)
  9194. }
  9195. }
  9196. func EditPlanSort(c *gin.Context) {
  9197. appG := app.Gin{C: c}
  9198. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9199. fsions := gofasion.NewFasion(string(dataByte))
  9200. planIdStr := fsions.Get("planId").ValueStr()
  9201. mydate := fsions.Get("mydate").ValueStr()
  9202. sort := fsions.Get("sort").ValueStr()
  9203. tx := restful.Engine.NewSession()
  9204. defer tx.Close()
  9205. tx.Begin()
  9206. type downloadedplan struct {
  9207. Id int64 `xorm:"id"`
  9208. Sort int `xorm:"sort"`
  9209. Pid int64 `xorm:"pid"`
  9210. }
  9211. planInfo := new(downloadedplan)
  9212. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  9213. if err != nil {
  9214. logs.Error(err)
  9215. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9216. tx.Rollback()
  9217. return
  9218. }
  9219. sort1, _ := strconv.Atoi(sort)
  9220. if sort1 == planInfo.Sort {
  9221. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  9222. tx.Rollback()
  9223. return
  9224. }
  9225. 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()
  9226. if err != nil {
  9227. logs.Error(err)
  9228. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9229. tx.Rollback()
  9230. return
  9231. }
  9232. if count1 == 0 {
  9233. tx.Rollback()
  9234. logs.Error(err)
  9235. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  9236. return
  9237. }
  9238. 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()
  9239. if err != nil {
  9240. logs.Error(err)
  9241. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9242. tx.Rollback()
  9243. return
  9244. }
  9245. if count > 0 {
  9246. tx.Rollback()
  9247. logs.Error(err)
  9248. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  9249. return
  9250. }
  9251. if planInfo.Sort > sort1 {
  9252. 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()
  9253. if err != nil {
  9254. logs.Error(err)
  9255. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9256. tx.Rollback()
  9257. return
  9258. }
  9259. var minSort, pidCount int
  9260. for _, sort := range minSortList {
  9261. minSort, _ = strconv.Atoi(sort["sort"])
  9262. }
  9263. planList := make([]*downloadedplan, 0)
  9264. 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)
  9265. if err != nil {
  9266. logs.Error(err)
  9267. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9268. tx.Rollback()
  9269. return
  9270. }
  9271. planPid := planInfo.Pid
  9272. planList1 := make([]*downloadedplan, 0)
  9273. planList2 := make([]*downloadedplan, 0)
  9274. for _, plan := range planList {
  9275. if plan.Pid == planPid {
  9276. pidCount++
  9277. planList1 = append(planList1, plan)
  9278. } else {
  9279. planList2 = append(planList2, plan)
  9280. }
  9281. }
  9282. planList1 = append(planList1, planList2...)
  9283. for i, plan := range planList1 {
  9284. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  9285. if err != nil {
  9286. logs.Error(err)
  9287. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9288. tx.Rollback()
  9289. return
  9290. }
  9291. }
  9292. } else {
  9293. 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()
  9294. if err != nil {
  9295. logs.Error(err)
  9296. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9297. tx.Rollback()
  9298. return
  9299. }
  9300. var maxSort int
  9301. for _, sort := range maxSortList {
  9302. maxSort, _ = strconv.Atoi(sort["sort"])
  9303. }
  9304. planList := make([]*downloadedplan, 0)
  9305. 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)
  9306. if err != nil {
  9307. logs.Error(err)
  9308. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9309. tx.Rollback()
  9310. return
  9311. }
  9312. planPid := planInfo.Pid
  9313. planList1 := make([]*downloadedplan, 0)
  9314. planList2 := make([]*downloadedplan, 0)
  9315. for _, plan := range planList {
  9316. if plan.Pid == planPid {
  9317. // pidCount++
  9318. planList1 = append(planList1, plan)
  9319. } else {
  9320. planList2 = append(planList2, plan)
  9321. }
  9322. }
  9323. planList2 = append(planList2, planList1...)
  9324. for i, plan := range planList2 {
  9325. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  9326. if err != nil {
  9327. logs.Error(err)
  9328. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9329. tx.Rollback()
  9330. return
  9331. }
  9332. }
  9333. }
  9334. err = tx.Commit()
  9335. if err != nil {
  9336. logs.Error(err)
  9337. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9338. tx.Rollback()
  9339. return
  9340. }
  9341. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9342. }
  9343. func EditDownloadedplanArtificial(c *gin.Context) {
  9344. appG := app.Gin{C: c}
  9345. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9346. fsions := gofasion.NewFasion(string(dataByte))
  9347. planIdStr := fsions.Get("planId").ValueStr()
  9348. tx := restful.Engine.NewSession()
  9349. defer tx.Close()
  9350. tx.Begin()
  9351. planIdList := strings.Split(planIdStr, ",")
  9352. for _, planId := range planIdList {
  9353. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? `, planId)
  9354. if err != nil {
  9355. logs.Error(err)
  9356. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9357. tx.Rollback()
  9358. return
  9359. }
  9360. }
  9361. err := tx.Commit()
  9362. if err != nil {
  9363. logs.Error(err)
  9364. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9365. tx.Rollback()
  9366. return
  9367. }
  9368. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9369. }
  9370. type PlanRFID struct {
  9371. RFID string `json:"RFID"`
  9372. Lweight string `json:"lweight"`
  9373. Gear string `json:"gear"`
  9374. Speed string `json:"speed"`
  9375. }
  9376. func GetPlanRFID(c *gin.Context) {
  9377. appG := app.Gin{C: c}
  9378. RFIDStr := c.Query("RFID")
  9379. planRFIDList := make([]*PlanRFID, 0)
  9380. planRFIDList = append(planRFIDList, &PlanRFID{
  9381. RFID: RFIDStr,
  9382. Lweight: "1411.1",
  9383. Gear: "1",
  9384. Speed: "10",
  9385. })
  9386. planRFIDList = append(planRFIDList, &PlanRFID{
  9387. RFID: RFIDStr,
  9388. Lweight: "1322.1",
  9389. Gear: "1",
  9390. Speed: "10",
  9391. })
  9392. planRFIDList = append(planRFIDList, &PlanRFID{
  9393. RFID: RFIDStr,
  9394. Lweight: "1904.1",
  9395. Gear: "1",
  9396. Speed: "10",
  9397. })
  9398. planRFIDList = append(planRFIDList, &PlanRFID{
  9399. RFID: RFIDStr,
  9400. Lweight: "1870.1",
  9401. Gear: "1",
  9402. Speed: "10",
  9403. })
  9404. planRFIDList = append(planRFIDList, &PlanRFID{
  9405. RFID: RFIDStr,
  9406. Lweight: "2041.1",
  9407. Gear: "1",
  9408. Speed: "10",
  9409. })
  9410. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  9411. }
  9412. type tmrEquipmentMuster struct {
  9413. A string
  9414. N string
  9415. }
  9416. func GetTmrEquipmentMuster(c *gin.Context) {
  9417. appG := app.Gin{C: c}
  9418. id := c.Query("id")
  9419. tx := restful.Engine.NewSession()
  9420. defer tx.Close()
  9421. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  9422. if err != nil {
  9423. logs.Error(err)
  9424. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9425. return
  9426. }
  9427. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  9428. for _, data := range dataList {
  9429. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  9430. for _, g := range tmrEquipmentMusterList {
  9431. a, _ := strconv.ParseFloat(g.A, 64)
  9432. n, _ := strconv.ParseFloat(g.N, 64)
  9433. a1, n1 := ddmmtoddd(a, n)
  9434. g.A = fmt.Sprintf("%f", n1)
  9435. g.N = fmt.Sprintf("%f", a1)
  9436. }
  9437. }
  9438. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  9439. }
  9440. func ddmmtoddd(lng, lat float64) (float64, float64) {
  9441. lngDegree := fmt.Sprintf("%f", lng/100)
  9442. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  9443. lngDegreeInt := int(lngDegreefloat * 1000000)
  9444. dd := lngDegreeInt / 100 * 100 / 60
  9445. fmt.Println(dd)
  9446. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  9447. latDegree := fmt.Sprintf("%f", lat/100)
  9448. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  9449. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  9450. latDegreeInt := int(latDegreefloat * 1000000)
  9451. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  9452. a, _ := strconv.ParseFloat(lngStr, 64)
  9453. b, _ := strconv.ParseFloat(latStr, 64)
  9454. return coordtransform.WGS84toGCJ02(b, a)
  9455. }
  9456. func EditDownloadedplanExecWeight(c *gin.Context) {
  9457. appG := app.Gin{C: c}
  9458. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9459. fsions := gofasion.NewFasion(string(dataByte))
  9460. pid := fsions.Get("pid").ValueStr()
  9461. sort := fsions.Get("sort").ValueStr()
  9462. weight := fsions.Get("weight").ValueStr()
  9463. userId := fsions.Get("userId").ValueStr()
  9464. tx := restful.Engine.NewSession()
  9465. defer tx.Close()
  9466. tx.Begin()
  9467. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  9468. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  9469. pid, sort, pid, sort, weight, userId)
  9470. if err != nil {
  9471. logs.Error(err)
  9472. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9473. tx.Rollback()
  9474. return
  9475. }
  9476. _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9477. if err != nil {
  9478. logs.Error(err)
  9479. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9480. tx.Rollback()
  9481. return
  9482. }
  9483. _, 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)
  9484. if err != nil {
  9485. logs.Error(err)
  9486. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9487. tx.Rollback()
  9488. return
  9489. }
  9490. err = tx.Commit()
  9491. if err != nil {
  9492. logs.Error(err)
  9493. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9494. tx.Rollback()
  9495. return
  9496. }
  9497. appG.Response(http.StatusOK, e.SUCCESS, true)
  9498. }
  9499. func EditDownloadplandtl2Weight(c *gin.Context) {
  9500. appG := app.Gin{C: c}
  9501. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9502. fsions := gofasion.NewFasion(string(dataByte))
  9503. pid := fsions.Get("pid").ValueStr()
  9504. sort := fsions.Get("sort").ValueStr()
  9505. weight := fsions.Get("weight").ValueStr()
  9506. userId := fsions.Get("userId").ValueStr()
  9507. tx := restful.Engine.NewSession()
  9508. defer tx.Close()
  9509. tx.Begin()
  9510. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9511. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9512. pid, sort, pid, sort, weight, userId)
  9513. if err != nil {
  9514. logs.Error(err)
  9515. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9516. tx.Rollback()
  9517. return
  9518. }
  9519. _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9520. if err != nil {
  9521. logs.Error(err)
  9522. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9523. tx.Rollback()
  9524. return
  9525. }
  9526. err = tx.Commit()
  9527. if err != nil {
  9528. logs.Error(err)
  9529. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9530. tx.Rollback()
  9531. return
  9532. }
  9533. appG.Response(http.StatusOK, e.SUCCESS, true)
  9534. }
  9535. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9536. params := fasion.Get("parammaps")
  9537. surplus := params.Get("surplus").ValueStr()
  9538. surplusId := params.Get("surplusId").ValueStr()
  9539. tx := restful.Engine.NewSession()
  9540. defer tx.Close()
  9541. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9542. if surplusId != "0" {
  9543. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9544. if err != nil {
  9545. log.Println("PostDataByName-error-1: ", err)
  9546. return errors.New("配方修改失败!")
  9547. }
  9548. type ftdetail struct {
  9549. Id string
  9550. Fname string
  9551. Sort int64
  9552. }
  9553. ftList := make([]*ftdetail, 0)
  9554. for _, data := range dataList {
  9555. ft := new(ftdetail)
  9556. ft.Fname = data["fname"]
  9557. ft.Id = data["id"]
  9558. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9559. if err != nil {
  9560. log.Println("PostDataByName-error-2: ", err)
  9561. return err
  9562. }
  9563. ft.Sort = sort
  9564. ftList = append(ftList, ft)
  9565. }
  9566. if surplus == "日粮" {
  9567. for _, ft := range ftList {
  9568. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9569. }
  9570. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9571. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9572. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9573. fmt.Println(err)
  9574. } else {
  9575. var sort int64
  9576. for _, ft := range ftList {
  9577. if ft.Fname == surplus {
  9578. sort = ft.Sort
  9579. break
  9580. }
  9581. }
  9582. if sort == 0 {
  9583. for _, ft := range ftList {
  9584. ft.Sort = ft.Sort + 1
  9585. }
  9586. } else {
  9587. for _, ft := range ftList {
  9588. if ft.Sort >= sort {
  9589. ft.Sort = ft.Sort + 1
  9590. }
  9591. }
  9592. }
  9593. for _, ft := range ftList {
  9594. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9595. }
  9596. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9597. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9598. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9599. if err != nil {
  9600. log.Println("PostDataByName-error-1: ", err)
  9601. fmt.Println(err)
  9602. return errors.New("配方修改失败!")
  9603. }
  9604. }
  9605. }
  9606. return nil
  9607. }
  9608. func FeedSurplus(fasion *gofasion.Fasion) {
  9609. tx := restful.Engine.NewSession()
  9610. defer tx.Close()
  9611. params := fasion.Get("parammaps")
  9612. feedId := params.Get("id").ValueStr()
  9613. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9614. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9615. }
  9616. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9617. // params := fasion.Get("parammaps")
  9618. // surplus := params.Get("surplus").ValueStr()
  9619. // surplusId := params.Get("surplusId").ValueStr()
  9620. tx := restful.Engine.NewSession()
  9621. defer tx.Close()
  9622. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9623. if surplusId != "0" {
  9624. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9625. if err != nil {
  9626. log.Println("PostDataByName-error-1: ", err)
  9627. return errors.New("配方修改失败!")
  9628. }
  9629. type ftdetail struct {
  9630. Id string
  9631. Fname string
  9632. Sort int64
  9633. }
  9634. ftList := make([]*ftdetail, 0)
  9635. for _, data := range dataList {
  9636. ft := new(ftdetail)
  9637. ft.Fname = data["fname"]
  9638. ft.Id = data["id"]
  9639. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9640. if err != nil {
  9641. log.Println("PostDataByName-error-2: ", err)
  9642. return err
  9643. }
  9644. ft.Sort = sort
  9645. ftList = append(ftList, ft)
  9646. }
  9647. if surplus == "日粮" {
  9648. for _, ft := range ftList {
  9649. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9650. }
  9651. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9652. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9653. pastureId, id, surplusId, surplusId, surplusId)
  9654. fmt.Println(err)
  9655. } else {
  9656. var sort int64
  9657. for _, ft := range ftList {
  9658. if ft.Fname == surplus {
  9659. sort = ft.Sort
  9660. break
  9661. }
  9662. }
  9663. if sort == 0 {
  9664. for _, ft := range ftList {
  9665. ft.Sort = ft.Sort + 1
  9666. }
  9667. } else {
  9668. for _, ft := range ftList {
  9669. if ft.Sort >= sort {
  9670. ft.Sort = ft.Sort + 1
  9671. }
  9672. }
  9673. }
  9674. for _, ft := range ftList {
  9675. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9676. }
  9677. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9678. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9679. id, surplusId, surplusId, sort, surplusId, pastureId)
  9680. if err != nil {
  9681. log.Println("PostDataByName-error-1: ", err)
  9682. fmt.Println(err)
  9683. return errors.New("配方修改失败!")
  9684. }
  9685. }
  9686. }
  9687. return nil
  9688. }
  9689. func GetLanguageStatus() string {
  9690. tx := restful.Engine.NewSession()
  9691. defer tx.Close()
  9692. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9693. if err != nil {
  9694. log.Println(err)
  9695. return "0"
  9696. }
  9697. return dataList[0]["inforvalue"]
  9698. }
  9699. func EditLanguage(c *gin.Context) {
  9700. appG := app.Gin{C: c}
  9701. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9702. fsions := gofasion.NewFasion(string(dataByte))
  9703. language := fsions.Get("language").ValueStr()
  9704. tx := restful.Engine.NewSession()
  9705. defer tx.Close()
  9706. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9707. if err != nil {
  9708. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9709. return
  9710. }
  9711. if language == "0" {
  9712. _, err := tx.Exec(`delete from dictlist `)
  9713. if err != nil {
  9714. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9715. return
  9716. }
  9717. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9718. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9719. if err != nil {
  9720. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9721. return
  9722. }
  9723. } else {
  9724. _, err := tx.Exec(`delete from dictlist `)
  9725. if err != nil {
  9726. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9727. return
  9728. }
  9729. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9730. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9731. if err != nil {
  9732. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9733. return
  9734. }
  9735. }
  9736. appG.Response(http.StatusOK, e.SUCCESS, true)
  9737. }
  9738. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9739. tx := restful.Engine.NewSession()
  9740. defer tx.Close()
  9741. 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
  9742. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9743. if err != nil {
  9744. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9745. return
  9746. }
  9747. for _, dataexcel := range barList {
  9748. // dataexcel := make(map[string]interface{}, 0)
  9749. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9750. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9751. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9752. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9753. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9754. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9755. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9756. // if err != nil {
  9757. // logs.Error(err)
  9758. // return
  9759. // }
  9760. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9761. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9762. // if err != nil {
  9763. // logs.Error(err)
  9764. // return
  9765. // }
  9766. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9767. continue
  9768. }
  9769. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9770. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9771. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9772. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9773. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9774. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9775. // /*
  9776. tx.SQL(` update lpplandtl1 set lweight = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9777. if err != nil {
  9778. logs.Error(err)
  9779. return
  9780. }
  9781. tx.SQL(` update fpdetail set ptuse = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9782. if err != nil {
  9783. logs.Error(err)
  9784. return
  9785. }
  9786. // */
  9787. exist, err := tx.SQL(` select id from feedp where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9788. if err != nil {
  9789. logs.Error(err)
  9790. return
  9791. }
  9792. if !exist {
  9793. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9794. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9795. if err != nil {
  9796. logs.Error(err)
  9797. return
  9798. }
  9799. }
  9800. var feedpargs []interface{}
  9801. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9802. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9803. if _, ok := dataexcel["ftname"]; ok {
  9804. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9805. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9806. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9807. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9808. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9809. } else {
  9810. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9811. }
  9812. if _, ok := dataexcel["ptsfname"]; ok {
  9813. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9814. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9815. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9816. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9817. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9818. } else {
  9819. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9820. }
  9821. upFeedpSql += " where barname = ? and pastureid = ? "
  9822. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9823. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9824. if err != nil {
  9825. logs.Error(err)
  9826. return
  9827. }
  9828. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9829. if err != nil {
  9830. logs.Error(err)
  9831. return
  9832. }
  9833. if !exist1 {
  9834. _, 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) `,
  9835. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9836. if err != nil {
  9837. logs.Error(err)
  9838. return
  9839. }
  9840. }
  9841. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9842. if err != nil {
  9843. logs.Error(err)
  9844. return
  9845. }
  9846. if !exist2 {
  9847. _, 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) `,
  9848. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9849. if err != nil {
  9850. logs.Error(err)
  9851. return
  9852. }
  9853. }
  9854. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9855. if err != nil {
  9856. logs.Error(err)
  9857. return
  9858. }
  9859. if !exist3 {
  9860. _, 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) `,
  9861. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9862. if err != nil {
  9863. logs.Error(err)
  9864. return
  9865. }
  9866. }
  9867. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9868. if err != nil {
  9869. logs.Error(err)
  9870. return
  9871. }
  9872. if !exist4 {
  9873. _, 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) `,
  9874. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9875. if err != nil {
  9876. logs.Error(err)
  9877. return
  9878. }
  9879. }
  9880. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9881. if err != nil {
  9882. logs.Error(err)
  9883. return
  9884. }
  9885. if !exist5 {
  9886. _, 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) `,
  9887. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9888. if err != nil {
  9889. logs.Error(err)
  9890. return
  9891. }
  9892. }
  9893. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9894. if err != nil {
  9895. logs.Error(err)
  9896. return
  9897. }
  9898. if !exist6 {
  9899. _, 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) `,
  9900. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9901. if err != nil {
  9902. logs.Error(err)
  9903. return
  9904. }
  9905. }
  9906. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9907. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9908. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9909. and pastureid = ? and times = ?`
  9910. var fpdargs1 []interface{}
  9911. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9912. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9913. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9914. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9915. if err != nil {
  9916. fmt.Println(err)
  9917. return
  9918. }
  9919. var fpdargs2 []interface{}
  9920. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9921. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9922. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9923. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9924. if err != nil {
  9925. fmt.Println(err)
  9926. return
  9927. }
  9928. var fpdargs3 []interface{}
  9929. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9930. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9931. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9932. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9933. if err != nil {
  9934. fmt.Println(err)
  9935. return
  9936. }
  9937. var fpdargs4 []interface{}
  9938. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9939. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9940. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9941. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9942. if err != nil {
  9943. fmt.Println(err)
  9944. return
  9945. }
  9946. var fpdargs5 []interface{}
  9947. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9948. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9949. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9950. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9951. if err != nil {
  9952. fmt.Println(err)
  9953. return
  9954. }
  9955. var fpdargs6 []interface{}
  9956. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  9957. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9958. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  9959. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  9960. if err != nil {
  9961. fmt.Println(err)
  9962. return
  9963. }
  9964. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  9965. 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()
  9966. if err != nil {
  9967. return
  9968. }
  9969. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9970. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9971. upFpdetailList := make([]*upFpdetail, 0)
  9972. for _, newfpd := range newList {
  9973. for _, oldfpd := range oldFpdList {
  9974. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  9975. var oldweight, newweight float64
  9976. if oldfpd["weight"] != nil {
  9977. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  9978. }
  9979. if newfpd["weight"] != nil {
  9980. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  9981. }
  9982. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  9983. upFpdetailList = append(upFpdetailList, &upFpdetail{
  9984. Old: oldweight,
  9985. New: newweight,
  9986. Times: newfpd["times"].(int64),
  9987. Ptid: newfpd["ptid"].(int64),
  9988. Fweight: fweight,
  9989. Id: oldfpd["id"].(int64),
  9990. })
  9991. break
  9992. }
  9993. }
  9994. }
  9995. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  9996. }
  9997. }
  9998. func AddXxwFtdetail(c *gin.Context) {
  9999. appG := app.Gin{C: c}
  10000. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  10001. c.Bind(&xxwFtdetailList)
  10002. tx := restful.Engine.NewSession()
  10003. defer tx.Close()
  10004. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  10005. if err != nil {
  10006. logs.Error(err)
  10007. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10008. }
  10009. _, err = tx.Insert(xxwFtdetailList)
  10010. if err != nil {
  10011. logs.Error(err)
  10012. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10013. }
  10014. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  10015. appG.Response(http.StatusOK, e.SUCCESS, true)
  10016. }
  10017. func AddXxwFeedtemplet(c *gin.Context) {
  10018. appG := app.Gin{C: c}
  10019. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  10020. c.Bind(&xxwFeedtempletList)
  10021. tx := restful.Engine.NewSession()
  10022. defer tx.Close()
  10023. pastureinfo := new(udPastureInfo)
  10024. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  10025. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  10026. if err != nil {
  10027. logs.Error(err)
  10028. return
  10029. }
  10030. for _, ft := range xxwFeedtempletList {
  10031. ids, err := setting.SnowIds.NextId()
  10032. if err != nil {
  10033. ids = time.Now().UnixNano()
  10034. logging.Info("create SnowIds err", err)
  10035. }
  10036. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  10037. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  10038. ft.RecipeobjName, ft.RecipeobjName)
  10039. if err != nil {
  10040. logs.Error(err)
  10041. return
  10042. }
  10043. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  10044. _, 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')),
  10045. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  10046. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  10047. if err != nil {
  10048. logs.Error(err)
  10049. return
  10050. }
  10051. }
  10052. appG.Response(http.StatusOK, e.SUCCESS, true)
  10053. }
  10054. func ProcessExcel(c *gin.Context) {
  10055. appG := app.Gin{C: c}
  10056. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10057. fasion := gofasion.NewFasion(string(dataByte))
  10058. params := fasion.Get("parammaps")
  10059. pastureid := params.Get("pastureid").ValueStr()
  10060. startTime := params.Get("startTime").ValueStr()
  10061. stopTime := params.Get("stopTime").ValueStr()
  10062. iscompleted := params.Get("iscompleted").ValueStr()
  10063. lpplantype := params.Get("lpplantype").ValueStr()
  10064. error := params.Get("error").ValueStr()
  10065. hlwc1 := params.Get("hlwc1").ValueStr()
  10066. hlwc2 := params.Get("hlwc2").ValueStr()
  10067. slwc1 := params.Get("slwc1").ValueStr()
  10068. slwc2 := params.Get("slwc2").ValueStr()
  10069. hlzq1 := params.Get("hlzq1").ValueStr()
  10070. hlzq2 := params.Get("hlzq2").ValueStr()
  10071. slzq1 := params.Get("slzq1").ValueStr()
  10072. slzq2 := params.Get("slzq2").ValueStr()
  10073. fclassid := params.Get("fclassid").ValueStr()
  10074. minproesstime := params.Get("minproesstime").ValueStr()
  10075. maxproesstime := params.Get("maxproesstime").ValueStr()
  10076. tx := restful.Engine.NewSession()
  10077. defer tx.Close()
  10078. planList, err := tx.SQL(`SELECT
  10079. 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
  10080. FROM downloadedplan d
  10081. join pasture p on p.pastureid = d.pastureid
  10082. WHERE d.pastureid= ? and d.intime IS NOT NULL
  10083. AND mydate >= ? AND mydate <= ?
  10084. AND (iscompleted=? or ?='')
  10085. AND (lpplantype = ? or ? = '')
  10086. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  10087. 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
  10088. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  10089. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10090. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  10091. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10092. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  10093. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10094. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  10095. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10096. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  10097. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  10098. 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,
  10099. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  10100. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  10101. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  10102. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10103. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  10104. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  10105. or (?= '' and ? = '' ))
  10106. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  10107. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  10108. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  10109. maxproesstime, minproesstime, maxproesstime).QueryString()
  10110. if err != nil {
  10111. logs.Error(err)
  10112. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10113. return
  10114. }
  10115. planExecList, err := tx.SQL(`SELECT
  10116. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10117. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10118. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  10119. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10120. ) proesstime,
  10121. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10122. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  10123. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10124. sumproesstime, d1.pid,
  10125. d1.sort,
  10126. d1.fname,
  10127. d1.lweight,
  10128. d1.actualweightminus,
  10129. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  10130. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  10131. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  10132. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  10133. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  10134. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  10135. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  10136. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10137. d1.begintime stoptime,
  10138. d1.lastactualweight,
  10139. d1.actualweight,
  10140. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  10141. case d1.buttontype
  10142. when 1 then '自动'
  10143. when 2 then '手动'
  10144. when 3 then '手动'
  10145. end,
  10146. case d1.buttontype
  10147. when 1 then 'Automatic'
  10148. when 2 then 'Manual'
  10149. when 3 then 'Manual'
  10150. end
  10151. ) buttontype
  10152. FROM
  10153. downloadplandtl1_exec d1
  10154. WHERE d1.date between ? and ?
  10155. ORDER BY sort
  10156. `, startTime, stopTime).QueryString()
  10157. if err != nil {
  10158. logs.Error(err)
  10159. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10160. return
  10161. }
  10162. planExec2, err := tx.SQL(`SELECT
  10163. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  10164. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10165. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10166. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  10167. ) proesstime,
  10168. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  10169. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10170. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  10171. d1.sort,
  10172. d1.fname,
  10173. d1.lweight,
  10174. d1.actualweightminus,
  10175. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  10176. ABS(d1.lweight- d1.actualweightminus) diff,
  10177. 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,
  10178. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10179. d1.begintime stoptime,
  10180. d1.lastactualweight,
  10181. d1.actualweight,d1.pid
  10182. FROM
  10183. downloadplandtl2 d1
  10184. WHERE d1.date between ? and ?
  10185. ORDER BY sort`, startTime, stopTime).QueryString()
  10186. if err != nil {
  10187. logs.Error(err)
  10188. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10189. return
  10190. }
  10191. // 创建一个新的 Excel 文件
  10192. f := excelizexuri.NewFile()
  10193. // 创建工作表名称
  10194. sheetName := "Sheet1"
  10195. // border := []excelizexuri.Border{
  10196. // {Type: "left", Color: "000000", Style: 1},
  10197. // {Type: "right", Color: "000000", Style: 1},
  10198. // {Type: "top", Color: "000000", Style: 1},
  10199. // {Type: "bottom", Color: "000000", Style: 1},
  10200. // }
  10201. // 创建新的样式
  10202. style := &excelizexuri.Style{
  10203. // Border: border,
  10204. Alignment: &excelizexuri.Alignment{
  10205. Vertical: "center",
  10206. Horizontal: "center",
  10207. ShrinkToFit: true,
  10208. WrapText: true,
  10209. },
  10210. }
  10211. styleTitle := &excelizexuri.Style{
  10212. Fill: excelizexuri.Fill{
  10213. Color: []string{"FFFF0000"}, // 尝试使用完整的ARGB格式
  10214. },
  10215. // Border: border,
  10216. Font: &excelizexuri.Font{
  10217. Bold: true, // 加粗
  10218. Size: 24, // 字体大小
  10219. // Name: "宋体", // 字体名称
  10220. // WrapText :true,
  10221. Color: "000000", // 字体颜色(黑色)
  10222. },
  10223. Alignment: &excelizexuri.Alignment{
  10224. Vertical: "center", // 垂直居中
  10225. Horizontal: "center", // 水平居中
  10226. ShrinkToFit: true,
  10227. WrapText: true,
  10228. },
  10229. }
  10230. // 创建样式 ID
  10231. styleTitleId, err := f.NewStyle(styleTitle)
  10232. if err != nil {
  10233. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10234. return
  10235. }
  10236. // 创建样式 ID
  10237. styleID, err := f.NewStyle(style)
  10238. if err != nil {
  10239. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10240. return
  10241. }
  10242. // 合并单元格并设置内容
  10243. f.MergeCell(sheetName, "A1", "K1")
  10244. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  10245. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  10246. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  10247. planExecMap := make(map[string][]map[string]string, 0)
  10248. for _, planExec := range planExecList {
  10249. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  10250. }
  10251. plan2Map := make(map[string][]map[string]string, 0)
  10252. for _, plan2 := range planExec2 {
  10253. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  10254. }
  10255. num := 2
  10256. var notBorder []int
  10257. for _, plan := range planList {
  10258. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  10259. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10260. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10261. for i, header := range headers {
  10262. // 从 A2 开始
  10263. if header == "开始日期" {
  10264. cell := "%" + fmt.Sprintf("c%d", num)
  10265. cell = fmt.Sprintf(cell, 'A'+i+1)
  10266. f.SetCellValue(sheetName, cell, header)
  10267. f.SetCellStyle(sheetName, cell, cell, styleID)
  10268. continue
  10269. }
  10270. cell := "%" + fmt.Sprintf("c%d", num)
  10271. cell = fmt.Sprintf(cell, 'A'+i)
  10272. f.SetCellValue(sheetName, cell, header)
  10273. f.SetCellStyle(sheetName, cell, cell, styleID)
  10274. }
  10275. num += 1
  10276. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  10277. cell := "%" + fmt.Sprintf("c%d", num)
  10278. cell = fmt.Sprintf(cell, 'A'+0)
  10279. f.SetCellValue(sheetName, cell, plan["pastureName"])
  10280. f.SetCellStyle(sheetName, cell, cell, styleID)
  10281. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  10282. cell = "%" + fmt.Sprintf("c%d", num)
  10283. cell = fmt.Sprintf(cell, 'A'+1)
  10284. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  10285. f.SetCellStyle(sheetName, cell, cell, styleID)
  10286. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  10287. cell = "%" + fmt.Sprintf("c%d", num)
  10288. cell = fmt.Sprintf(cell, 'A'+2)
  10289. f.SetCellValue(sheetName, cell, plan["projname"])
  10290. f.SetCellStyle(sheetName, cell, cell, styleID)
  10291. cell = "%" + fmt.Sprintf("c%d", num)
  10292. cell = fmt.Sprintf(cell, 'A'+3)
  10293. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10294. f.SetCellValue(sheetName, cell, plan["mydate"])
  10295. f.SetCellStyle(sheetName, cell, cell, styleID)
  10296. cell = "%" + fmt.Sprintf("c%d", num)
  10297. cell = fmt.Sprintf(cell, 'A'+6)
  10298. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10299. f.SetCellValue(sheetName, cell, plan["intime"])
  10300. f.SetCellStyle(sheetName, cell, cell, styleID)
  10301. num += 1
  10302. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10303. for i, header := range headers1 {
  10304. cell = "%" + fmt.Sprintf("c%d", num)
  10305. cell = fmt.Sprintf(cell, 'C'+i)
  10306. f.SetCellValue(sheetName, cell, header)
  10307. f.SetCellStyle(sheetName, cell, cell, styleID)
  10308. // maxWidth := len(header)
  10309. // colName := string('C' + i)
  10310. // f.SetColWidth(sheetName, colName, colName, 20)
  10311. f.SetColWidth(sheetName, header, header, 40)
  10312. }
  10313. num += 1
  10314. // 在循环外部创建红色样式(只创建一次)
  10315. redStyle := &excelizexuri.Style{
  10316. Fill: excelizexuri.Fill{
  10317. Type: "pattern",
  10318. Color: []string{"FF0000"},
  10319. Pattern: 1,
  10320. },
  10321. // Font: &excelizexuri.Font{
  10322. // Bold: true, // 加粗
  10323. // Size: 24, // 字体大小
  10324. // // Name: "宋体", // 字体名称
  10325. // // WrapText :true,
  10326. // Color: "FFFF0000", // 字体颜色(黑色)
  10327. // },
  10328. Alignment: &excelizexuri.Alignment{
  10329. Vertical: "center",
  10330. Horizontal: "center",
  10331. ShrinkToFit: true,
  10332. WrapText: true,
  10333. },
  10334. }
  10335. redStyleID, err := f.NewStyle(redStyle)
  10336. if err != nil {
  10337. c.String(http.StatusInternalServerError, "Failed to create red style: "+err.Error())
  10338. return
  10339. }
  10340. // 在循环内部正确使用条件判断
  10341. for _, planExec := range planExecMap[plan["id"]] {
  10342. var currentStyleID int
  10343. if planExec["abnormal"] == "1" {
  10344. currentStyleID = redStyleID
  10345. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, planExec["abnormal"]) // 调试
  10346. } else {
  10347. currentStyleID = styleID
  10348. }
  10349. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10350. sort, _ := strconv.Atoi(planExec["sort"])
  10351. f.SetCellValue(sheetName, cell, sort)
  10352. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10353. cell = fmt.Sprintf("D%d", num)
  10354. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  10355. f.SetCellValue(sheetName, cell, lweight)
  10356. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10357. cell = fmt.Sprintf("E%d", num)
  10358. if _, ok := planExec["actualweightminus"]; ok {
  10359. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  10360. f.SetCellValue(sheetName, cell, actualweightminus)
  10361. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10362. } else {
  10363. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  10364. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10365. }
  10366. cell = fmt.Sprintf("F%d", num)
  10367. f.SetCellValue(sheetName, cell, planExec["fname"])
  10368. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10369. cell = fmt.Sprintf("G%d", num)
  10370. if _, ok := planExec["diff"]; ok {
  10371. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  10372. f.SetCellValue(sheetName, cell, diff)
  10373. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10374. } else {
  10375. f.SetCellValue(sheetName, cell, planExec["diff"])
  10376. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10377. }
  10378. cell = fmt.Sprintf("H%d", num)
  10379. if _, ok := planExec["diffRate"]; ok {
  10380. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  10381. f.SetCellValue(sheetName, cell, diffRate)
  10382. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10383. } else {
  10384. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  10385. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10386. }
  10387. cell = fmt.Sprintf("I%d", num)
  10388. f.SetCellValue(sheetName, cell, planExec["intime"])
  10389. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10390. cell = fmt.Sprintf("J%d", num)
  10391. if _, ok := planExec["lastactualweight"]; ok {
  10392. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  10393. f.SetCellValue(sheetName, cell, lastactualweight)
  10394. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10395. } else {
  10396. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  10397. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10398. }
  10399. cell = fmt.Sprintf("K%d", num)
  10400. if _, ok := planExec["actualweight"]; ok {
  10401. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  10402. f.SetCellValue(sheetName, cell, actualweight)
  10403. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10404. } else {
  10405. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  10406. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10407. }
  10408. num += 1
  10409. }
  10410. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10411. for i, header := range headers2 {
  10412. cell := "%" + fmt.Sprintf("c%d", num)
  10413. cell = fmt.Sprintf(cell, 'C'+i)
  10414. f.SetCellValue(sheetName, cell, header)
  10415. f.SetCellStyle(sheetName, cell, cell, styleID)
  10416. maxWidth := len(header)
  10417. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  10418. }
  10419. num += 1
  10420. for _, plan2 := range plan2Map[plan["id"]] {
  10421. var currentStyleID int
  10422. if plan2["abnormal"] == "1" {
  10423. currentStyleID = redStyleID
  10424. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, plan2["abnormal"]) // 调试
  10425. } else {
  10426. currentStyleID = styleID
  10427. }
  10428. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10429. sort, _ := strconv.Atoi(plan2["sort"])
  10430. f.SetCellValue(sheetName, cell, sort)
  10431. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10432. cell = fmt.Sprintf("D%d", num)
  10433. f.SetCellValue(sheetName, cell, plan2["fname"])
  10434. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10435. cell = fmt.Sprintf("E%d", num)
  10436. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  10437. f.SetCellValue(sheetName, cell, lweight)
  10438. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10439. cell = fmt.Sprintf("F%d", num)
  10440. if _, ok := plan2["actualweightminus"]; ok {
  10441. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  10442. f.SetCellValue(sheetName, cell, actualweightminus)
  10443. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10444. } else {
  10445. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  10446. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10447. }
  10448. cell = fmt.Sprintf("G%d", num)
  10449. if _, ok := plan2["diff"]; ok {
  10450. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  10451. f.SetCellValue(sheetName, cell, diff)
  10452. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10453. } else {
  10454. f.SetCellValue(sheetName, cell, plan2["diff"])
  10455. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10456. }
  10457. cell = fmt.Sprintf("H%d", num)
  10458. if _, ok := plan2["diffRate"]; ok {
  10459. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  10460. f.SetCellValue(sheetName, cell, diffRate)
  10461. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10462. } else {
  10463. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  10464. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10465. }
  10466. cell = fmt.Sprintf("I%d", num)
  10467. f.SetCellValue(sheetName, cell, plan2["intime"])
  10468. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10469. cell = fmt.Sprintf("J%d", num)
  10470. if _, ok := plan2["lastactualweight"]; ok {
  10471. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  10472. f.SetCellValue(sheetName, cell, lastactualweight)
  10473. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10474. } else {
  10475. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  10476. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10477. }
  10478. cell = fmt.Sprintf("K%d", num)
  10479. if _, ok := plan2["lastactualweight"]; ok {
  10480. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  10481. f.SetCellValue(sheetName, cell, actualweight)
  10482. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10483. } else {
  10484. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  10485. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10486. }
  10487. num += 1
  10488. }
  10489. num += 1
  10490. notBorder = append(notBorder, num)
  10491. }
  10492. // for i := 2; i < num; i++ {
  10493. // exist := false
  10494. // for _, n := range notBorder {
  10495. // if i+1 == n {
  10496. // exist = true
  10497. // break
  10498. // }
  10499. // }
  10500. // if !exist {
  10501. // // 为 A-K 列设置边框
  10502. // for col := 'A'; col <= 'K'; col++ {
  10503. // cellName := fmt.Sprintf("%c%d", col, i)
  10504. // style, _ := f.NewStyle(&excelizexuri.Style{
  10505. // // Border: border,
  10506. // Alignment: &excelizexuri.Alignment{
  10507. // Vertical: "center",
  10508. // Horizontal: "center",
  10509. // ShrinkToFit: true,
  10510. // WrapText: true,
  10511. // },
  10512. // })
  10513. // f.SetCellStyle(sheetName, cellName, cellName, style)
  10514. // }
  10515. // }
  10516. // }
  10517. for col := 'A'; col <= 'K'; col++ {
  10518. colName := string(col)
  10519. switch colName {
  10520. case "A", "B": // 牧场名称、TMR列
  10521. f.SetColWidth(sheetName, colName, colName, 10)
  10522. case "C": // 操作编号列
  10523. f.SetColWidth(sheetName, colName, colName, 10)
  10524. case "D", "E": // 计划重量、实际重量列
  10525. f.SetColWidth(sheetName, colName, colName, 12)
  10526. case "F": // 代表成分/投料位置列
  10527. f.SetColWidth(sheetName, colName, colName, 20)
  10528. case "G", "H": // 误差数、准确率列
  10529. f.SetColWidth(sheetName, colName, colName, 12)
  10530. case "I": // 完成时间列
  10531. f.SetColWidth(sheetName, colName, colName, 15)
  10532. case "J", "K": // 起始读数重量、完成读数重量列
  10533. f.SetColWidth(sheetName, colName, colName, 15)
  10534. }
  10535. }
  10536. // 设置响应头
  10537. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10538. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10539. c.Header("Content-Transfer-Encoding", "binary")
  10540. // 写入 Excel 文件到响应
  10541. if err := f.Write(c.Writer); err != nil {
  10542. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10543. return
  10544. }
  10545. }
  10546. func RestartMqtt(c *gin.Context) {
  10547. appG := app.Gin{C: c}
  10548. // 发送 GET 请求到 MQTT 重启接口
  10549. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10550. if err != nil {
  10551. logging.Error("RestartMqtt request failed:", err)
  10552. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10553. return
  10554. }
  10555. defer resp.Body.Close()
  10556. // 读取响应内容f
  10557. body, err := ioutil.ReadAll(resp.Body)
  10558. if err != nil {
  10559. logging.Error("RestartMqtt read response failed:", err)
  10560. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10561. return
  10562. }
  10563. // 检查响应状态码
  10564. if resp.StatusCode != http.StatusOK {
  10565. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10566. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10567. return
  10568. }
  10569. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10570. }
  10571. func FpdBatchEditByWeight(c *gin.Context) {
  10572. appG := app.Gin{C: c}
  10573. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10574. fsions := gofasion.NewFasion(string(dataByte))
  10575. barList := fsions.Get("barList").Array()
  10576. pastureid := fsions.Get("pastureId").ValueStr()
  10577. tx := restful.Engine.NewSession()
  10578. defer tx.Close()
  10579. 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
  10580. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10581. if err != nil {
  10582. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10583. return
  10584. }
  10585. for _, barFsions := range barList {
  10586. dataexcel := make(map[string]interface{}, 0)
  10587. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10588. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10589. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10590. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10591. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10592. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10593. continue
  10594. }
  10595. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10596. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10597. // if err != nil {
  10598. // logs.Error(err)
  10599. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10600. // return
  10601. // }
  10602. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10603. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10604. // if err != nil {
  10605. // logs.Error(err)
  10606. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10607. // return
  10608. // }
  10609. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10610. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10611. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10612. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10613. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10614. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10615. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10616. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10617. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10618. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10619. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10620. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10621. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10622. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10623. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10624. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10625. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10626. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10627. if err != nil {
  10628. logs.Error(err)
  10629. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10630. return
  10631. }
  10632. if !ftexist {
  10633. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10634. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10635. if err != nil {
  10636. logs.Error(err)
  10637. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10638. return
  10639. }
  10640. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10641. if err != nil {
  10642. logs.Error(err)
  10643. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10644. return
  10645. }
  10646. }
  10647. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10648. if err != nil {
  10649. logs.Error(err)
  10650. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10651. return
  10652. }
  10653. if !exist {
  10654. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10655. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10656. if err != nil {
  10657. logs.Error(err)
  10658. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10659. return
  10660. }
  10661. }
  10662. var feedpargs []interface{}
  10663. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10664. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10665. if _, ok := dataexcel["ftname"]; ok {
  10666. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10667. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10668. // upFeedpSql += `,ftweight = ? `
  10669. // feedpargs = append(feedpargs, weight)
  10670. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10671. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10672. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10673. } else {
  10674. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10675. }
  10676. // if _, ok := dataexcel["ptsfname"]; ok {
  10677. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10678. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10679. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10680. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10681. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10682. // } else {
  10683. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10684. // }
  10685. upFeedpSql += " where barname = ? and pastureid = ? "
  10686. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10687. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10688. if err != nil {
  10689. logs.Error(err)
  10690. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10691. return
  10692. }
  10693. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10694. if err != nil {
  10695. logs.Error(err)
  10696. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10697. return
  10698. }
  10699. if !exist1 {
  10700. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10701. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10702. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10703. if err != nil {
  10704. logs.Error(err)
  10705. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10706. return
  10707. }
  10708. }
  10709. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10710. if err != nil {
  10711. logs.Error(err)
  10712. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10713. return
  10714. }
  10715. if !exist2 {
  10716. _, 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) `,
  10717. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10718. if err != nil {
  10719. logs.Error(err)
  10720. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10721. return
  10722. }
  10723. }
  10724. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10725. if err != nil {
  10726. logs.Error(err)
  10727. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10728. return
  10729. }
  10730. if !exist3 {
  10731. _, 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) `,
  10732. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10733. if err != nil {
  10734. logs.Error(err)
  10735. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10736. return
  10737. }
  10738. }
  10739. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10740. if err != nil {
  10741. logs.Error(err)
  10742. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10743. return
  10744. }
  10745. if !exist4 {
  10746. _, 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) `,
  10747. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10748. if err != nil {
  10749. logs.Error(err)
  10750. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10751. return
  10752. }
  10753. }
  10754. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  10755. if err != nil {
  10756. logs.Error(err)
  10757. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10758. return
  10759. }
  10760. if !exist5 {
  10761. _, 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) `,
  10762. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10763. if err != nil {
  10764. logs.Error(err)
  10765. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10766. return
  10767. }
  10768. }
  10769. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  10770. if err != nil {
  10771. logs.Error(err)
  10772. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10773. return
  10774. }
  10775. if !exist6 {
  10776. _, 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) `,
  10777. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10778. if err != nil {
  10779. logs.Error(err)
  10780. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10781. return
  10782. }
  10783. }
  10784. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10785. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10786. and pastureid = ? and times = ?`
  10787. var fpdargs1 []interface{}
  10788. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10789. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10790. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10791. if err != nil {
  10792. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10793. return
  10794. }
  10795. var fpdargs2 []interface{}
  10796. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10797. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10798. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10799. if err != nil {
  10800. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10801. return
  10802. }
  10803. var fpdargs3 []interface{}
  10804. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10805. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10806. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10807. if err != nil {
  10808. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10809. return
  10810. }
  10811. var fpdargs4 []interface{}
  10812. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10813. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10814. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10815. if err != nil {
  10816. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10817. return
  10818. }
  10819. var fpdargs5 []interface{}
  10820. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10821. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10822. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10823. if err != nil {
  10824. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10825. return
  10826. }
  10827. var fpdargs6 []interface{}
  10828. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10829. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10830. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10831. if err != nil {
  10832. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10833. return
  10834. }
  10835. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10836. 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()
  10837. if err != nil {
  10838. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10839. return
  10840. }
  10841. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10842. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10843. upFpdetailList := make([]*upFpdetail, 0)
  10844. for _, newfpd := range newList {
  10845. for _, oldfpd := range oldFpdList {
  10846. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10847. var oldweight, newweight float64
  10848. if oldfpd["weight"] != nil {
  10849. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10850. }
  10851. if newfpd["weight"] != nil {
  10852. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10853. }
  10854. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10855. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10856. Old: oldweight,
  10857. New: newweight,
  10858. Times: newfpd["times"].(int64),
  10859. Ptid: newfpd["ptid"].(int64),
  10860. Fweight: fweight,
  10861. Id: oldfpd["id"].(int64),
  10862. })
  10863. break
  10864. }
  10865. }
  10866. }
  10867. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10868. }
  10869. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10870. }
  10871. func FtImportExcel(c *gin.Context) {
  10872. appG := app.Gin{C: c}
  10873. inputdata := ""
  10874. c.Request.ParseForm()
  10875. params := c.Request.Form
  10876. file, _, err := c.Request.FormFile("file")
  10877. if err != nil {
  10878. appG.Response(http.StatusOK, e.ERROR, err)
  10879. return
  10880. }
  10881. sqlnamestrs := params.Get("name")
  10882. sheetname := params.Get("sheetname")
  10883. pastureid := params.Get("pastureid")
  10884. //importParams := params.Get("importParams")
  10885. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10886. // 必输项参数 (字符串格式 "field1,field2,field3")
  10887. requiredParams := params.Get("requiredParams")
  10888. // 日期参数
  10889. dateParams := params.Get("dateParams")
  10890. // 数字参数
  10891. numParams := params.Get("numParams")
  10892. //将字符串分割开
  10893. dateParamslist := strings.Split(dateParams, ",")
  10894. requiredParamslist := strings.Split(requiredParams, ",")
  10895. numParamslist := strings.Split(numParams, ",")
  10896. queryData := make([]interface{}, 0)
  10897. sqlslist := strings.Split(sqlnamestrs, ",")
  10898. xlsx1, err := excelize.OpenReader(file)
  10899. if err != nil {
  10900. fmt.Println(err)
  10901. return
  10902. }
  10903. ok := 0
  10904. error := 0
  10905. isdone := true
  10906. rows := xlsx1.GetRows(sheetname)
  10907. // 限制10000条,多余的截取掉
  10908. if len(rows) > 10000 {
  10909. rows = rows[:10000]
  10910. }
  10911. tx := restful.Engine.NewSession()
  10912. ftNameList := make(map[string]interface{})
  10913. var ftNames []interface{}
  10914. for i, row := range rows {
  10915. if i > 0 {
  10916. entry := make(map[string]interface{})
  10917. outentry := make(map[string]interface{})
  10918. for j, colCell := range rows[0] {
  10919. for k, colCell1 := range row {
  10920. if j == k {
  10921. outentry[colCell] = colCell1
  10922. entry[colCell] = colCell1
  10923. }
  10924. }
  10925. }
  10926. inputdata = ""
  10927. a := ""
  10928. fmt.Println(outentry, entry)
  10929. //校验日期格式
  10930. for _, v := range dateParamslist {
  10931. if v == "" {
  10932. continue
  10933. }
  10934. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10935. dtime, err := TransfTime(d.(string))
  10936. if err != nil {
  10937. a = strings.Trim(v, " ")
  10938. break
  10939. }
  10940. outentry[strings.Trim(v, " ")] = dtime
  10941. }
  10942. }
  10943. if a != "" {
  10944. outentry["error_msg"] = a + " 格式错误"
  10945. error++
  10946. queryData = append(queryData, outentry)
  10947. continue
  10948. }
  10949. a = ""
  10950. //校验必填格式
  10951. for _, v := range requiredParamslist {
  10952. if v == "" {
  10953. continue
  10954. }
  10955. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  10956. a = strings.Trim(v, " ")
  10957. break
  10958. }
  10959. }
  10960. if a != "" {
  10961. outentry["error_msg"] = a + " 未填或格式错误"
  10962. error++
  10963. queryData = append(queryData, outentry)
  10964. continue
  10965. }
  10966. a = ""
  10967. //校验数字格式
  10968. for _, v := range numParamslist {
  10969. if v == "" {
  10970. continue
  10971. }
  10972. d, ok := outentry[strings.Trim(v, " ")]
  10973. if !ok || d == "" {
  10974. outentry[strings.Trim(v, " ")] = 0
  10975. } else {
  10976. var fl float64
  10977. switch d.(type) {
  10978. case string:
  10979. fl, err = strconv.ParseFloat(d.(string), 64)
  10980. }
  10981. if err != nil || fl < 0 {
  10982. a = strings.Trim(v, " ")
  10983. break
  10984. }
  10985. }
  10986. }
  10987. if a != "" {
  10988. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  10989. error++
  10990. queryData = append(queryData, outentry)
  10991. continue
  10992. }
  10993. err := tx.Begin()
  10994. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  10995. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  10996. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  10997. }
  10998. for _, sqlnamestr := range sqlslist {
  10999. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  11000. paramslist := strings.Split(paramslists, ",")
  11001. if len(paramslist) > 0 {
  11002. s_params := make([]interface{}, 0)
  11003. for _, value := range paramslist {
  11004. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  11005. if tempv, exists := c.Get("jwt_username"); exists {
  11006. s_params = append(s_params, tempv.(string))
  11007. } else {
  11008. s_params = append(s_params, "")
  11009. }
  11010. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  11011. s_params = append(s_params, pastureid)
  11012. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  11013. ids, err := setting.SnowIds.NextId()
  11014. if err != nil {
  11015. ids = time.Now().UnixNano()
  11016. logging.Info("create SnowIds err", err)
  11017. }
  11018. s_params = append(s_params, ids)
  11019. } else {
  11020. if outentry[strings.Trim(value, " ")] == nil {
  11021. s_params = append(s_params, "")
  11022. } else {
  11023. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  11024. }
  11025. }
  11026. }
  11027. outentry["input"] = inputdata
  11028. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  11029. if err != nil {
  11030. if tx != nil {
  11031. tx.Rollback()
  11032. }
  11033. if tx != nil {
  11034. tx.Close()
  11035. }
  11036. msg := geterrmsg(err.Error())
  11037. outentry["error_msg"] = msg
  11038. error++
  11039. queryData = append(queryData, outentry)
  11040. isdone = true
  11041. break
  11042. } else {
  11043. if len(returnmsgmap1) > 0 {
  11044. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  11045. if tx != nil {
  11046. tx.Rollback()
  11047. }
  11048. if tx != nil {
  11049. tx.Close()
  11050. }
  11051. msg := geterrmsg(va.(string))
  11052. outentry["error_msg"] = msg
  11053. error++
  11054. queryData = append(queryData, outentry)
  11055. isdone = true
  11056. break
  11057. }
  11058. }
  11059. isdone = false
  11060. }
  11061. }
  11062. }
  11063. ftNames = append(ftNames, outentry["配方名称"])
  11064. switch {
  11065. case err != nil:
  11066. if tx != nil {
  11067. tx.Rollback()
  11068. }
  11069. default:
  11070. if tx != nil {
  11071. err = tx.Commit()
  11072. }
  11073. }
  11074. if tx != nil {
  11075. tx.Close()
  11076. }
  11077. }
  11078. if !isdone {
  11079. ok++
  11080. isdone = true
  11081. }
  11082. }
  11083. go ftSync(ftNames, pastureid)
  11084. data := make(map[string]interface{})
  11085. data["result"] = queryData
  11086. data["success"] = ok
  11087. data["err_count"] = error
  11088. appG.Response(http.StatusOK, e.SUCCESS, data)
  11089. }
  11090. func ftSync(ftNameList []interface{}, pastureId string) {
  11091. tx := restful.Engine.NewSession()
  11092. defer tx.Close()
  11093. for _, ftName := range ftNameList {
  11094. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  11095. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  11096. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  11097. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  11098. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  11099. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  11100. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  11101. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  11102. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, ftName).QueryString()
  11103. FpdBatchEditGrfd(pastureId, values1)
  11104. }
  11105. }
  11106. func CopyFeedtemplet(c *gin.Context) {
  11107. appG := app.Gin{C: c}
  11108. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11109. fsion := gofasion.NewFasion(string(dataByte))
  11110. pastureid := fsion.Get("pastureid").ValueStr()
  11111. newName := fsion.Get("newName").ValueStr()
  11112. id := fsion.Get("id").ValueStr()
  11113. tx := restful.Engine.NewSession()
  11114. defer tx.Close()
  11115. count, err := tx.SQL(` select count(1) from feedtemplet where tname = ? `, newName).Count()
  11116. if err != nil {
  11117. appG.Response(http.StatusOK, e.ERROR, err)
  11118. return
  11119. }
  11120. if count > 0 {
  11121. appG.Response(http.StatusOK, e.ERROR, "配方名称重复!")
  11122. return
  11123. }
  11124. type ftCode struct {
  11125. Tcode string `xorm:"tcode"`
  11126. }
  11127. code := new(ftCode)
  11128. err = tx.SQL(`select if(left((select max(tcode) from feedtemplet where pastureid = ?),8) =
  11129. (select DATE_FORMAT(now(),"%Y%m%d")),(select max(tcode)+1 from feedtemplet where pastureid = ?),
  11130. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))) tcode`, pastureid, pastureid).GetFirst(code).Error
  11131. if err != nil {
  11132. appG.Response(http.StatusOK, e.ERROR, err)
  11133. return
  11134. }
  11135. if code.Tcode == "" {
  11136. appG.Response(http.StatusOK, e.ERROR, "配方编码生产失败!")
  11137. return
  11138. }
  11139. _, err = tx.Exec(`INSERT INTO feedtemplet(pastureid,tname,tcode,tcolor,ccid,ccname,fttype,fttypeid,source,
  11140. remark,enable,sort,volume,autozone)
  11141. select pastureid,?,?,tcolor,ccid,ccname,fttype,fttypeid,source,
  11142. remark,enable,sort,volume,autozone from feedtemplet where id = ? `, newName, code.Tcode, id)
  11143. if err != nil {
  11144. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11145. return
  11146. }
  11147. _, err = tx.Exec(`insert into ftdetail(pastureid,ftid,fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11148. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry)
  11149. select pastureid,(select id from feedtemplet where tcode = ? ),fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11150. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry
  11151. from ftdetail where ftid = ? `, code.Tcode, id)
  11152. if err != nil {
  11153. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11154. return
  11155. }
  11156. appG.Response(http.StatusOK, e.SUCCESS, true)
  11157. }
  11158. func Test(c *gin.Context) {
  11159. appG := app.Gin{C: c}
  11160. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11161. appG.Response(http.StatusOK, e.SUCCESS, string(dataByte))
  11162. }
  11163. func GetPlanDry(c *gin.Context) {
  11164. appG := app.Gin{C: c}
  11165. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11166. fsion := gofasion.NewFasion(string(dataByte))
  11167. date := fsion.Get("date").ValueStr()
  11168. tx := restful.Engine.NewSession()
  11169. defer tx.Close()
  11170. dataList, err := tx.SQL(`SELECT
  11171. t.feedtempletName,
  11172. ifnull(t.feedtempletPrice,0)feedtempletPrice,
  11173. ifnull(t.feedtempletWeight,0)feedtempletWeight,
  11174. ifnull(t.feedtempletDryWeight,0)feedtempletDryWeight,
  11175. t.tmrno,
  11176. t.bname,
  11177. t.barid,
  11178. t.dry,
  11179. t.actualweightminus,
  11180. t.mydate,
  11181. t.pasturename,
  11182. t.endDate,
  11183. t.startDate,
  11184. t.times,
  11185. -- 计算startDate和endDate的中间时间
  11186. ifnull(DATE_FORMAT(
  11187. DATE_ADD(
  11188. t.startDate,
  11189. INTERVAL TIMESTAMPDIFF(SECOND, t.startDate, t.endDate)/2 SECOND
  11190. ),
  11191. '%Y-%m-%d %H:%i:%s'
  11192. ),'') AS midTime
  11193. FROM (
  11194. SELECT
  11195. (SELECT sort FROM downloadedplan WHERE pid = d.pid AND mydate = d.mydate AND lpplantype IN (0,1)) tmrno,
  11196. b.bname,
  11197. b.id barid,
  11198. ROUND(IF(IFNULL(d2.actualweightminus,0) < 0, d2.lweight/(select sum(lweight) from downloadplandtl2 where pid = d2.pid )*(select sum(dd1.actualweightminus) from downloadplandtl1 dd1 join downloadedplan dd on dd1.pid = dd.id where dd.pid = d.pid and dd.mydate = d.mydate and dd.lpplantype in(0,1) ) , d2.actualweightminus/(select sum(lweight) from downloadplandtl2 where pid = d2.pid )*(select sum(dd1.actualweightminus) from downloadplandtl1 dd1 join downloadedplan dd on dd1.pid = dd.id where dd.pid = d.pid and dd.mydate = d.mydate and dd.lpplantype in(0,1) ) )*((SELECT IFNULL(AVG(dry),0) FROM downloadedplan dd
  11199. JOIN downloadplandtl1 dd1 ON dd.id = dd1.pid
  11200. JOIN feednur fn ON fn.fid = dd1.fid
  11201. WHERE dd.pid = d.pid AND dd.mydate = d.mydate AND lpplantype IN (0,1,4))/100),2) dry,
  11202. IF(IFNULL(d2.actualweightminus,0) < 0, d2.lweight/(select sum(lweight) from downloadplandtl2 where pid = d2.pid )*(select sum(dd1.actualweightminus) from downloadplandtl1 dd1 join downloadedplan dd on dd1.pid = dd.id where dd.pid = d.pid and dd.mydate = d.mydate and dd.lpplantype in(0,1) ) , d2.actualweightminus/(select sum(actualweightminus) from downloadplandtl2 where pid = d2.pid )*(select sum(dd1.actualweightminus) from downloadplandtl1 dd1 join downloadedplan dd on dd1.pid = dd.id where dd.pid = d.pid and dd.mydate = d.mydate and dd.lpplantype in(0,1) ) ) actualweightminus,
  11203. DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate,
  11204. p.pasture_name pastureName,
  11205. DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endDate,
  11206. DATE_FORMAT(IFNULL(
  11207. (SELECT MAX(intime) FROM downloadplandtl2 d1
  11208. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d1.intime<d2.intime),
  11209. (SELECT MAX(intime) FROM downloadplandtl1_exec de
  11210. WHERE de.date=d2.date AND de.pastureid = d2.pastureid AND de.pid=d2.pid)
  11211. ), '%Y-%m-%d %H:%i:%s') startDate,
  11212. d.times ,
  11213. ( SELECT
  11214. round(SUM(
  11215. IF(ftd.preftid<>0,
  11216. ftd.fweight*IFNULL((SELECT SUM(ftd1.fweight*f1.dry/100)/SUM(ftd1.fweight) FROM ftdetaildate ftd1
  11217. JOIN feednur f1 ON f1.fid= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11218. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11219. ftd.fweight*f.dry/100)) ,2)
  11220. dryweight
  11221. FROM ftdetaildate ftd
  11222. LEFT JOIN feednur f ON f.fid= ftd.fid AND f.pastureid = ftd.pastureid
  11223. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletDryWeight,(
  11224. select
  11225. sum(ftd.fweight)
  11226. FROM ftdetaildate ftd
  11227. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletWeight,
  11228. ( SELECT
  11229. round(SUM(
  11230. IF(ftd.preftid<>0,
  11231. IFNULL((SELECT SUM(ftd1.fweight*f1.uprice) FROM ftdetaildate ftd1
  11232. JOIN feed f1 ON f1.id= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11233. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11234. ftd.fweight*f.uprice)) ,2)
  11235. dryweight
  11236. FROM ftdetaildate ftd
  11237. LEFT JOIN feed f ON f.id= ftd.fid AND f.pastureid = ftd.pastureid
  11238. WHERE ftd.ftid = d.tempid and ftd.date = d2.date )
  11239. feedtempletPrice,d.templetname feedtempletName
  11240. FROM downloadedplan d
  11241. JOIN downloadplandtl2 d2 ON d.id=d2.PID
  11242. JOIN bar b ON b.id = d2.fbarid
  11243. JOIN pasture p ON p.pastureid = d.pastureid
  11244. WHERE d.mydate = DATE_FORMAT(?,'%Y-%m-%d')
  11245. AND d2.type = 0
  11246. AND d.havebutton = 1
  11247. ) t
  11248. WHERE 1=1 `, date).QueryString()
  11249. if err != nil {
  11250. logs.Error(err)
  11251. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11252. return
  11253. }
  11254. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11255. }
  11256. func GetBar(c *gin.Context) {
  11257. appG := app.Gin{C: c}
  11258. tx := restful.Engine.NewSession()
  11259. defer tx.Close()
  11260. pastureinfo := new(udPastureInfo)
  11261. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  11262. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  11263. if err != nil {
  11264. logs.Error(err)
  11265. return
  11266. }
  11267. dataList, err := tx.SQL(` select id,bname from bar where pastureid = ?`, pastureinfo.Pastureid).QueryString()
  11268. if err != nil {
  11269. logs.Error(err)
  11270. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11271. return
  11272. }
  11273. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11274. }
  11275. func GetHomepage(c *gin.Context) {
  11276. appG := app.Gin{C: c}
  11277. tx := restful.Engine.NewSession()
  11278. defer tx.Close()
  11279. dataList, err := tx.SQL(` SELECT
  11280. ifnull((SELECT CONCAT(ROUND(if(SUM(lweight) <= SUM(iweight),SUM(lweight)/SUM(iweight),SUM(iweight)/SUM(lweight))*100,2),'%') yesRateHL
  11281. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11282. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) ),'0.00%')yesRateHL, -- 昨日混料准确率
  11283. (SELECT CONCAT(ROUND(SUM(iweight)/SUM(lweight)*100,2),'%') yesRateHL
  11284. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11285. AND dt.mydate BETWEEN DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 31 DAY),'%Y-%m-%d') AND DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) )monRateHL , -- 近30日混料准确率
  11286. ifnull((SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11287. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11288. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) ),'0.00%')yesRateSL, -- 昨日撒料准确率
  11289. (SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11290. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11291. AND dt.mydate BETWEEN DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 31 DAY),'%Y-%m-%d') AND DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) )monRateSL, -- 进30日撒料准确率
  11292. ifnull((SELECT CONCAT(ROUND(IF(COUNT(de.id)>0,SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio,1,0))/COUNT(de.id),0)*100,2),'%') -- 正确率
  11293. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11294. WHERE dt.pastureid = d.pastureid AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')),'0.00%') yesRateSLR, -- 昨日正确率
  11295. (SELECT CONCAT(ROUND(IF(COUNT(de.id)>0,SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio,1,0))/COUNT(de.id),0)*100,2),'%') -- 正确率
  11296. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11297. WHERE dt.pastureid = d.pastureid
  11298. AND dt.mydate BETWEEN DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 31 DAY),'%Y-%m-%d') AND DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')) monRateSLR, -- 近30日正确率
  11299. (SELECT COUNT(*)FROM downloadedplan dt WHERE dt.pastureid= d.pastureid AND dt.mydate = d.mydate and dt.iscompleted=1 and if ( 0 = 0 ,1=1, if(0 = 1 ,dt.lpplantype in(0,1), dt.lpplantype in(0,2) ) )) doneTimes,
  11300. (SELECT COUNT(*)FROM downloadedplan dt WHERE dt.pastureid= d.pastureid AND dt.mydate = d.mydate and if ( 0 = 0 ,1=1, if(0 = 1 ,dt.lpplantype in(0,1), dt.lpplantype in(0,2) ) ) ) planTimes,
  11301. ifnull((SELECT SUM(dc.actualweightminus) FROM downloadplandtl1_exec dc join downloadedplan dt on dt.id = dc.pid WHERE dc.pastureid = 0 AND dc.date = d.mydate and if ( 0 = 0 ,1=1, if(0 = 1 ,dt.lpplantype in(0,1), dt.lpplantype in(0,2) ) ) ),0) doneWeight,
  11302. ifnull((SELECT SUM(dc.lweight ) FROM downloadplandtl1_exec dc join downloadedplan dt on dt.id = dc.pid WHERE dc.pastureid = 0 AND dc.date = d.mydate and if ( 0 = 0 ,1=1, if(0 = 1 ,dt.lpplantype in(0,1), dt.lpplantype in(0,2) ) ) ),0) planWeight,
  11303. ifnull(round(getSLtimeDiffSINGEL(d.pastureid,d.mydate),2),0.00) temtime,
  11304. ifnull(round(getSLtimeDiffMonth(d.pastureid) ,2),0.00) montime
  11305. FROM
  11306. (SELECT (select column_default as pastureid from information_schema.COLUMNS
  11307. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid') as pastureid,date_format(now(),'%Y-%m-%d') mydate) d `, setting.DatabaseSetting.Name).QueryString()
  11308. if err != nil {
  11309. logs.Error(err)
  11310. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11311. return
  11312. }
  11313. dataList1, err := tx.SQL(`select
  11314. ifnull(round(sum(if(d1.feedcode = '-1', d1.actualweightminus * (ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetail ftd2 WHERE ftd2.ftid = d1.fid ))* f.uprice,f.uprice * d1.actualweightminus )) / (select sum(ccount) from downloadplandtl2 d2 join bar b on b.id = d2.fbarid join feedp fp on fp.barid = b.id where date = d1.date),2),0) cost , ifnull(round(sum(if(d1.feedcode = '-1', d1.actualweightminus * (ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetail ftd2 WHERE ftd2.ftid = d1.fid ))* f.uprice,f.uprice * d1.actualweightminus )),2),0) totalCost from downloadplandtl1 d1
  11315. LEFT JOIN ftdetail ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1'
  11316. join feed f on f.id = ifnull(ftd.fid,d1.fid) where d1.date = date_format(now(),'%Y-%m-%d') `).QueryString()
  11317. if err != nil {
  11318. logs.Error(err)
  11319. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11320. return
  11321. }
  11322. for _, data := range dataList {
  11323. for _, data1 := range dataList1 {
  11324. data["totalCost"] = data1["totalCost"]
  11325. data["cost"] = data1["cost"]
  11326. }
  11327. }
  11328. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11329. }
  11330. func GetFeedingManagement(c *gin.Context) {
  11331. appG := app.Gin{C: c}
  11332. typea := c.Query("typea") // 0 栏舍 1 日期
  11333. startDate := c.Query("startdate")
  11334. endDate := c.Query("enddate")
  11335. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11336. // fsion := gofasion.NewFasion(string(dataByte))
  11337. tx := restful.Engine.NewSession()
  11338. defer tx.Close()
  11339. if typea == "0" {
  11340. dataList, err := tx.SQL(`select t.bname typea ,round(t.actualweightminus,2) actualweightminus ,round(t.dryweight,2) dryweight ,round(t.priceweight,2) totalcost ,round(t.priceweight / t.ccount,2) cost,t.ccount from (SELECT
  11341. SUM(
  11342. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11343. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11344. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11345. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11346. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11347. )
  11348. )actualweightminus ,
  11349. SUM(
  11350. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11351. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11352. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11353. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11354. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11355. ) * ifnull(fn.dry,0)
  11356. ) dryweight , SUM(
  11357. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11358. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11359. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11360. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11361. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11362. ) * ifnull(f.uprice,0)
  11363. ) priceweight
  11364. ,(select ccount from feedpdate where date = d1.date and barid = d2.fbarid) ccount,b.bname
  11365. FROM
  11366. downloadedplan d
  11367. JOIN downloadplandtl2 d2
  11368. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11369. JOIN downloadplandtl1 d1
  11370. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11371. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11372. LEFT JOIN ftdetaildate ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = ftd1.id AND d1.feedcode = '-1' AND ftd.date =d1.date AND ftd.version = ftd1.version
  11373. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11374. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11375. left join feednur fn on fn.fid = f.id
  11376. WHERE d.mydate BETWEEN ? AND ? GROUP BY d2.fbarid ) t `, startDate, endDate).QueryString()
  11377. if err != nil {
  11378. logs.Error(err)
  11379. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11380. return
  11381. }
  11382. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11383. } else {
  11384. dataList, err := tx.SQL(`select date_format(t.date ,'%Y-%m-%d') typea ,round(t.actualweightminus,2) actualweightminus ,round(t.dryweight,2) dryweight ,round(t.priceweight,2) totalcost ,round(t.priceweight / (select sum(ccount) from feedpdate fp where fp.date = t.date and fp.barid in(select fbarid from downloadplandtl2 where date = t.date and type = 0) ) ,2) cost,(select sum(ccount) from feedpdate fp where fp.date = t.date and fp.barid in(select fbarid from downloadplandtl2 where date = t.date and type = 0) ) ccount from (SELECT
  11385. SUM(
  11386. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11387. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11388. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11389. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11390. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11391. )
  11392. )actualweightminus ,
  11393. SUM(
  11394. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11395. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11396. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11397. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11398. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11399. ) * ifnull(fn.dry,0)
  11400. ) dryweight , SUM(
  11401. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  11402. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11403. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid )),
  11404. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  11405. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.date = d1.date AND ftd2.version = ftd1.version and ftd1.id = ftd2.ftid ))
  11406. ) * ifnull(f.uprice,0)
  11407. ) priceweight
  11408. ,(select sum(ccount) from feedpdate fp join downloadplandtl2 dd2 on dd2.fbarid = fp.barid where fp.date = d2.date and dd2.date = d2.date ) ccount,d2.date
  11409. FROM
  11410. downloadedplan d
  11411. JOIN downloadplandtl2 d2
  11412. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11413. JOIN downloadplandtl1 d1
  11414. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11415. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11416. LEFT JOIN ftdetaildate ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = ftd1.id AND d1.feedcode = '-1' AND ftd.date =d1.date AND ftd.version = ftd1.version
  11417. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11418. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11419. left join feednur fn on fn.fid = f.id
  11420. WHERE d.mydate BETWEEN ? AND ?
  11421. GROUP BY d.mydate) t `, startDate, endDate).QueryString()
  11422. if err != nil {
  11423. logs.Error(err)
  11424. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11425. return
  11426. }
  11427. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11428. }
  11429. }
  11430. func GetFpdetailFname(c *gin.Context) {
  11431. appG := app.Gin{C: c}
  11432. // id := c.Query("id")
  11433. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11434. fsion := gofasion.NewFasion(string(dataByte))
  11435. id := fsion.Get("id").ValueDefaultStr("")
  11436. tx := restful.Engine.NewSession()
  11437. defer tx.Close()
  11438. fpdetailFnameList := make([]*models.FpdetailFname, 0)
  11439. err := tx.SQL(` SELECT
  11440. TRIM(ftid)ftid,TRIM(fid)fid,
  11441. IFNULL((SELECT fname FROM feed WHERE pastureid =ftdetail.pastureid AND id = ftdetail.fid),ftdetail. fname) fname,
  11442. fweight,sort,
  11443. TRIM(ftdetail.id) id, fweight /(select sum(fweight) from ftdetail where ftid = (select ftid from feedp where barid = ? ) ) sumFweight
  11444. FROM
  11445. ftdetail
  11446. WHERE ( ftid=(select ftid from feedp where barid = ? )) AND is_show = 1
  11447. ORDER BY ftdetail.sort,ftdetail.id `, id, id).Find(&fpdetailFnameList)
  11448. if err != nil {
  11449. logs.Error(err)
  11450. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11451. return
  11452. }
  11453. fpdetailList := make([]*models.Fpdetail, 0)
  11454. err = tx.SQL(`select id,barid,barname,times,weight from fpdetail where barid = ?`, id).Find(&fpdetailList)
  11455. if err != nil {
  11456. logs.Error(err)
  11457. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11458. return
  11459. }
  11460. for _, f := range fpdetailFnameList {
  11461. f.FWeight = 0
  11462. for _, fpd := range fpdetailList {
  11463. value := f.SumFWeight * fpd.Weight
  11464. // 将其四舍五入到小数点后两位
  11465. roundedValue := math.Round(value*100) / 100
  11466. if fpd.Times == 1 {
  11467. f.TimesOne = roundedValue
  11468. } else if fpd.Times == 2 {
  11469. f.TimesTwo = roundedValue
  11470. } else if fpd.Times == 3 {
  11471. f.TimesThree = roundedValue
  11472. } else if fpd.Times == 4 {
  11473. f.TimesFour = roundedValue
  11474. } else if fpd.Times == 5 {
  11475. f.TimesFive = roundedValue
  11476. } else if fpd.Times == 6 {
  11477. f.TimesSix = roundedValue
  11478. }
  11479. f.FWeight += value
  11480. }
  11481. }
  11482. fpdetailFname := new(models.FpdetailFname)
  11483. fpdetailFname.FName = "合计"
  11484. for _, f := range fpdetailFnameList {
  11485. fpdetailFname.TimesOne += f.TimesOne
  11486. fpdetailFname.TimesTwo += f.TimesTwo
  11487. fpdetailFname.TimesThree += f.TimesThree
  11488. fpdetailFname.TimesFour += f.TimesFour
  11489. fpdetailFname.TimesFive += f.TimesFive
  11490. fpdetailFname.TimesSix += f.TimesSix
  11491. fpdetailFname.FWeight += f.FWeight
  11492. f.FWeight = RoundFloat(f.FWeight, 2)
  11493. }
  11494. // 在处理代码中
  11495. fpdetailFname.TimesOne = RoundFloat(fpdetailFname.TimesOne, 2)
  11496. fpdetailFname.TimesTwo = RoundFloat(fpdetailFname.TimesTwo, 2)
  11497. fpdetailFname.TimesThree = RoundFloat(fpdetailFname.TimesThree, 2)
  11498. fpdetailFname.TimesFour = RoundFloat(fpdetailFname.TimesFour, 2)
  11499. fpdetailFname.TimesFive = RoundFloat(fpdetailFname.TimesFive, 2)
  11500. fpdetailFname.TimesSix = RoundFloat(fpdetailFname.TimesSix, 2)
  11501. fpdetailFname.FWeight = RoundFloat(fpdetailFname.FWeight, 2)
  11502. fpdetailFnameList = append(fpdetailFnameList, fpdetailFname)
  11503. appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11504. }
  11505. func RoundFloat(x float64, prec int) float64 {
  11506. output := math.Pow(10, float64(prec))
  11507. return math.Round(x*output) / output
  11508. }
  11509. func GetLyUdData(c *gin.Context) {
  11510. appG := app.Gin{C: c}
  11511. // id := c.Query("id")
  11512. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11513. fsion := gofasion.NewFasion(string(dataByte))
  11514. myDate := fsion.Get("myDate").ValueDefaultStr("")
  11515. times := fsion.Get("Times").ValueDefaultStr("")
  11516. name := fsion.Get("name").ValueDefaultStr("")
  11517. tx := restful.Engine.NewSession()
  11518. defer tx.Close()
  11519. if name == "dateplanlist" {
  11520. data, err := tx.SQL(`select dl.id as did,if(dl.HaveButton=1,1,0) isDo, dl.id as id,dl.ProjName,dl.tmrtname TNAME, '' DNAME,DATE_FORMAT(dl.Mydate,'%Y-%m-%d') Mydate,d2.xxwTempletCode fId,dl.templetName fName, DATE_FORMAT(dl.InTime,'%Y-%m-%d %H:%i:%s') benginTime,DATE_FORMAT(max(d2.Intime),'%Y-%m-%d %H:%i:%s') endDate, dl.Times as Times, dl.Sort ,'是' Status, p.pasturecode kptCattleId from downloadedplan dl
  11521. join pasture p on dl.pastureId=p.pastureid JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId
  11522. where dl.Mydate = ? AND dl.lpplanType =0 and dl.Times= ? GROUP BY dl.id union all
  11523. select dd.id as did,if(dd.HaveButton=1,1,0) isDo, dd.id as id,dd.ProjName,dd.tmrtname TNAME, '' DNAME,DATE_FORMAT(dd.Mydate,'%Y-%m-%d') Mydate,d2.xxwTempletCode fId,dd.templetName fName, DATE_FORMAT(dd.InTime,'%Y-%m-%d %H:%i:%s') benginTime,DATE_FORMAT(max(d2.Intime),'%Y-%m-%d %H:%i:%s') endDate, dd.Times as Times, dd.Sort ,'是' Status, p.pasturecode kptCattleId
  11524. from downloadedplan dl join pasture p on dl.pastureId=p.pastureid
  11525. JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId inner join downloadedplan dd on dd.pid=dl.pid and dd.mydate=dl.mydate and dd.lpplanType=1 and dl.pastureId=dd.pastureId
  11526. where dl.Mydate = ? AND dl.lpplanType =2 and dl.Times= ?
  11527. GROUP BY dl.id order by ProjName `, myDate, times, myDate, times).Query().List()
  11528. fmt.Println(err)
  11529. appG.Response(http.StatusOK, e.SUCCESS, data)
  11530. return
  11531. } else if name == "getAddFeed" {
  11532. data, _ := tx.SQL(`SELECT IF(d.HaveButton=1,1,0) isDo,d.id did,d.ProjName ProjName,date_format(d.mydate,'%Y-%m-%d') loadDate,d.Sort tmrNo,d.Times Times,ftd.xxwTempletCode fId,ftd.tname fName,d.tmrtname TNAME,f.fname FNAME, f.xxwFeedCode feedId,d1.SORT SORT,d1.feedallowratio allowableError,(select round(sum(if(ActualWeightMinus>0,ActualWeightMinus,0)),2) from downloadplandtl1 where PID = d.id and pastureId = d.pastureId ) LWEIGHT,
  11533. round(d1.lweight,2) expWeight,round(if(d1.actualweightminus>0,d1.actualweightminus,0),2) actualWeight,'' DNAME,if((select count(1) from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc) >0 ,(select DATE_FORMAT(InTime,'%Y-%m-%d %H:%i:%s') from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc limit 1),DATE_FORMAT(d.InTime,'%Y-%m-%d %H:%i:%s') ) startTime,
  11534. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM downloadedplan dd
  11535. JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11536. inner join downloadedplan d on dd.pid=d.pid and dd.mydate=d.mydate and d.lpplanType in (0,1) AND d.pastureId = dd.pastureId
  11537. join feedtemplet ftd on ftd.id = d.tempid and ftd.pastureId = d.pastureId
  11538. JOIN feed f ON f.id = d1.fid AND f.pastureId = d.pastureId
  11539. WHERE DATE_FORMAT(dd.Mydate ,'%Y-%m-%d' ) = ? and dd.Times =? and d1.type = 0
  11540. UNION ALL SELECT IF(d.HaveButton=1,1,0) isDo,d.id did,d.ProjName ProjName,date_format(d.mydate,'%Y-%m-%d') loadDate,d.Sort tmrNo,d.Times Times,ftd.xxwTempletCode fId,ftd.tname fName,d.tmrtname TNAME,f.fname FNAME, f.xxwFeedCode feedId,d1.SORT SORT,d1.feedallowratio allowableError,(select round(sum(if(ActualWeightMinus>0,ActualWeightMinus,0)),2) from downloadplandtl1 where PID = d.id and pastureId = d.pastureId and type = 0) LWEIGHT,
  11541. round(d1.LWEIGHT *(ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and ftid = ftdd.ftid and pastureId = d.pastureId )),2) expWeight,
  11542. round((if(d1.ActualWeightMinus>0,d1.ActualWeightMinus,0)) * (ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and pastureId = d.pastureId and ftid = ftdd.ftid )),2) actualWeight,
  11543. '' DNAME ,if((select count(1) from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc) >0 ,(select DATE_FORMAT(InTime,'%Y-%m-%d %H:%i:%s') from downloadplandtl1 where pid = d.id and sort < d1.sort and pastureId = d.pastureId order by sort desc limit 1),DATE_FORMAT(d.InTime,'%Y-%m-%d %H:%i:%s') ) startTime,
  11544. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM
  11545. downloadedplan dd JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11546. inner join downloadedplan d on dd.pid=d.pid and dd.mydate=d.mydate and d.lpplanType in (0,1) AND d.pastureId = dd.pastureId
  11547. join feedtemplet ftd on ftd.id = d1.fid and ftd.pastureId = d.pastureId
  11548. join ftdetaildate ftdd on ftdd.ftid = ftd.id and ftdd.date = d.Mydate and ftdd.pastureId = d.pastureId
  11549. join feed f on f.id = ftdd.fid and f.pastureId = d.pastureId
  11550. WHERE DATE_FORMAT( dd.Mydate ,'%Y-%m-%d' ) = ? AND dd.Times = ? and d1.type = 0 and d1.feedcode = -1 `, myDate, times, myDate, times).Query().List()
  11551. appG.Response(http.StatusOK, e.SUCCESS, data)
  11552. return
  11553. } else if name == "getDeleteFeed" {
  11554. data, _ := tx.SQL(`SELECT if(d.HaveButton=1,1,0) isDo,date_format(d.mydate,'%Y-%m-%d') as dropDate,d.SORT as tmrNo,d.Times as Times, d2.Fname as penName,d2.cowcount as cowCount,d.tmrtname TNAME, d2.SORT as SORT, d2.LWEIGHT as expWeight,if(d2.ActualWeightMinus>0,d2.ActualWeightMinus,0) as actualWeight,
  11555. date_format(timestamp(d2.InTime,CONCAT('-',d2.processTime)),'%Y-%m-%d %H:%i:%s') as startTime, date_format(d2.InTime,'%Y-%m-%d %H:%i:%s') as endTime,'' as DNAME ,
  11556. (select ProjName from downloadedplan dd where dd.pid=d.pid and dd.mydate=d.mydate and dd.lpplanType in (0,1) AND d.pastureId = dd.pastureId) ProjName
  11557. ,d2.xxwBarCode as penId,if(d.lpplanType=2,(select id from downloadedplan p where p.pid=d.pid and p.mydate=? and p.Times=?
  11558. and p.lpplanType=1 limit 1),d2.pid) Id from downloadedplan d LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID
  11559. and d.pastureId=d2.pastureId where d.mydate=? AND d.lpplanType in (0,2) and d.Times=?`, myDate, times, myDate, times).Query().List()
  11560. appG.Response(http.StatusOK, e.SUCCESS, data)
  11561. return
  11562. }
  11563. // appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11564. }