ops.go 459 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668
  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. fmt.Println(time.Now())
  217. if sqlnamestr == "getHomepageStr" {
  218. parammaps := fsion.Get("parammaps")
  219. pastureid := parammaps.Get("pastureid").ValueStr()
  220. var montimeList []float64
  221. var montime float64
  222. var wg sync.WaitGroup
  223. now := time.Now()
  224. for i := 0; i < 30; i++ {
  225. wg.Add(1)
  226. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  227. go func(nowstr string) {
  228. defer wg.Done()
  229. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  230. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  231. if len(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})) > 0 {
  232. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  233. montimeList = append(montimeList, m)
  234. }
  235. }(nowstr)
  236. }
  237. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  238. if err != nil {
  239. logging.Error("GetDataByName err: ", err)
  240. msg := geterrmsg(err.Error())
  241. appG.Response(http.StatusOK, e.ERROR, msg)
  242. }
  243. wg.Wait()
  244. for _, m := range montimeList {
  245. montime += m
  246. }
  247. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  248. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  249. return
  250. }
  251. // if sqlnamestr == "getHomepageStr" {
  252. // }
  253. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  254. if err != nil {
  255. logging.Error("GetDataByName err: ", err)
  256. msg := geterrmsg(err.Error())
  257. appG.Response(http.StatusOK, e.ERROR, msg)
  258. } else {
  259. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  260. }
  261. }
  262. } else {
  263. appG.Response(http.StatusOK, e.SUCCESS, nil)
  264. }
  265. }
  266. // @Summary 根据APISQL表中SQL执行得到数据集
  267. // @Tags GetDataByName
  268. // @Accept json
  269. // @Produce json
  270. // @Param sqlname body string true "sqlname"
  271. // @Param offset body int true "offset"
  272. // @Param pagecount body int true "pagecount"
  273. // @Param returntype body string true "returntype"
  274. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  275. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  276. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  277. // @Router /data/GetDataByName [POST]
  278. func GetDataBySqlIN(c *gin.Context) {
  279. appG := app.Gin{C: c}
  280. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  281. fsion := gofasion.NewFasion(string(dataByte))
  282. sqlnamestr := fsion.Get("name").ValueStr()
  283. offset := fsion.Get("offset").ValueDefaultInt(0)
  284. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  285. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  286. tx := restful.Engine.NewSession()
  287. err := tx.Begin()
  288. defer func() {
  289. switch {
  290. case err != nil:
  291. logging.Error("tx.Begin 事务启动失败__error:", err)
  292. if tx != nil {
  293. tx.Rollback()
  294. }
  295. default:
  296. if tx != nil {
  297. err = tx.Commit()
  298. }
  299. }
  300. if tx != nil {
  301. tx.Close()
  302. }
  303. }()
  304. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  305. if sql != "" {
  306. s_params := make([]interface{}, 0)
  307. if fsion.HasKey("parammaps") {
  308. parammaps := fsion.Get("parammaps")
  309. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  310. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  311. }
  312. paramslist := strings.Split(p, ",")
  313. if len(paramslist) > 0 && p != "" {
  314. for _, value := range paramslist {
  315. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  316. if tempv, exists := c.Get("jwt_username"); exists {
  317. s_params = append(s_params, tempv.(string))
  318. } else {
  319. s_params = append(s_params, "")
  320. }
  321. } else {
  322. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  323. }
  324. }
  325. }
  326. } else if fsion.HasKey("params") {
  327. params := fsion.Get("params").Array()
  328. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  329. for _, v_params := range params {
  330. s_params = append(s_params, v_params.ValueStr())
  331. }
  332. }
  333. if returntype == "xlsx" {
  334. var xlsxfile *xlsx.File
  335. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  336. //c.File("c:/dd.xlsx")
  337. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  338. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  339. c.Header("Content-Transfer-Encoding", "binary")
  340. _ = xlsxfile.Write(c.Writer)
  341. } else {
  342. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  343. if err != nil {
  344. logging.Error("GetDataByName err: ", err)
  345. msg := geterrmsg(err.Error())
  346. appG.Response(http.StatusOK, e.ERROR, msg)
  347. } else {
  348. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  349. }
  350. }
  351. } else {
  352. appG.Response(http.StatusOK, e.SUCCESS, nil)
  353. }
  354. }
  355. // 错误处理
  356. // 将报错信息处理成汉字
  357. func geterrmsg(errstr string) (msgstr string) {
  358. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  359. rs := []rune(errstr)
  360. if hzRegexp.MatchString(string(rs[0])) {
  361. msgstr = errstr
  362. return
  363. }
  364. if strings.Contains(errstr, "Duplicate entry") {
  365. strs := strings.Split(errstr, ` key '`)
  366. if len(strs) > 1 {
  367. if len(strs[len(strs)-1]) > 1 {
  368. errstr = "Duplicate entry :" + strs[len(strs)-1]
  369. }
  370. }
  371. }
  372. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  373. if err != nil {
  374. msgstr = errstr
  375. return
  376. }
  377. if msg == nil || len(msg) == 0 {
  378. var param []interface{}
  379. param = append(param, errstr, errstr)
  380. go func() {
  381. tx := restful.Engine.NewSession()
  382. err := tx.Begin()
  383. defer func() {
  384. switch {
  385. case err != nil:
  386. logging.Error("tx.Begin 事务启动失败__error:", err)
  387. if tx != nil {
  388. tx.Rollback()
  389. }
  390. default:
  391. if tx != nil {
  392. err = tx.Commit()
  393. }
  394. }
  395. if tx != nil {
  396. tx.Close()
  397. }
  398. }()
  399. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  400. if err != nil {
  401. logging.Error("insert into err_msg(err,msg) err", err)
  402. }
  403. }()
  404. msgstr = errstr
  405. } else {
  406. msgstr = msg[0]["msg"]
  407. }
  408. return
  409. }
  410. // @Summary 根据APISQL表中SQL执行得到数据集
  411. // @Tags GetDataByNameForm
  412. // @Accept json
  413. // @Produce json
  414. // @Param sqlname body json true "sqlname"
  415. // @Param offset query int true "offset"
  416. // @Param pagecount query int true "pagecount"
  417. // @Param returntype query string true "returntype"
  418. // @Param s formData json true "ss"
  419. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  420. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  421. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  422. // @Router /data/GetDataByNameForm [POST]
  423. func GetDataByNameForm(c *gin.Context) {
  424. appG := app.Gin{C: c}
  425. //sqlnamestr := c.PostForm("measureNumber")
  426. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  427. //fsion := gofasion.NewFasion(string(dataByte))
  428. //sqlnamestr := fsion.Get("name").ValueStr()
  429. //offset := fsion.Get("offset").ValueInt()
  430. //pagecount := fsion.Get("pagecount").ValueInt()
  431. //returntype := fsion.Get("returntype").ValueStr()
  432. //params := fsion.Get("params").Array()
  433. c.Request.ParseForm()
  434. params := c.Request.Form
  435. offset := 0
  436. pageSize_ := 0
  437. returntype := params.Get("page")
  438. if returntype == "" {
  439. returntype = "0"
  440. }
  441. if tempv, exists := c.Get("jwt_username"); exists {
  442. params.Set("JwtUserName", tempv.(string))
  443. } else {
  444. params.Set("JwtUserName", "")
  445. }
  446. sqlnamestr := params.Get("name")
  447. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  448. s_params := make([]interface{}, 0)
  449. if returntype == "1" {
  450. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  451. if error != nil {
  452. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  453. }
  454. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  455. if error != nil {
  456. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  457. }
  458. pageSize_ = pageSize
  459. offset = pageNum
  460. }
  461. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  462. paramslist := strings.Split(p, ",")
  463. if len(paramslist) > 0 && p != "" {
  464. for _, value := range paramslist {
  465. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  466. }
  467. }
  468. if sql != "" {
  469. if returntype == "xlsx" {
  470. var xlsxfile *xlsx.File
  471. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  472. c.Header("Content-Type", "application/octet-stream")
  473. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  474. c.Header("Content-Transfer-Encoding", "binary")
  475. _ = xlsxfile.Write(c.Writer)
  476. } else {
  477. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  478. if err != nil {
  479. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  480. } else {
  481. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  482. }
  483. }
  484. } else {
  485. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  486. }
  487. }
  488. // @Summary 递归获取所有
  489. // @Tags menu
  490. // @Accept json
  491. // @Produce json
  492. // @Param Ton query string true "Ton"
  493. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  494. // @Router /authdata/GetRoleMenus [GET]
  495. func GetRecuDataByName(c *gin.Context) {
  496. appG := app.Gin{C: c}
  497. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  498. fsion := gofasion.NewFasion(string(dataByte))
  499. sqlnamestr := fsion.Get("name").ValueStr()
  500. parentidname := fsion.Get("idname").ValueStr()
  501. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  502. params := make(map[string]interface{})
  503. s_params := make([]interface{}, 0)
  504. if fsion.HasKey("params") {
  505. for _, v_params := range fsion.Get("params").Array() {
  506. s_params = append(s_params, v_params.ValueStr())
  507. }
  508. params["params"] = s_params
  509. } else {
  510. jparams := fsion.Get("parammaps")
  511. paramslist := strings.Split(p, ",")
  512. if len(paramslist) > 0 && p != "" {
  513. for _, value := range paramslist {
  514. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  515. if tempv, exists := c.Get("jwt_username"); exists {
  516. params[value] = tempv.(string)
  517. } else {
  518. params[value] = ""
  519. }
  520. } else {
  521. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  522. }
  523. }
  524. }
  525. }
  526. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  527. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  528. if err != nil {
  529. appG.Response(http.StatusOK, e.ERROR, err.Error())
  530. }
  531. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  532. }
  533. // @Summary 根据APISQL表中SQL执行得到数据集
  534. // @Tags GetDataByNames
  535. // @Accept json
  536. // @Produce json
  537. // @RequestBody sqlname query string true "sqlname"
  538. // @Param offset query int true "offset"
  539. // @Param pagecount query int true "pagecount"
  540. // @Param returntype query string true "returntype"
  541. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  542. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  543. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  544. // @Router /data/GetDataByNames [POST]
  545. func GetDataByNames(c *gin.Context) {
  546. appG := app.Gin{C: c}
  547. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  548. fsion := gofasion.NewFasion(string(dataByte))
  549. sqlParams := fsion.Array()
  550. queryData := make(map[string]interface{})
  551. for _, v := range sqlParams {
  552. fsion2 := gofasion.NewFasion(v.Json())
  553. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  554. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  555. if sql == "" {
  556. errorm := make(map[string]interface{})
  557. errorm["code"] = e.ERROR
  558. errorm["message"] = "sql没找到"
  559. queryData[fsion2.Get("name").ValueStr()] = errorm
  560. continue
  561. } else if sql != "" {
  562. offset := fsion2.Get("offset").ValueInt()
  563. pagecount := fsion2.Get("pagecount").ValueInt()
  564. returntype := fsion2.Get("returntype").ValueStr()
  565. s_params := make([]interface{}, 0)
  566. if fsion2.HasKey("parammaps") {
  567. parammaps := fsion2.Get("parammaps")
  568. paramslist := strings.Split(p, ",")
  569. if len(paramslist) > 0 && p != "" {
  570. for _, value := range paramslist {
  571. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  572. if tempv, exists := c.Get("jwt_username"); exists {
  573. s_params = append(s_params, tempv.(string))
  574. } else {
  575. s_params = append(s_params, "")
  576. }
  577. } else {
  578. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  579. }
  580. }
  581. }
  582. } else if fsion2.HasKey("params") {
  583. params := fsion2.Get("params").Array()
  584. for _, v_params := range params {
  585. s_params = append(s_params, v_params.ValueStr())
  586. }
  587. }
  588. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  589. if err != nil {
  590. errorm := make(map[string]interface{})
  591. errorm["code"] = e.ERROR
  592. errorm["message"] = err.Error()
  593. queryData[fsion2.Get("name").ValueStr()] = errorm
  594. logging.Error("GetDataByNames err: ", err)
  595. continue
  596. } else {
  597. queryData[fsion2.Get("name").ValueStr()] = queryData1
  598. }
  599. }
  600. }
  601. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  602. }
  603. // @Summary 根据APISQL表中SQL执行得到数据集
  604. // @Tags PostDataByNameForm
  605. // @Accept json
  606. // @Produce json
  607. // @Param sqlname query string true "sqlname"
  608. // @Param offset query int true "offset"
  609. // @Param pagecount query int true "pagecount"
  610. // @Param returntype query string true "returntype"
  611. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  612. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  613. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  614. // @Router /data/PostDataByNameForm [POST]
  615. func PostDataByNameForm(c *gin.Context) {
  616. appG := app.Gin{C: c}
  617. c.Request.ParseForm()
  618. params := c.Request.Form
  619. sqlnamestr := params.Get("name")
  620. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  621. s_params := make([]interface{}, 0)
  622. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  623. paramslist := strings.Split(p, ",")
  624. if len(paramslist) > 0 {
  625. for _, value := range paramslist {
  626. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  627. }
  628. }
  629. if sql != "" {
  630. queryData, err := execDataBySql(sql, s_params)
  631. if err != nil {
  632. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  633. } else {
  634. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  635. }
  636. } else {
  637. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  638. }
  639. }
  640. // GetReportform 将数据集转换格式
  641. // @Tags PostDataByNameForm
  642. // @Accept json
  643. // @Produce json
  644. // @Param sqlname query string true "sqlname"
  645. // @Param offset query int true "offset"
  646. // @Param pagecount query int true "pagecount"
  647. // @Param returntype query string true "returntype"
  648. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  649. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  650. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  651. func GetReportform(c *gin.Context) {
  652. appG := app.Gin{C: c}
  653. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  654. fsion := gofasion.NewFasion(string(dataByte))
  655. sqlnamestr := fsion.Get("name").ValueStr()
  656. checked := fsion.Get("checked").ValueStr()
  657. offset := fsion.Get("offset").ValueDefaultInt(0)
  658. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  659. parammaps := fsion.Get("parammaps")
  660. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  661. mode := parammaps.Get("mode").ValueDefaultInt(0)
  662. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  663. tx := restful.Engine.NewSession()
  664. err := tx.Begin()
  665. defer func() {
  666. switch {
  667. case err != nil:
  668. if tx != nil {
  669. tx.Rollback()
  670. }
  671. default:
  672. if tx != nil {
  673. err = tx.Commit()
  674. }
  675. }
  676. if tx != nil {
  677. tx.Close()
  678. }
  679. }()
  680. //fmt.Println("***************************************")
  681. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea, mode)
  682. if err != nil {
  683. appG.Response(http.StatusOK, e.ERROR, err.Error())
  684. } else {
  685. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  686. }
  687. }
  688. // GetUpkeepPlan 保养计划
  689. func GetUpkeepPlan(c *gin.Context) {
  690. appG := app.Gin{C: c}
  691. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  692. fsion := gofasion.NewFasion(string(dataByte))
  693. sqlnamestr := fsion.Get("name").ValueStr()
  694. offset := fsion.Get("offset").ValueDefaultInt(0)
  695. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  696. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  697. month := fsion.Get("month").ValueDefaultStr("map")
  698. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  699. tx := restful.Engine.NewSession()
  700. err := tx.Begin()
  701. defer func() {
  702. switch {
  703. case err != nil:
  704. if tx != nil {
  705. tx.Rollback()
  706. }
  707. default:
  708. if tx != nil {
  709. err = tx.Commit()
  710. }
  711. }
  712. if tx != nil {
  713. tx.Close()
  714. }
  715. }()
  716. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  717. if sql != "" {
  718. s_params := make([]interface{}, 0)
  719. if fsion.HasKey("parammaps") {
  720. parammaps := fsion.Get("parammaps")
  721. paramslist := strings.Split(p, ",")
  722. if len(paramslist) > 0 && p != "" {
  723. for _, value := range paramslist {
  724. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  725. if tempv, exists := c.Get("jwt_username"); exists {
  726. s_params = append(s_params, tempv.(string))
  727. } else {
  728. s_params = append(s_params, "")
  729. }
  730. } else {
  731. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  732. }
  733. }
  734. }
  735. } else if fsion.HasKey("params") {
  736. params := fsion.Get("params").Array()
  737. for _, v_params := range params {
  738. s_params = append(s_params, v_params.ValueStr())
  739. }
  740. }
  741. if returntype == "xlsx" {
  742. var xlsxfile *xlsx.File
  743. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  744. //c.File("c:/dd.xlsx")
  745. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  746. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  747. c.Header("Content-Transfer-Encoding", "binary")
  748. _ = xlsxfile.Write(c.Writer)
  749. } else {
  750. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  751. if err != nil {
  752. appG.Response(http.StatusOK, e.ERROR, err.Error())
  753. } else {
  754. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  755. if v, ok := value["id"]; ok {
  756. //month = "2020-03"
  757. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  758. if seviceplans != nil {
  759. for _, va := range seviceplans { //根据保养计划获取保养单
  760. //day,_ :=strconv.Atoi(va["day"])
  761. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  762. //buk := make(map[string]map[string]string)
  763. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  764. jstr := ""
  765. if bu["plantime"][8:9] == "0" {
  766. jstr = "m" + bu["plantime"][9:]
  767. } else {
  768. jstr = "m" + bu["plantime"][8:]
  769. }
  770. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  771. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  772. } else {
  773. if bu["flowCompeleted"] >= "2" {
  774. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  775. } else {
  776. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  777. }
  778. }
  779. }
  780. }
  781. }
  782. }
  783. }
  784. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  785. }
  786. }
  787. } else {
  788. appG.Response(http.StatusOK, e.SUCCESS, nil)
  789. }
  790. }
  791. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  792. // todo 优化性能 children统一查询
  793. // @Tags PostDataByNameForm
  794. // @Accept json
  795. // @Produce json
  796. // @Param sqlname query string true "sqlname"
  797. // @Param offset query int true "offset"
  798. // @Param pagecount query int true "pagecount"
  799. // @Param returntype query string true "returntype"
  800. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  801. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  802. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  803. func GetArrList(c *gin.Context) {
  804. appG := app.Gin{C: c}
  805. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  806. fsion := gofasion.NewFasion(string(dataByte))
  807. sqlnamestr := fsion.Get("name").ValueStr()
  808. sqlnamestr1 := fsion.Get("name1").ValueStr()
  809. offset := fsion.Get("offset").ValueDefaultInt(0)
  810. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  811. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  812. month := fsion.Get("month").ValueDefaultStr("map")
  813. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  814. tx := restful.Engine.NewSession()
  815. err := tx.Begin()
  816. defer func() {
  817. switch {
  818. case err != nil:
  819. if tx != nil {
  820. tx.Rollback()
  821. }
  822. default:
  823. if tx != nil {
  824. err = tx.Commit()
  825. }
  826. }
  827. if tx != nil {
  828. tx.Close()
  829. }
  830. }()
  831. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  832. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  833. if sql != "" {
  834. s_params := make([]interface{}, 0)
  835. if fsion.HasKey("parammaps") {
  836. parammaps := fsion.Get("parammaps")
  837. paramslist := strings.Split(p, ",")
  838. if len(paramslist) > 0 && p != "" {
  839. for _, value := range paramslist {
  840. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  841. if tempv, exists := c.Get("jwt_username"); exists {
  842. s_params = append(s_params, tempv.(string))
  843. } else {
  844. s_params = append(s_params, "")
  845. }
  846. } else {
  847. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  848. }
  849. }
  850. }
  851. }
  852. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  853. if err != nil {
  854. appG.Response(http.StatusOK, e.ERROR, err.Error())
  855. } else {
  856. paramslist1 := strings.Split(p1, ",")
  857. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  858. s_params1 := make([]interface{}, 0)
  859. if len(paramslist1) > 0 && p1 != "" {
  860. for _, v := range paramslist1 {
  861. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  862. }
  863. }
  864. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  865. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  866. }
  867. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  868. }
  869. } else {
  870. appG.Response(http.StatusOK, e.SUCCESS, nil)
  871. }
  872. }
  873. func GetAccount(c *gin.Context) {
  874. appG := app.Gin{C: c}
  875. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  876. fsion := gofasion.NewFasion(string(dataByte))
  877. sqlnamestr := fsion.Get("name").ValueStr()
  878. offset := fsion.Get("offset").ValueDefaultInt(0)
  879. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  880. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  881. tx := restful.Engine.NewSession()
  882. err := tx.Begin()
  883. defer func() {
  884. switch {
  885. case err != nil:
  886. logging.Error("tx.Begin 事务启动失败__error:", err)
  887. if tx != nil {
  888. tx.Rollback()
  889. }
  890. default:
  891. if tx != nil {
  892. err = tx.Commit()
  893. }
  894. }
  895. if tx != nil {
  896. tx.Close()
  897. }
  898. }()
  899. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  900. if sql != "" {
  901. s_params := make([]interface{}, 0)
  902. if fsion.HasKey("parammaps") {
  903. parammaps := fsion.Get("parammaps")
  904. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  905. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  906. }
  907. paramslist := strings.Split(p, ",")
  908. if len(paramslist) > 0 && p != "" {
  909. for _, value := range paramslist {
  910. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  911. if tempv, exists := c.Get("jwt_username"); exists {
  912. s_params = append(s_params, tempv.(string))
  913. } else {
  914. s_params = append(s_params, "")
  915. }
  916. } else {
  917. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  918. }
  919. }
  920. }
  921. } else if fsion.HasKey("params") {
  922. params := fsion.Get("params").Array()
  923. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  924. for _, v_params := range params {
  925. s_params = append(s_params, v_params.ValueStr())
  926. }
  927. }
  928. if returntype == "xlsx" {
  929. var xlsxfile *xlsx.File
  930. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  931. //c.File("c:/dd.xlsx")
  932. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  933. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  934. c.Header("Content-Transfer-Encoding", "binary")
  935. _ = xlsxfile.Write(c.Writer)
  936. } else {
  937. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  938. if err != nil {
  939. logging.Error("GetDataByName err: ", err)
  940. msg := geterrmsg(err.Error())
  941. appG.Response(http.StatusOK, e.ERROR, msg)
  942. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  943. } else {
  944. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  945. }
  946. }
  947. } else {
  948. appG.Response(http.StatusOK, e.SUCCESS, nil)
  949. }
  950. }
  951. // PostDataByName 根据APISQL表中SQL执行得到数据集
  952. // @Accept json
  953. // @Produce json
  954. // @Param sqlname query string true "sqlname"
  955. // @Param offset query int true "offset"
  956. // @Param pagecount query int true "pagecount"
  957. // @Param returntype query string true "returntype"
  958. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  959. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  960. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  961. // @Router /data/PostDataByName [POST]
  962. func PostDataByName(c *gin.Context) {
  963. appG := app.Gin{C: c}
  964. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  965. fsion := gofasion.NewFasion(string(dataByte))
  966. var err error
  967. queryData, err := module.PostDataByName(c, fsion)
  968. if err != nil {
  969. appG.Response(http.StatusOK, e.ERROR, err.Error())
  970. return
  971. }
  972. var (
  973. keyWord string
  974. )
  975. switch fsion.Get("name").ValueStr() {
  976. case "insertFeedclass":
  977. keyWord = "feed"
  978. err = module.GroupCategorySync(keyWord, fsion)
  979. case "deleteFeedclass":
  980. keyWord = "feed_delete"
  981. err = module.GroupCategoryDelete(keyWord, fsion)
  982. case "insertCowclass":
  983. keyWord = "cow"
  984. err = module.GroupCategorySync(keyWord, fsion)
  985. case "deleteCowclass":
  986. keyWord = "cow_delete"
  987. err = module.GroupCategoryDelete(keyWord, fsion)
  988. // case "updateFT":
  989. // FtdetailSurplus(fsion)
  990. // case "updateFeed":
  991. // FeedSurplus(fsion)
  992. default:
  993. }
  994. if err != nil {
  995. logging.Error(keyWord, err)
  996. }
  997. if queryData != nil {
  998. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  999. return
  1000. }
  1001. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1002. }
  1003. //人脸识别/格润富德接口
  1004. func GetRJSBData(c *gin.Context) {
  1005. appG := app.Gin{C: c}
  1006. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1007. fsion := gofasion.NewFasion(string(dataByte))
  1008. sqlnamestr := fsion.Get("name").ValueStr()
  1009. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1010. offset := fsion.Get("offset").ValueDefaultInt(0)
  1011. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1012. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1013. month := fsion.Get("month").ValueDefaultStr("map")
  1014. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1015. pagecount = 1
  1016. tx := restful.Engine.NewSession()
  1017. err := tx.Begin()
  1018. defer func() {
  1019. switch {
  1020. case err != nil:
  1021. if tx != nil {
  1022. tx.Rollback()
  1023. }
  1024. default:
  1025. if tx != nil {
  1026. err = tx.Commit()
  1027. }
  1028. }
  1029. if tx != nil {
  1030. tx.Close()
  1031. }
  1032. }()
  1033. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1034. _, 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 )
  1035. where id = (select tmrid from downloadedplan d where d.pid = (select pid from downloadedplan where lpplantype = 5 and mydate =
  1036. date_format(now() ,'%Y-%m-%d') and havebutton = 1 and iscompleted= 0 ) and mydate = date_format(now() ,'%Y-%m-%d')
  1037. and lpplantype in(0,1)) `).Execute()
  1038. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1039. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1040. if sql != "" {
  1041. s_params := make([]interface{}, 0)
  1042. if fsion.HasKey("parammaps") {
  1043. parammaps := fsion.Get("parammaps")
  1044. paramslist := strings.Split(p, ",")
  1045. if len(paramslist) > 0 && p != "" {
  1046. for _, value := range paramslist {
  1047. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1048. if tempv, exists := c.Get("jwt_username"); exists {
  1049. s_params = append(s_params, tempv.(string))
  1050. } else {
  1051. s_params = append(s_params, "")
  1052. }
  1053. } else {
  1054. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1055. }
  1056. }
  1057. }
  1058. }
  1059. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1060. if err != nil {
  1061. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1062. } else {
  1063. paramslist1 := strings.Split(p1, ",")
  1064. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1065. s_params1 := make([]interface{}, 0)
  1066. if len(paramslist1) > 0 && p1 != "" {
  1067. for _, v := range paramslist1 {
  1068. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1069. }
  1070. }
  1071. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1072. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1073. }
  1074. var wg sync.WaitGroup
  1075. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1076. wg.Add(1)
  1077. go func(value map[string]interface{}) {
  1078. defer wg.Done()
  1079. // ,havebutton = 1
  1080. _, err = tx.SQL(`update downloadedplan set artificial = 2 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1081. }(value)
  1082. }
  1083. wg.Wait()
  1084. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1085. }
  1086. fmt.Println("先锋获取数据:", time.Now(), queryData)
  1087. } else {
  1088. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1089. }
  1090. }
  1091. func PostRJSBData(c *gin.Context) {
  1092. appG := app.Gin{C: c}
  1093. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1094. fsion := gofasion.NewFasion(string(dataByte))
  1095. logging.Info("PostRJSBData err: ", string(dataByte))
  1096. s_params := make([]interface{}, 0)
  1097. tx := restful.Engine.NewSession()
  1098. err := tx.Begin()
  1099. defer func() {
  1100. switch {
  1101. case err != nil:
  1102. if tx != nil {
  1103. tx.Rollback()
  1104. }
  1105. default:
  1106. if tx != nil {
  1107. err = tx.Commit()
  1108. }
  1109. }
  1110. if tx != nil {
  1111. tx.Close()
  1112. }
  1113. }()
  1114. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1115. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1116. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1117. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1118. if !fsion.HasKey("parammaps") {
  1119. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1120. return
  1121. }
  1122. parammaps := fsion.Get("parammaps")
  1123. paramslist := strings.Split(p, ",")
  1124. if len(paramslist) > 0 && p != "" {
  1125. for _, value := range paramslist {
  1126. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1127. }
  1128. }
  1129. projuctid := parammaps.Get("projuctid").ValueStr()
  1130. _, err = tx.SQL(`update tmr set concentrate = (select d.id from downloadedplan d
  1131. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1132. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1133. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1134. and lpplantype in(0,1)) `, projuctid, projuctid, projuctid, projuctid).Execute()
  1135. if err != nil {
  1136. logging.Error("PostRJSBData-0 err: ", err)
  1137. msg := geterrmsg(err.Error())
  1138. // appG.Response(http.StatusOK, e.ERROR, msg)
  1139. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1140. return
  1141. }
  1142. _, err = tx.SQL(sql, s_params...).Execute()
  1143. if err != nil {
  1144. logging.Error("PostRJSBData err: ", err)
  1145. msg := geterrmsg(err.Error())
  1146. // appG.Response(http.StatusOK, e.ERROR, msg)
  1147. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1148. return
  1149. }
  1150. s_params = make([]interface{}, 0)
  1151. paramslist = strings.Split(p1, ",")
  1152. if len(paramslist) > 0 && p1 != "" {
  1153. for _, value := range paramslist {
  1154. // if value == "ID" {
  1155. // id := parammaps.Get("ID").ValueStr()
  1156. // pastureid := parammaps.Get("pastureid").ValueStr()
  1157. // 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
  1158. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1159. // if err != nil {
  1160. // logging.Error("PostRJSBData err: ", err)
  1161. // msg := geterrmsg(err.Error())
  1162. // appG.Response(http.StatusOK, e.ERROR, msg)
  1163. // return
  1164. // }
  1165. // for _, item := range datalist {
  1166. // id = item["id"]
  1167. // }
  1168. // s_params = append(s_params, id)
  1169. // } else {
  1170. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1171. // }
  1172. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1173. }
  1174. }
  1175. _, err = tx.SQL(sql1, s_params...).Execute()
  1176. if err != nil {
  1177. logging.Error("PostRJSBData1 err: ", err)
  1178. msg := geterrmsg(err.Error())
  1179. appG.Response(http.StatusOK, e.ERROR, msg)
  1180. return
  1181. }
  1182. s_params = make([]interface{}, 0)
  1183. paramslist = strings.Split(p2, ",")
  1184. if len(paramslist) > 0 && p2 != "" {
  1185. for _, value := range paramslist {
  1186. if value == "ID" {
  1187. id := parammaps.Get("ID").ValueStr()
  1188. pastureid := parammaps.Get("pastureid").ValueStr()
  1189. 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
  1190. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1191. if err != nil {
  1192. logging.Error("PostRJSBData err: ", err)
  1193. msg := geterrmsg(err.Error())
  1194. appG.Response(http.StatusOK, e.ERROR, msg)
  1195. return
  1196. }
  1197. for _, item := range datalist {
  1198. id = item["id"]
  1199. }
  1200. s_params = append(s_params, id)
  1201. } else {
  1202. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1203. }
  1204. }
  1205. }
  1206. _, err = tx.SQL(sql2, s_params...).Execute()
  1207. if err != nil {
  1208. logging.Error("PostRJSBData2 err: ", err)
  1209. msg := geterrmsg(err.Error())
  1210. appG.Response(http.StatusOK, e.ERROR, msg)
  1211. return
  1212. }
  1213. s_params = make([]interface{}, 0)
  1214. paramslist = strings.Split(p3, ",")
  1215. if len(paramslist) > 0 && p3 != "" {
  1216. for _, value := range paramslist {
  1217. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1218. }
  1219. }
  1220. _, err = tx.SQL(sql3, s_params...).Execute()
  1221. if err != nil {
  1222. logging.Error("PostRJSBData3 err: ", err)
  1223. msg := geterrmsg(err.Error())
  1224. appG.Response(http.StatusOK, e.ERROR, msg)
  1225. return
  1226. }
  1227. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1228. }
  1229. func PostRJSBDatas(c *gin.Context) {
  1230. appG := app.Gin{C: c}
  1231. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1232. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1233. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1234. fmt.Println("先锋回传数据:", time.Now(), string(dataByte))
  1235. tx := restful.Engine.NewSession()
  1236. err := tx.Begin()
  1237. defer func() {
  1238. switch {
  1239. case err != nil:
  1240. if tx != nil {
  1241. tx.Rollback()
  1242. }
  1243. default:
  1244. if tx != nil {
  1245. err = tx.Commit()
  1246. }
  1247. }
  1248. if tx != nil {
  1249. tx.Close()
  1250. }
  1251. }()
  1252. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1253. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1254. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1255. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1256. for _, fsion := range fsions {
  1257. if !fsion.HasKey("parammaps") {
  1258. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1259. return
  1260. }
  1261. parammaps := fsion.Get("parammaps")
  1262. ID := parammaps.Get("ID").ValueStr()
  1263. if ID == "" {
  1264. continue
  1265. }
  1266. s_params := make([]interface{}, 0)
  1267. paramslist := strings.Split(p, ",")
  1268. if len(paramslist) > 0 && p != "" {
  1269. for _, value := range paramslist {
  1270. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1271. }
  1272. }
  1273. _, err := tx.SQL(sql, s_params...).Execute()
  1274. if err != nil {
  1275. logging.Error("PostRJSBData err: ", err)
  1276. msg := geterrmsg(err.Error())
  1277. // appG.Response(http.StatusOK, e.ERROR, msg)
  1278. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1279. return
  1280. }
  1281. s_params = make([]interface{}, 0)
  1282. paramslist = strings.Split(p1, ",")
  1283. if len(paramslist) > 0 && p1 != "" {
  1284. for _, value := range paramslist {
  1285. // if value == "ID" {
  1286. // id := parammaps.Get("ID").ValueStr()
  1287. // pastureid := parammaps.Get("pastureid").ValueStr()
  1288. // 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
  1289. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1290. // if err != nil {
  1291. // logging.Error("PostRJSBData err: ", err)
  1292. // msg := geterrmsg(err.Error())
  1293. // appG.Response(http.StatusOK, e.ERROR, msg)
  1294. // return
  1295. // }
  1296. // for _, item := range datalist {
  1297. // id = item["id"]
  1298. // }
  1299. // s_params = append(s_params, id)
  1300. // } else {
  1301. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1302. // }
  1303. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1304. }
  1305. }
  1306. _, err = tx.SQL(sql1, s_params...).Execute()
  1307. if err != nil {
  1308. logging.Error("PostRJSBData1 err: ", err)
  1309. msg := geterrmsg(err.Error())
  1310. appG.Response(http.StatusOK, e.ERROR, msg)
  1311. return
  1312. }
  1313. s_params = make([]interface{}, 0)
  1314. paramslist = strings.Split(p2, ",")
  1315. if len(paramslist) > 0 && p2 != "" {
  1316. for _, value := range paramslist {
  1317. if value == "ID" {
  1318. id := parammaps.Get("ID").ValueStr()
  1319. pastureid := parammaps.Get("pastureid").ValueStr()
  1320. 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
  1321. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1322. if err != nil {
  1323. logging.Error("PostRJSBData err: ", err)
  1324. msg := geterrmsg(err.Error())
  1325. appG.Response(http.StatusOK, e.ERROR, msg)
  1326. return
  1327. }
  1328. for _, item := range datalist {
  1329. id = item["id"]
  1330. }
  1331. s_params = append(s_params, id)
  1332. } else {
  1333. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1334. }
  1335. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1336. }
  1337. }
  1338. _, err = tx.SQL(sql2, s_params...).Execute()
  1339. if err != nil {
  1340. logging.Error("PostRJSBData2 err: ", err)
  1341. msg := geterrmsg(err.Error())
  1342. appG.Response(http.StatusOK, e.ERROR, msg)
  1343. return
  1344. }
  1345. s_params = make([]interface{}, 0)
  1346. paramslist = strings.Split(p3, ",")
  1347. if len(paramslist) > 0 && p3 != "" {
  1348. for _, value := range paramslist {
  1349. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1350. }
  1351. }
  1352. _, err = tx.SQL(sql3, s_params...).Execute()
  1353. if err != nil {
  1354. logging.Error("PostRJSBData3 err: ", err)
  1355. msg := geterrmsg(err.Error())
  1356. appG.Response(http.StatusOK, e.ERROR, msg)
  1357. return
  1358. }
  1359. // ALTER TABLE `tmr`
  1360. // ADD COLUMN `concentrate` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 未回传 1 已回传' AFTER `appoint`
  1361. projuctid := parammaps.Get("projuctid").ValueStr()
  1362. _, err = tx.SQL(`update tmr set xianfeng = 0, concentrate = (select d.id from downloadedplan d
  1363. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1364. and lpplantype in(0,1)) where id = (select tmrid from downloadedplan d
  1365. where d.pid = (select pid from downloadedplan where id = ?) and mydate =(select mydate from downloadedplan where id = ?)
  1366. and lpplantype in(0,1)) and ( select count(1) from downloadedplan where id = ? and iscompleted = 0 ) = 0 `,
  1367. projuctid, projuctid, projuctid, projuctid, projuctid).Execute()
  1368. if err != nil {
  1369. logging.Error("PostRJSBData-0 err: ", err)
  1370. msg := geterrmsg(err.Error())
  1371. // appG.Response(http.StatusOK, e.ERROR, msg)
  1372. appG.Response(http.StatusOK, e.SUCCESS, msg)
  1373. return
  1374. }
  1375. count, _ := tx.SQL(`select count(1) from downloadedplan where id = ? and iscompleted = 0`, projuctid).Count()
  1376. if count == 0 {
  1377. fmt.Println(projuctid, "先锋回传计划已完成", count, err)
  1378. }
  1379. }
  1380. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1381. }
  1382. // @Summary 根据APISQL表中SQL执行得到数据集
  1383. // @Tags ExecDataByConfig
  1384. // @Accept json
  1385. // @Produce json
  1386. // @Param sqlname query string true "sqlname"
  1387. // @Param offset query int true "offset"
  1388. // @Param pagecount query int true "pagecount"
  1389. // @Param returntype query string true "returntype"
  1390. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1391. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1392. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1393. // @Router /data/PostDataByName [POST]
  1394. func ExecDataByConfig(c *gin.Context) {
  1395. appG := app.Gin{C: c}
  1396. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1397. tempval_ := make(map[string]interface{})
  1398. tempCommon := make(map[string]interface{})
  1399. tempval := make([]map[string]interface{}, 0)
  1400. err := json.Unmarshal(dataByte, &tempval_)
  1401. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1402. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1403. if err != nil {
  1404. } else {
  1405. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1406. tempCommon = v
  1407. }
  1408. if v, ok := tempval_["data"].([]interface{}); ok {
  1409. for _, Tvalue := range v {
  1410. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1411. tempval = append(tempval, v1)
  1412. }
  1413. }
  1414. }
  1415. tx := restful.Engine.NewSession()
  1416. err := tx.Begin()
  1417. if err != nil {
  1418. logging.Error("tx.Begin 事务启动失败__error:", err)
  1419. }
  1420. defer func() {
  1421. switch {
  1422. case err != nil:
  1423. if tx != nil {
  1424. tx.Rollback()
  1425. }
  1426. default:
  1427. if tx != nil {
  1428. err = tx.Commit()
  1429. }
  1430. }
  1431. if tx != nil {
  1432. tx.Close()
  1433. }
  1434. }()
  1435. if err == nil {
  1436. if tempv, exists := c.Get("jwt_username"); exists {
  1437. tempCommon["jwt_username"] = tempv.(string)
  1438. }
  1439. for _, paramvalue := range tempval {
  1440. fmt.Println(paramvalue["name"])
  1441. if paramvalue["name"].(string) == "updateBigFP" {
  1442. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1443. if err != nil {
  1444. msg := geterrmsg(err.Error())
  1445. appG.Response(http.StatusOK, e.ERROR, msg)
  1446. return
  1447. }
  1448. }
  1449. }
  1450. for _, paramvalue := range tempval {
  1451. if _, ok := paramvalue["resultname"]; !ok {
  1452. paramvalue["resultname"] = paramvalue["name"]
  1453. }
  1454. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1455. if err != nil {
  1456. logging.Error("ExecDataParam error:", err)
  1457. break
  1458. }
  1459. // if paramvalue["name"].(string) == "createdownloadedplan" {
  1460. // checkPlan(tx, paramvalue, tempCommon, tempval, 0)
  1461. // }
  1462. }
  1463. if err == nil {
  1464. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1465. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1466. } else {
  1467. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1468. }
  1469. } else {
  1470. msg := geterrmsg(err.Error())
  1471. appG.Response(http.StatusOK, e.ERROR, msg)
  1472. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1473. }
  1474. }
  1475. }
  1476. if err != nil {
  1477. msg := geterrmsg(err.Error())
  1478. appG.Response(http.StatusOK, e.ERROR, msg)
  1479. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1480. }
  1481. }
  1482. func interfacetostring(val interface{}) string {
  1483. switch val.(type) {
  1484. case string:
  1485. ss := val.(string)
  1486. return ss
  1487. break
  1488. case int:
  1489. ss := val.(int)
  1490. return strconv.Itoa(ss)
  1491. break
  1492. case int64:
  1493. ss := val.(int64)
  1494. return strconv.FormatInt(ss, 10)
  1495. break
  1496. case float64:
  1497. ss := val.(float64)
  1498. return strconv.FormatFloat(ss, 'E', -1, 32)
  1499. break
  1500. }
  1501. return ""
  1502. }
  1503. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1504. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1505. tempstrb := strings.IndexAny(valuestring, "@")
  1506. tempstre := strings.IndexAny(valuestring, ".")
  1507. if tempstrb > -1 && tempstre > -1 {
  1508. for _, ParamMapList := range ParamMap {
  1509. if v, ok := ParamMapList["resultname"]; ok {
  1510. if v == valuestring[tempstrb+1:tempstre] {
  1511. if v1, ok := ParamMapList["resultmaps"]; ok {
  1512. if newA, ok := v1.([]map[string]interface{}); ok {
  1513. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1514. } else if newA, ok := v1.(map[string]interface{}); ok {
  1515. return interfacetostring(newA[valuestring[tempstre+1:]])
  1516. }
  1517. }
  1518. }
  1519. }
  1520. }
  1521. } else {
  1522. return valuestring
  1523. }
  1524. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1525. return fmt.Sprintf("%f", valuestring)
  1526. }
  1527. return ""
  1528. }
  1529. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1530. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1531. tempstrb := strings.IndexAny(valuestring, "@")
  1532. tempstre := strings.IndexAny(valuestring, ".")
  1533. if tempstrb > -1 && tempstre > -1 {
  1534. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1535. if s, ok := v.(string); ok {
  1536. return s
  1537. } else if s, ok := v.(float64); ok {
  1538. return strconv.FormatFloat(s, 'f', -1, 64)
  1539. // return strconv.FormatInt(int64(s), 10)
  1540. }
  1541. }
  1542. }
  1543. }
  1544. return ""
  1545. }
  1546. 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) {
  1547. sqlname := fasion["name"].(string)
  1548. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1549. if v, ok := fasion["type"]; ok {
  1550. sqltype = v.(string)
  1551. }
  1552. sql := ""
  1553. p := ""
  1554. s_params := make([]interface{}, 0)
  1555. if sqltype != "" {
  1556. sql, p = restful.GetSqlByName(sqlname, tx)
  1557. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1558. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1559. paramslist := strings.Split(p, ",")
  1560. if len(paramslist) > 0 && p != "" {
  1561. for _, value := range paramslist {
  1562. ss := ""
  1563. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1564. ids, err := setting.SnowIds.NextId()
  1565. if err != nil {
  1566. ids = time.Now().UnixNano()
  1567. logging.Info("create SnowIds err", err)
  1568. }
  1569. s_params = append(s_params, ids)
  1570. } else {
  1571. if ss == "" && CommonParamMap != nil {
  1572. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1573. ss = valuestring
  1574. tempstrb := strings.IndexAny(valuestring, "@")
  1575. tempstre := strings.IndexAny(valuestring, ".")
  1576. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1577. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1578. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1579. }
  1580. } else {
  1581. if sqlname != "checkPassword" && sqlname != "updatePwd" {
  1582. ss = ""
  1583. }
  1584. }
  1585. }
  1586. }
  1587. if ss == "" && ParentParamMap != nil {
  1588. ss = getParamValue_(v, value, ParentParamMap)
  1589. }
  1590. if ss == "" && sameParamMap != nil {
  1591. ss = getParamValue(v, value, sameParamMap)
  1592. }
  1593. if ss == "" && ParamMap != nil {
  1594. ss = getParamValue(v, value, ParamMap)
  1595. }
  1596. s_params = append(s_params, ss)
  1597. }
  1598. }
  1599. }
  1600. }
  1601. }
  1602. if sql == "" {
  1603. sqltype = ""
  1604. }
  1605. if sqltype == "s1" {
  1606. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1607. if v, ok := tempValParam.(map[string]interface{}); ok {
  1608. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1609. }
  1610. if err != nil {
  1611. return nil, err
  1612. }
  1613. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1614. if err != nil {
  1615. return nil, err
  1616. }
  1617. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1618. } else if sqltype == "sm" {
  1619. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1620. if v, ok := tempValParam.(map[string]interface{}); ok {
  1621. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1622. } else {
  1623. }
  1624. if err != nil {
  1625. return nil, err
  1626. }
  1627. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1628. if err != nil {
  1629. return nil, err
  1630. }
  1631. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1632. } else if sqltype == "v" {
  1633. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1634. if v, ok := tempValParam.(map[string]interface{}); ok {
  1635. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1636. } else {
  1637. }
  1638. if err != nil {
  1639. return nil, err
  1640. }
  1641. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1642. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1643. }
  1644. } else if sqltype == "e" {
  1645. tempVal_arrary := make([]map[string]interface{}, 0)
  1646. tempVal_map := make(map[string]interface{})
  1647. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1648. if err == nil {
  1649. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1650. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1651. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1652. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1653. return tempVal_arrary, err
  1654. }
  1655. return nil, err
  1656. } else {
  1657. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1658. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1659. if err != nil {
  1660. return nil, err
  1661. }
  1662. return nil, err
  1663. }
  1664. }
  1665. return nil, nil
  1666. }
  1667. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1668. var err error
  1669. subarray, ok := fasion["children"]
  1670. if ok {
  1671. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1672. tempVal_arrary := make([]map[string]interface{}, 0)
  1673. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1674. tempVal_ := make(map[string]interface{})
  1675. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1676. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1677. } else {
  1678. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1679. }
  1680. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1681. if err != nil {
  1682. return err
  1683. }
  1684. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1685. }
  1686. v.(map[string]interface{})["children"] = tempVal_arrary
  1687. }
  1688. }
  1689. return nil
  1690. }
  1691. // @Summary 删除图片
  1692. // @Tags RemovePicByName
  1693. // @Accept json
  1694. // @Produce json
  1695. // @Param sqlname query string true "sqlname"
  1696. // @Param offset query int true "offset"
  1697. // @Param pagecount query int true "pagecount"
  1698. // @Param returntype query string true "returntype"
  1699. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1700. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1701. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1702. // @Router /data/PostDataByName [POST]
  1703. func RemovePicByName(c *gin.Context) {
  1704. logging.Info("RemovePicByName ", c.Keys)
  1705. appG := app.Gin{C: c}
  1706. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1707. fsion := gofasion.NewFasion(string(dataByte))
  1708. sqlnamestr := fsion.Get("name").ValueStr()
  1709. picname := fsion.Get("picname").ValueStr()
  1710. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1711. params := fsion.Get("params").Array()
  1712. s_params := make([]interface{}, 0)
  1713. for _, v_params := range params {
  1714. s_params = append(s_params, v_params.ValueStr())
  1715. }
  1716. if sql != "" {
  1717. queryData, err := execDataBySql(sql, s_params)
  1718. if picname != "" {
  1719. // Destination
  1720. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1721. err := os.Remove(distPath) //删除文件test.txt
  1722. if err != nil {
  1723. //如果删除失败则输出 file remove Error!
  1724. fmt.Println("file remove Error!")
  1725. //输出错误详细信息
  1726. fmt.Printf("%s", err)
  1727. } else {
  1728. //如果删除成功则输出 file remove OK!
  1729. fmt.Print("file remove OK!")
  1730. }
  1731. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1732. err = os.Remove(distPath) //删除文件test.txt
  1733. if err != nil {
  1734. //如果删除失败则输出 file remove Error!
  1735. fmt.Println("file remove Error!")
  1736. //输出错误详细信息
  1737. fmt.Printf("%s", err)
  1738. } else {
  1739. //如果删除成功则输出 file remove OK!
  1740. fmt.Print("file remove OK!")
  1741. }
  1742. }
  1743. if err != nil {
  1744. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1745. } else {
  1746. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1747. }
  1748. } else {
  1749. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1750. }
  1751. }
  1752. // @Summary 删除文件
  1753. // @Tags RemoveFileByName
  1754. // @Accept json
  1755. // @Produce json
  1756. // @Param sqlname query string true "sqlname"
  1757. // @Param offset query int true "offset"
  1758. // @Param pagecount query int true "pagecount"
  1759. // @Param returntype query string true "returntype"
  1760. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1761. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1762. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1763. // @Router /data/PostDataByName [POST]
  1764. func RemoveFileByName(c *gin.Context) {
  1765. appG := app.Gin{C: c}
  1766. id := c.Param("id")
  1767. logging.Info("DownloadFile ", c.Keys, id)
  1768. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1769. if eqdoc == nil {
  1770. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1771. return
  1772. }
  1773. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1774. err = os.Remove(distPath) //删除文件test.txt
  1775. if err != nil {
  1776. //如果删除失败则输出 file remove Error!
  1777. fmt.Println("file remove Error!")
  1778. //输出错误详细信息
  1779. fmt.Printf("%s", err)
  1780. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1781. return
  1782. }
  1783. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1784. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1785. }
  1786. // @Summary 根据APISQL表中SQL执行得到数据集
  1787. // @Tags PostDataByName
  1788. // @Accept json
  1789. // @Produce json
  1790. // @Param sqlname query string true "sqlname"
  1791. // @Param offset query int true "offset"
  1792. // @Param pagecount query int true "pagecount"
  1793. // @Param returntype query string true "returntype"
  1794. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1795. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1796. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1797. // @Router /data/PostDataByName [POST]
  1798. func UpdateDataRelation(c *gin.Context) {
  1799. appG := app.Gin{C: c}
  1800. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1801. fsion := gofasion.NewFasion(string(dataByte))
  1802. tablename := fsion.Get("name").ValueStr()
  1803. dataname := fsion.Get("dataname").ValueStr()
  1804. datavalue := fsion.Get("datavalue").ValueStr()
  1805. valuename := fsion.Get("valuename").ValueStr()
  1806. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1807. values := fsion.Get("values").Array()
  1808. tx := restful.Engine.NewSession()
  1809. err := tx.Begin()
  1810. defer func() {
  1811. switch {
  1812. case err != nil:
  1813. if tx != nil {
  1814. tx.Rollback()
  1815. }
  1816. default:
  1817. if tx != nil {
  1818. err = tx.Commit()
  1819. }
  1820. }
  1821. if tx != nil {
  1822. tx.Close()
  1823. }
  1824. }()
  1825. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1826. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1827. d_params := make([]interface{}, 4)
  1828. d_params[0] = datavalue
  1829. s_params := ""
  1830. for _, v_values := range values {
  1831. d_params[1] = v_values.ValueStr()
  1832. if s_params == "" {
  1833. s_params = v_values.ValueStr()
  1834. } else {
  1835. s_params = s_params + "," + v_values.ValueStr()
  1836. }
  1837. d_params[2] = d_params[1]
  1838. d_params[3] = d_params[0]
  1839. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1840. if err != nil {
  1841. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1842. break
  1843. }
  1844. }
  1845. if s_params != "" {
  1846. deleteSqlstr := "delete from " + tablename + " " +
  1847. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1848. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1849. if err != nil {
  1850. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1851. } else if err == nil {
  1852. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1853. }
  1854. } else {
  1855. deleteSqlstr := "delete from " + tablename + " " +
  1856. " where " + dataname + " = " + datavalue
  1857. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1858. if err != nil {
  1859. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1860. } else if err == nil {
  1861. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1862. }
  1863. }
  1864. }
  1865. // @Summary 根据APISQL表中SQL执行得到数据集
  1866. // @Tags PostDatasByName
  1867. // @Accept json
  1868. // @Produce json
  1869. // @Param sqlname query string true "sqlname"
  1870. // @Param offset query int true "offset"
  1871. // @Param pagecount query int true "pagecount"
  1872. // @Param returntype query string true "returntype"
  1873. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1874. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1875. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1876. // @Router /data/PostDatasByName [POST]
  1877. func PostDataByNames(c *gin.Context) {
  1878. appG := app.Gin{C: c}
  1879. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1880. fsion := gofasion.NewFasion(string(dataByte))
  1881. sqlParams := fsion.Get("array").Array()
  1882. queryData := make(map[string]interface{})
  1883. for _, v := range sqlParams {
  1884. fsion2 := gofasion.NewFasion(v.Json())
  1885. ss := fsion2.Get("name")
  1886. aa := fsion2.Get("params")
  1887. fmt.Println(ss, aa)
  1888. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1889. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1890. if sql == "" {
  1891. errorm := make(map[string]interface{})
  1892. errorm["code"] = e.ERROR
  1893. errorm["message"] = "sql没有找到"
  1894. errorm["param"] = ""
  1895. queryData[fsion2.Get("name").ValueStr()] = errorm
  1896. continue
  1897. } else if sql != "" {
  1898. s_params := make([]interface{}, 0)
  1899. if fsion2.HasKey("parammaps") {
  1900. parammaps := fsion2.Get("parammaps")
  1901. paramslist := strings.Split(p, ",")
  1902. if len(paramslist) > 0 && p != "" {
  1903. for _, value := range paramslist {
  1904. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1905. if tempv, exists := c.Get("jwt_username"); exists {
  1906. s_params = append(s_params, tempv.(string))
  1907. } else {
  1908. s_params = append(s_params, "")
  1909. }
  1910. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1911. ids, err := setting.SnowIds.NextId()
  1912. if err != nil {
  1913. ids = time.Now().UnixNano()
  1914. logging.Info("create SnowIds err", err)
  1915. }
  1916. s_params = append(s_params, ids)
  1917. } else {
  1918. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1919. }
  1920. }
  1921. }
  1922. } else if fsion2.HasKey("params") {
  1923. params := fsion2.Get("params").Array()
  1924. //ids,err := setting.SnowIds.NextId()
  1925. //if err !=nil{
  1926. // ids = time.Now().UnixNano()
  1927. // logging.Info("create SnowIds err",err)
  1928. //}
  1929. //s_params = append(s_params, ids)
  1930. for _, v_params := range params {
  1931. s_params = append(s_params, v_params.ValueStr())
  1932. }
  1933. }
  1934. _, err := execDataBySql(sql, s_params)
  1935. if err != nil {
  1936. logging.Error("PostDataByName err: ", err)
  1937. errorm := make(map[string]interface{})
  1938. errorm["code"] = e.ERROR
  1939. errorm["message"] = err.Error()
  1940. errorm["param"] = s_params
  1941. queryData[fsion2.Get("name").ValueStr()] = errorm
  1942. continue
  1943. } else {
  1944. errorm := make(map[string]interface{})
  1945. errorm["code"] = e.SUCCESS
  1946. errorm["message"] = "success"
  1947. queryData[fsion2.Get("name").ValueStr()] = errorm
  1948. continue
  1949. }
  1950. } else {
  1951. errorm := make(map[string]interface{})
  1952. errorm["code"] = e.ERROR
  1953. errorm["message"] = "NO SQL"
  1954. errorm["param"] = ""
  1955. queryData[fsion2.Get("name").ValueStr()] = errorm
  1956. }
  1957. }
  1958. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1959. }
  1960. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1961. if offset > 0 {
  1962. offset = offset - 1
  1963. }
  1964. //if pagecount == 0 {
  1965. // pagecount = setting.AppSetting.PageSize
  1966. //}else if pagecount>setting.AppSetting.PageSize{
  1967. // pagecount = setting.AppSetting.PageSize
  1968. //}
  1969. if returntype == "list" {
  1970. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1971. return queryData, err
  1972. } else if returntype == "listlist" {
  1973. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1974. return queryData, err
  1975. } else {
  1976. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1977. return queryData, err
  1978. }
  1979. }
  1980. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1981. if offset > 0 {
  1982. offset = offset - 1
  1983. }
  1984. //if pagecount == 0 {
  1985. // pagecount = setting.AppSetting.PageSize
  1986. //}else if pagecount>setting.AppSetting.PageSize{
  1987. // pagecount = setting.AppSetting.PageSize
  1988. //}
  1989. if returntype == "list" {
  1990. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1991. return queryData, err
  1992. } else if returntype == "listlist" {
  1993. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1994. return queryData, err
  1995. } else {
  1996. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1997. return queryData, err
  1998. }
  1999. }
  2000. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  2001. paramslist := strings.Split(Params, ",")
  2002. s_params := make([]interface{}, 0)
  2003. if isList {
  2004. for _, v_params := range thisParams["params"].([]interface{}) {
  2005. s_params = append(s_params, v_params)
  2006. }
  2007. } else {
  2008. paramslist := strings.Split(Params, ",")
  2009. if len(paramslist) > 0 && Params != "" {
  2010. for _, value := range paramslist {
  2011. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2012. }
  2013. }
  2014. }
  2015. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  2016. for _, queryData_ := range queryData {
  2017. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  2018. if isList {
  2019. if queryData_[idname] != nil {
  2020. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  2021. }
  2022. } else {
  2023. if queryData_[idname] != nil {
  2024. thisParams[idname] = queryData_[idname].(interface{})
  2025. }
  2026. if len(paramslist) > 0 && Params != "" {
  2027. s_params = make([]interface{}, 0)
  2028. for _, value := range paramslist {
  2029. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2030. }
  2031. }
  2032. }
  2033. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  2034. } else {
  2035. }
  2036. }
  2037. return queryData, err
  2038. }
  2039. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2040. queryData, err := restful.ExecQuery(sqlstr, params)
  2041. return queryData, err
  2042. }
  2043. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2044. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2045. return queryData, err
  2046. }
  2047. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2048. queryData, err := restful.ExecQuery(sqlstr, params)
  2049. return queryData, err
  2050. }
  2051. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2052. // @Tags ImportExcel
  2053. // @Accept json
  2054. // @Produce json
  2055. // @Param file query string true "文件名"
  2056. // @Param name header string true "执行sql的名字"
  2057. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2058. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2059. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2060. // @Router /data/ImportExcel [POST]
  2061. func ImportExcel(c *gin.Context) {
  2062. appG := app.Gin{C: c}
  2063. inputdata := ""
  2064. c.Request.ParseForm()
  2065. params := c.Request.Form
  2066. file, _, err := c.Request.FormFile("file")
  2067. if err != nil {
  2068. appG.Response(http.StatusOK, e.ERROR, err)
  2069. return
  2070. }
  2071. sqlnamestrs := params.Get("name")
  2072. sheetname := params.Get("sheetname")
  2073. pastureid := params.Get("pastureid")
  2074. //importParams := params.Get("importParams")
  2075. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2076. // 必输项参数 (字符串格式 "field1,field2,field3")
  2077. requiredParams := params.Get("requiredParams")
  2078. // 日期参数
  2079. dateParams := params.Get("dateParams")
  2080. // 数字参数
  2081. numParams := params.Get("numParams")
  2082. //将字符串分割开
  2083. dateParamslist := strings.Split(dateParams, ",")
  2084. requiredParamslist := strings.Split(requiredParams, ",")
  2085. numParamslist := strings.Split(numParams, ",")
  2086. queryData := make([]interface{}, 0)
  2087. sqlslist := strings.Split(sqlnamestrs, ",")
  2088. xlsx1, err := excelize.OpenReader(file)
  2089. if err != nil {
  2090. fmt.Println(err)
  2091. return
  2092. }
  2093. ok := 0
  2094. error := 0
  2095. isdone := true
  2096. rows := xlsx1.GetRows(sheetname)
  2097. // 限制10000条,多余的截取掉
  2098. if len(rows) > 10000 {
  2099. rows = rows[:10000]
  2100. }
  2101. for i, row := range rows {
  2102. if i > 0 {
  2103. entry := make(map[string]interface{})
  2104. outentry := make(map[string]interface{})
  2105. for j, colCell := range rows[0] {
  2106. for k, colCell1 := range row {
  2107. if j == k {
  2108. outentry[colCell] = colCell1
  2109. entry[colCell] = colCell1
  2110. }
  2111. }
  2112. }
  2113. inputdata = ""
  2114. a := ""
  2115. fmt.Println(outentry, entry)
  2116. //校验日期格式
  2117. for _, v := range dateParamslist {
  2118. if v == "" {
  2119. continue
  2120. }
  2121. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2122. dtime, err := TransfTime(d.(string))
  2123. if err != nil {
  2124. a = strings.Trim(v, " ")
  2125. break
  2126. }
  2127. outentry[strings.Trim(v, " ")] = dtime
  2128. }
  2129. }
  2130. if a != "" {
  2131. outentry["error_msg"] = a + " 格式错误"
  2132. error++
  2133. queryData = append(queryData, outentry)
  2134. continue
  2135. }
  2136. a = ""
  2137. //校验必填格式
  2138. for _, v := range requiredParamslist {
  2139. if v == "" {
  2140. continue
  2141. }
  2142. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2143. a = strings.Trim(v, " ")
  2144. break
  2145. }
  2146. }
  2147. if a != "" {
  2148. outentry["error_msg"] = a + " 未填或格式错误"
  2149. error++
  2150. queryData = append(queryData, outentry)
  2151. continue
  2152. }
  2153. a = ""
  2154. //校验数字格式
  2155. for _, v := range numParamslist {
  2156. if v == "" {
  2157. continue
  2158. }
  2159. d, ok := outentry[strings.Trim(v, " ")]
  2160. if !ok || d == "" {
  2161. outentry[strings.Trim(v, " ")] = 0
  2162. } else {
  2163. var fl float64
  2164. switch d.(type) {
  2165. case string:
  2166. fl, err = strconv.ParseFloat(d.(string), 64)
  2167. }
  2168. if err != nil || fl < 0 {
  2169. a = strings.Trim(v, " ")
  2170. break
  2171. }
  2172. }
  2173. }
  2174. if a != "" {
  2175. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2176. error++
  2177. queryData = append(queryData, outentry)
  2178. continue
  2179. }
  2180. tx := restful.Engine.NewSession()
  2181. err := tx.Begin()
  2182. for _, sqlnamestr := range sqlslist {
  2183. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2184. paramslist := strings.Split(paramslists, ",")
  2185. if len(paramslist) > 0 {
  2186. s_params := make([]interface{}, 0)
  2187. for _, value := range paramslist {
  2188. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2189. if tempv, exists := c.Get("jwt_username"); exists {
  2190. s_params = append(s_params, tempv.(string))
  2191. } else {
  2192. s_params = append(s_params, "")
  2193. }
  2194. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2195. s_params = append(s_params, pastureid)
  2196. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2197. ids, err := setting.SnowIds.NextId()
  2198. if err != nil {
  2199. ids = time.Now().UnixNano()
  2200. logging.Info("create SnowIds err", err)
  2201. }
  2202. s_params = append(s_params, ids)
  2203. } else {
  2204. if outentry[strings.Trim(value, " ")] == nil {
  2205. s_params = append(s_params, "")
  2206. } else {
  2207. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2208. }
  2209. }
  2210. }
  2211. outentry["input"] = inputdata
  2212. fmt.Println(sql, s_params)
  2213. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2214. if err != nil {
  2215. if tx != nil {
  2216. tx.Rollback()
  2217. }
  2218. if tx != nil {
  2219. tx.Close()
  2220. }
  2221. msg := geterrmsg(err.Error())
  2222. outentry["error_msg"] = msg
  2223. error++
  2224. queryData = append(queryData, outentry)
  2225. isdone = true
  2226. break
  2227. } else {
  2228. if len(returnmsgmap1) > 0 {
  2229. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2230. if tx != nil {
  2231. tx.Rollback()
  2232. }
  2233. if tx != nil {
  2234. tx.Close()
  2235. }
  2236. msg := geterrmsg(va.(string))
  2237. outentry["error_msg"] = msg
  2238. error++
  2239. queryData = append(queryData, outentry)
  2240. isdone = true
  2241. break
  2242. }
  2243. }
  2244. isdone = false
  2245. }
  2246. }
  2247. }
  2248. switch {
  2249. case err != nil:
  2250. if tx != nil {
  2251. tx.Rollback()
  2252. }
  2253. default:
  2254. if tx != nil {
  2255. err = tx.Commit()
  2256. }
  2257. }
  2258. if tx != nil {
  2259. tx.Close()
  2260. }
  2261. }
  2262. if !isdone {
  2263. ok++
  2264. isdone = true
  2265. }
  2266. }
  2267. data := make(map[string]interface{})
  2268. data["result"] = queryData
  2269. data["success"] = ok
  2270. data["err_count"] = error
  2271. appG.Response(http.StatusOK, e.SUCCESS, data)
  2272. }
  2273. func TransfTime(timestr string) (string, error) {
  2274. if timestr == "" {
  2275. return time.Now().Format("2006-01-02"), nil
  2276. }
  2277. days, err := strconv.Atoi(timestr)
  2278. if err != nil {
  2279. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2280. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2281. }
  2282. _, 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. t, err := time.Parse("2006.01.02", timestr)
  2287. if err != nil {
  2288. return "", err
  2289. } else {
  2290. return t.Format("2006-01-02"), nil
  2291. }
  2292. } else {
  2293. return t.Format("2006-01-02"), nil
  2294. }
  2295. } else {
  2296. return timestr, nil
  2297. }
  2298. }
  2299. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2300. times = times.AddDate(0, 0, days)
  2301. return times.Format("2006-01-02"), nil
  2302. }
  2303. func Createchart(c *gin.Context) {
  2304. appG := app.Gin{C: c}
  2305. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2306. fsion := gofasion.NewFasion(string(dataByte))
  2307. chart_name := fsion.Get("chart_name").ValueStr()
  2308. desc := fsion.Get("desc").ValueStr()
  2309. pastureid := fsion.Get("pastureid").ValueStr()
  2310. source_id := fsion.Get("source_id").ValueStr()
  2311. emp := fsion.Get("emp").ValueStr()
  2312. content := fsion.Get("content").Json()
  2313. var mapResult map[string]interface{}
  2314. err1 := json.Unmarshal([]byte(content), &mapResult)
  2315. if err1 != nil {
  2316. fmt.Println("JsonToMapDemo err: ", err1)
  2317. }
  2318. tx := restful.Engine.NewSession()
  2319. err := tx.Begin()
  2320. defer func() {
  2321. switch {
  2322. case err != nil:
  2323. logging.Error("tx.Begin 事务启动失败__error:", err)
  2324. if tx != nil {
  2325. tx.Rollback()
  2326. }
  2327. default:
  2328. if tx != nil {
  2329. err = tx.Commit()
  2330. }
  2331. }
  2332. if tx != nil {
  2333. tx.Close()
  2334. }
  2335. }()
  2336. ids, err := setting.SnowIds.NextId()
  2337. if err != nil {
  2338. ids = time.Now().UnixNano()
  2339. logging.Info("create SnowIds err", err)
  2340. }
  2341. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2342. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2343. if err != nil {
  2344. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2345. } else {
  2346. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2347. }
  2348. }
  2349. func Updatedashboard(c *gin.Context) {
  2350. appG := app.Gin{C: c}
  2351. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2352. fsion := gofasion.NewFasion(string(dataByte))
  2353. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2354. pastureid := fsion.Get("pastureid").ValueStr()
  2355. content := fsion.Get("content").Json()
  2356. var mapResult map[string]interface{}
  2357. err1 := json.Unmarshal([]byte(content), &mapResult)
  2358. if err1 != nil {
  2359. fmt.Println("JsonToMapDemo err: ", err1)
  2360. }
  2361. layout := mapResult["layout"]
  2362. tx := restful.Engine.NewSession()
  2363. err := tx.Begin()
  2364. defer func() {
  2365. switch {
  2366. case err != nil:
  2367. logging.Error("tx.Begin 事务启动失败__error:", err)
  2368. if tx != nil {
  2369. tx.Rollback()
  2370. }
  2371. default:
  2372. if tx != nil {
  2373. err = tx.Commit()
  2374. }
  2375. }
  2376. if tx != nil {
  2377. tx.Close()
  2378. }
  2379. }()
  2380. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2381. if err != nil {
  2382. println("2", err.Error())
  2383. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2384. } else {
  2385. if exec != nil {
  2386. if exec[0]["content"] == nil {
  2387. mapR := make(map[string]interface{})
  2388. mapR["layout"] = layout
  2389. mjson, _ := json.Marshal(mapR)
  2390. mString := string(mjson)
  2391. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2392. if err3 != nil {
  2393. println("3", err3.Error())
  2394. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2395. } else {
  2396. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2397. }
  2398. } else {
  2399. var mapR map[string]interface{}
  2400. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2401. if err1 != nil {
  2402. fmt.Println("JsonToMapDemo err: ", err2)
  2403. }
  2404. mapR["layout"] = layout
  2405. mjson, _ := json.Marshal(mapR)
  2406. mString := string(mjson)
  2407. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2408. if err3 != nil {
  2409. println("3", err3.Error())
  2410. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2411. } else {
  2412. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2413. }
  2414. }
  2415. } else {
  2416. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2417. }
  2418. }
  2419. }
  2420. func ExecSQL(c *gin.Context) {
  2421. appG := app.Gin{C: c}
  2422. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2423. fsion := gofasion.NewFasion(string(dataByte))
  2424. content := fsion.Get("content").Json()
  2425. pastureid := fsion.Get("pastureid").ValueStr()
  2426. var mapResult map[string]interface{}
  2427. err1 := json.Unmarshal([]byte(content), &mapResult)
  2428. if err1 != nil {
  2429. fmt.Println("JsonToMapDemo err: ", err1)
  2430. }
  2431. sqlstr := "select "
  2432. groupstr := " GROUP BY "
  2433. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2434. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2435. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2436. }
  2437. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2438. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2439. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2440. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2441. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2442. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2443. sqlstr = sqlstr + tem + ","
  2444. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2445. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2446. sqlstr = sqlstr + tem + ","
  2447. } else {
  2448. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2449. sqlstr = sqlstr + tem + ","
  2450. }
  2451. }
  2452. if _, ok := mapResult["selectedCalcul2"]; ok {
  2453. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2454. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2455. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2456. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2457. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2458. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2459. sqlstr = sqlstr + tem + ","
  2460. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2461. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2462. sqlstr = sqlstr + tem + ","
  2463. } else {
  2464. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2465. sqlstr = sqlstr + tem + ","
  2466. }
  2467. }
  2468. }
  2469. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2470. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2471. sqlstr = sqlstr + " where pastureid=" + pastureid
  2472. if len(mapResult["filters"].([]interface{})) > 0 {
  2473. sqlstr = sqlstr + " and "
  2474. }
  2475. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2476. for _, value := range mapResult["filters"].([]interface{}) {
  2477. switch value.(map[string]interface{})["filterOperator"].(string) {
  2478. case ">", "=", "<", ">=", "<=", "!=", "like":
  2479. 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 "
  2480. case "IN":
  2481. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2482. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2483. sqlstr = sqlstr + value1.(string) + ","
  2484. }
  2485. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2486. sqlstr = sqlstr + ")" + " AND "
  2487. case "BETWEEN":
  2488. 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 "
  2489. }
  2490. }
  2491. if len(mapResult["filters"].([]interface{})) > 0 {
  2492. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2493. }
  2494. //
  2495. groupstr = groupstr[0 : len(groupstr)-1]
  2496. sqlstr = sqlstr + groupstr + " "
  2497. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2498. sqlstr = sqlstr + " order by "
  2499. }
  2500. //
  2501. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2502. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2503. sqlstr = sqlstr + value.(string) + " "
  2504. } else {
  2505. sqlstr = sqlstr + value.(string) + ","
  2506. }
  2507. }
  2508. //
  2509. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2510. tx := restful.Engine.NewSession()
  2511. err := tx.Begin()
  2512. defer func() {
  2513. switch {
  2514. case err != nil:
  2515. logging.Error("tx.Begin 事务启动失败__error:", err)
  2516. if tx != nil {
  2517. tx.Rollback()
  2518. }
  2519. default:
  2520. if tx != nil {
  2521. err = tx.Commit()
  2522. }
  2523. }
  2524. if tx != nil {
  2525. tx.Close()
  2526. }
  2527. }()
  2528. exec, err := tx.SQL(sqlstr).Query().List()
  2529. if err != nil {
  2530. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2531. } else {
  2532. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2533. }
  2534. }
  2535. func Dashboards(c *gin.Context) {
  2536. appG := app.Gin{C: c}
  2537. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2538. fsion := gofasion.NewFasion(string(dataByte))
  2539. sqlnamestr := fsion.Get("name").ValueStr()
  2540. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2541. offset := fsion.Get("offset").ValueDefaultInt(0)
  2542. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2543. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2544. month := fsion.Get("month").ValueDefaultStr("map")
  2545. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2546. tx := restful.Engine.NewSession()
  2547. err := tx.Begin()
  2548. defer func() {
  2549. switch {
  2550. case err != nil:
  2551. if tx != nil {
  2552. tx.Rollback()
  2553. }
  2554. default:
  2555. if tx != nil {
  2556. err = tx.Commit()
  2557. }
  2558. }
  2559. if tx != nil {
  2560. tx.Close()
  2561. }
  2562. }()
  2563. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2564. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2565. if sql != "" {
  2566. s_params := make([]interface{}, 0)
  2567. if fsion.HasKey("parammaps") {
  2568. parammaps := fsion.Get("parammaps")
  2569. paramslist := strings.Split(p, ",")
  2570. if len(paramslist) > 0 && p != "" {
  2571. for _, value := range paramslist {
  2572. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2573. if tempv, exists := c.Get("jwt_username"); exists {
  2574. s_params = append(s_params, tempv.(string))
  2575. } else {
  2576. s_params = append(s_params, "")
  2577. }
  2578. } else {
  2579. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2580. }
  2581. }
  2582. }
  2583. }
  2584. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2585. if err != nil {
  2586. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2587. } else {
  2588. //paramslist1 := strings.Split(p1, ",")
  2589. dids := make([]interface{}, 0)
  2590. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2591. var mapResult map[string]interface{}
  2592. dids = append(dids, value["dashboard_id"])
  2593. if value["content"] != nil {
  2594. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2595. if err1 != nil {
  2596. println("JsonToMapDemo1 err: ", err1)
  2597. }
  2598. temap := make(map[string]interface{})
  2599. tem := mapResult["layout"].([]interface{})
  2600. if v, ok := value["chartids"]; ok {
  2601. chartids := strings.Split(v.(string), ",")
  2602. for _, va := range chartids {
  2603. a := false
  2604. for _, v2 := range tem {
  2605. if v2.(map[string]interface{})["id"].(string) == va {
  2606. a = true
  2607. //println("va1======",va)
  2608. }
  2609. }
  2610. if !a {
  2611. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2612. va + "\",\"id\":\"" + va +
  2613. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2614. var mapTem map[string]interface{}
  2615. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2616. if err1 != nil {
  2617. println("JsonToMapDemo err: ", err1)
  2618. }
  2619. tem = append(tem, mapTem)
  2620. }
  2621. }
  2622. temap["layout"] = tem
  2623. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2624. }
  2625. } else {
  2626. temap := make(map[string]interface{})
  2627. tem := make([]interface{}, 0)
  2628. if v, ok := value["chartids"]; ok {
  2629. chartids := strings.Split(v.(string), ",")
  2630. for _, va := range chartids {
  2631. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2632. va + "\",\"id\":\"" + va +
  2633. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2634. var mapTem map[string]interface{}
  2635. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2636. if err1 != nil {
  2637. println("JsonToMapDemo err: ", err1)
  2638. }
  2639. tem = append(tem, mapTem)
  2640. }
  2641. temap["layout"] = tem
  2642. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2643. }
  2644. }
  2645. }
  2646. queryData.(map[string]interface{})["order"] = dids
  2647. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2648. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2649. }
  2650. } else {
  2651. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2652. }
  2653. }
  2654. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2655. fsion := gofasion.NewFasion(parammaps)
  2656. sqlnamestr := fsion.Get("name").ValueStr()
  2657. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2658. offset := fsion.Get("offset").ValueDefaultInt(0)
  2659. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2660. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2661. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2662. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2663. body := []byte("")
  2664. if sql != "" {
  2665. s_params := make([]interface{}, 0)
  2666. if fsion.HasKey("parammaps") {
  2667. parammaps := fsion.Get("parammaps")
  2668. paramslist := strings.Split(p, ",")
  2669. if len(paramslist) > 0 && p != "" {
  2670. for _, value := range paramslist {
  2671. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2672. }
  2673. }
  2674. }
  2675. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2676. if err != nil {
  2677. } else {
  2678. paramslist1 := strings.Split(p1, ",")
  2679. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2680. s_params1 := make([]interface{}, 0)
  2681. if len(paramslist1) > 0 && p1 != "" {
  2682. for _, v := range paramslist1 {
  2683. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2684. }
  2685. }
  2686. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2687. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2688. body, _ = json.Marshal(queryData)
  2689. }
  2690. }
  2691. }
  2692. bs := bytes.NewBuffer(body)
  2693. client := &http.Client{}
  2694. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2695. req, err := http.NewRequest(RequestMethod,
  2696. url,
  2697. bs,
  2698. )
  2699. if err != nil {
  2700. }
  2701. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2702. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2703. if err != nil {
  2704. // handle error
  2705. }
  2706. resp, err := client.Do(req)
  2707. if err != nil {
  2708. return ""
  2709. }
  2710. defer resp.Body.Close()
  2711. result_body, err := ioutil.ReadAll(resp.Body)
  2712. if err != nil {
  2713. return ""
  2714. }
  2715. fmt.Println(string(result_body))
  2716. return ""
  2717. }
  2718. func GetSummary(c *gin.Context) {
  2719. appG := app.Gin{C: c}
  2720. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2721. fsion := gofasion.NewFasion(string(dataByte))
  2722. offset := fsion.Get("offset").ValueDefaultInt(0)
  2723. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2724. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2725. parammaps := fsion.Get("parammaps")
  2726. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2727. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2728. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2729. tx := restful.Engine.NewSession()
  2730. defer tx.Close()
  2731. sqlnamestr := ""
  2732. if genre == "0" {
  2733. if status == "0" {
  2734. sqlnamestr = "getAccuracyJSY"
  2735. } else if status == "1" {
  2736. sqlnamestr = "getAccuracyHFT"
  2737. } else if status == "2" {
  2738. sqlnamestr = "getAccuracyHNS"
  2739. } else if status == "3" {
  2740. sqlnamestr = "getAccuracyHSC"
  2741. } else if status == "4" {
  2742. sqlnamestr = "getAccuracyHCC"
  2743. } else if status == "5" {
  2744. sqlnamestr = "getAccuracyMC"
  2745. } else if status == "6" {
  2746. sqlnamestr = "getAccuracyFeedHL"
  2747. } else if status == "7" {
  2748. sqlnamestr = "getAccuracyRT"
  2749. }
  2750. } else {
  2751. if status == "0" {
  2752. sqlnamestr = "getAccuracySCCJSY"
  2753. } else if status == "1" {
  2754. sqlnamestr = "getAccuracySFT"
  2755. } else if status == "2" {
  2756. sqlnamestr = "getAccuracySNS"
  2757. } else if status == "3" {
  2758. sqlnamestr = "getAccuracySSC"
  2759. } else if status == "4" {
  2760. sqlnamestr = "getAccuracySCC"
  2761. } else if status == "5" {
  2762. sqlnamestr = "getAccuracySLCL"
  2763. } else if status == "7" {
  2764. sqlnamestr = "getAccuracySCCRT"
  2765. }
  2766. }
  2767. if isDate == "1" {
  2768. sqlnamestr += "Date"
  2769. }
  2770. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2771. // fmt.Println(sqlnamestr, sql)
  2772. if sql != "" {
  2773. s_params := make([]interface{}, 0)
  2774. // if fsion.HasKey("parammaps") {
  2775. fmt.Println(s_params, "222", p)
  2776. paramslist := strings.Split(p, ",")
  2777. if len(paramslist) > 0 && p != "" {
  2778. for _, value := range paramslist {
  2779. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2780. if tempv, exists := c.Get("jwt_username"); exists {
  2781. s_params = append(s_params, tempv.(string))
  2782. } else {
  2783. s_params = append(s_params, "")
  2784. }
  2785. } else {
  2786. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2787. }
  2788. }
  2789. }
  2790. if returntype == "xlsx" {
  2791. var xlsxfile *xlsx.File
  2792. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2793. //c.File("c:/dd.xlsx")
  2794. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2795. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2796. c.Header("Content-Transfer-Encoding", "binary")
  2797. _ = xlsxfile.Write(c.Writer)
  2798. } else {
  2799. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2800. if err != nil {
  2801. logging.Error("GetDataByName err: ", err)
  2802. msg := geterrmsg(err.Error())
  2803. appG.Response(http.StatusOK, e.ERROR, msg)
  2804. } else {
  2805. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2806. }
  2807. }
  2808. } else {
  2809. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2810. }
  2811. }
  2812. // type lpplanStruct struct {
  2813. // Id int64 `xorm:"id"`
  2814. // Tmrname string `xorm:"tmrname"`
  2815. // Tmrid int64 `xorm:"tmrid"`
  2816. // Sort int64 `xorm:"sort"`
  2817. // Sel int64 `xorm:"sel"`
  2818. // Times int64 `xorm:"times"`
  2819. // Ftname string `xorm:"ftname"`
  2820. // Ftid int64 `xorm:"ftid"`
  2821. // Maxweight float64 `xorm:"maxweight"`
  2822. // Sumweight float64 `xorm:"sumweight"`
  2823. // Sumcowcount int64 `xorm:"sumcowcount"`
  2824. // Pastureid string `xorm:"pastureid"`
  2825. // Display string `xorm:"display"`
  2826. // Issplit int64 `xorm:"issplit"`
  2827. // BeginTime string `xorm:"begintime"`
  2828. // }
  2829. func UpdateFTdetail(c *gin.Context) {
  2830. appG := app.Gin{C: c}
  2831. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2832. tempval_ := make(map[string]interface{})
  2833. tempCommon := make(map[string]interface{})
  2834. tempval := make([]map[string]interface{}, 0)
  2835. fTChange := make(map[string]interface{}, 0)
  2836. // fpdOldDataList := make([]map[string]interface{}, 0)
  2837. // fpdDataList := make([]map[string]interface{}, 0)
  2838. fsion := gofasion.NewFasion(string(dataByte))
  2839. // parammaps := fsion.Get("parammaps")
  2840. createdate := time.Now().Format("2006-01-02 15:04:05")
  2841. err := json.Unmarshal(dataByte, &tempval_)
  2842. if err != nil {
  2843. appG.Response(http.StatusOK, e.ERROR, false)
  2844. return
  2845. }
  2846. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2847. tx := restful.Engine.NewSession()
  2848. if v, ok := tempval_["data"].([]interface{}); ok {
  2849. for _, Tvalue := range v {
  2850. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2851. if v1["name"] == "updateFPbyFTChange" {
  2852. fTChange = v1
  2853. continue
  2854. }
  2855. tempval = append(tempval, v1)
  2856. }
  2857. }
  2858. }
  2859. parammaps := fTChange["parammaps"].(map[string]interface{})
  2860. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2861. // if err != nil {
  2862. // logs.Error(err)
  2863. // appG.Response(http.StatusOK, e.ERROR, false)
  2864. // return
  2865. // }
  2866. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2867. // if err != nil {
  2868. // logs.Error(err)
  2869. // appG.Response(http.StatusOK, e.ERROR, false)
  2870. // return
  2871. // }
  2872. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2873. // if err != nil {
  2874. // logs.Error(err)
  2875. // appG.Response(http.StatusOK, e.ERROR, false)
  2876. // return
  2877. // }
  2878. err = tx.Begin()
  2879. if err != nil {
  2880. logging.Error("tx.Begin 事务启动失败__error:", err)
  2881. }
  2882. defer func() {
  2883. if err != nil {
  2884. if tx != nil {
  2885. tx.Rollback()
  2886. }
  2887. }
  2888. if tx != nil {
  2889. tx.Close()
  2890. }
  2891. }()
  2892. if err != nil {
  2893. } else {
  2894. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2895. tempCommon = v
  2896. }
  2897. // 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 ,
  2898. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2899. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2900. // UNION
  2901. // 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 ,
  2902. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2903. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2904. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2905. if err == nil {
  2906. if tempv, exists := c.Get("jwt_username"); exists {
  2907. tempCommon["jwt_username"] = tempv.(string)
  2908. }
  2909. for _, paramvalue := range tempval {
  2910. if _, ok := paramvalue["resultname"]; !ok {
  2911. paramvalue["resultname"] = paramvalue["name"]
  2912. }
  2913. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2914. if err != nil {
  2915. logging.Error("ExecDataParam error:", err)
  2916. break
  2917. }
  2918. }
  2919. if err != nil {
  2920. msg := geterrmsg(err.Error())
  2921. appG.Response(http.StatusOK, e.ERROR, msg)
  2922. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2923. }
  2924. }
  2925. }
  2926. tx.Commit()
  2927. // go func() {
  2928. if fTChange != nil {
  2929. parammaps := fTChange["parammaps"].(map[string]interface{})
  2930. if parammaps["type"].(float64) == 1 {
  2931. _, err = tx.SQL(`UPDATE feedp fp
  2932. set
  2933. ccountratio = ccount *(ratio /100 ),
  2934. fp.ftweight= IFNULL(IF(
  2935. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2936. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2937. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2938. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2939. ),0),fp.feedweight = IFNULL(IF(
  2940. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2941. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2942. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2943. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2944. ),0) +ifnull(fp.supplyweight,0)
  2945. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2946. _, err = tx.SQL(`UPDATE fpdetail fpd
  2947. INNER JOIN feedp fp
  2948. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2949. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2950. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2951. } else {
  2952. _, err = tx.SQL(`UPDATE feedp fp
  2953. SET ccountratio = ccount *(ratio /100 ),
  2954. fp.supplyweight= IFNULL(IF(
  2955. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2956. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2957. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2958. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2959. ),0),fp.feedweight = IFNULL(IF(
  2960. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2961. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*(ccount *(ratio /100 )),
  2962. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*(ccount *(ratio /100 )) +
  2963. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*(ccount *(ratio /100 ))
  2964. ),0) +ifnull(fp.supplyweight,0)
  2965. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2966. _, err = tx.SQL(`UPDATE fpdetail fpd
  2967. INNER JOIN feedp fp
  2968. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2969. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2970. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2971. }
  2972. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  2973. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  2974. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  2975. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  2976. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  2977. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  2978. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  2979. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  2980. join feedtemplet ft on ft.id = fp.ftid where ft.id = ?`, parammaps["ftid"]).QueryString()
  2981. // fmt.Println(ftId)
  2982. tx.SQL(`update feedp fp set barname = (select bname from bar where id = fp.id ) where pastureid = ?`, parammaps["pastureid"]).Execute()
  2983. // fmt.Println(fsion.Get("userId").ValueStr(),"fsion.Get.ValueStr()")
  2984. FpdBatchEditGrfd(fmt.Sprintf("%v", parammaps["pastureid"]), values1)
  2985. // 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 ,
  2986. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2987. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2988. // UNION
  2989. // 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 ,
  2990. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2991. // WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2992. // order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2993. // lpplanList := make([]*lpplanStruct, 0)
  2994. // err = tx.SQL(`select id,times,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpplan.pastureid ) = 0 ,
  2995. // ifnull((select maxstirfeed from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),100000),(select ifnull(volume,0) from tmr where id = lpplan.tmrid ) *
  2996. // (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)
  2997. // if err != nil {
  2998. // logs.Error(err, 1)
  2999. // return
  3000. // }
  3001. // lppidlist := []string{}
  3002. // for _, lpp := range lpplanList {
  3003. // lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  3004. // }
  3005. // if len(lppidlist) <= 0 {
  3006. // appG.Response(http.StatusOK, e.SUCCESS, true)
  3007. // return
  3008. // }
  3009. // lpplandtl1AllList := make([]*lpplandtl1, 0)
  3010. // err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  3011. // order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  3012. // if err != nil {
  3013. // // tx.Rollback()
  3014. // logs.Error(err, 2, parammaps["pastureid"])
  3015. // return
  3016. // }
  3017. // for _, lpp := range lpplandtl1AllList {
  3018. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  3019. // and find_in_set(barid,?) `, parammaps["pastureid"], parammaps["pastureid"], lpp.Barid).Execute()
  3020. // if err != nil {
  3021. // logs.Error(err)
  3022. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3023. // return
  3024. // }
  3025. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3026. // WHERE pastureid=? and find_in_set(barid,? ) `, parammaps["pastureid"], lpp.Barid).Execute()
  3027. // if err != nil {
  3028. // logs.Error(err)
  3029. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3030. // return
  3031. // }
  3032. // }
  3033. // var wg sync.WaitGroup
  3034. // for _, old := range fpdOldDataList {
  3035. // for _, fpd := range fpdDataList {
  3036. // wg.Add(1)
  3037. // go func(old, fpd map[string]interface{}) {
  3038. // updateLppandList := make([]*lpplandtl1, 0)
  3039. // defer wg.Done()
  3040. // if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  3041. // fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  3042. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3043. // oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  3044. // // if weight > oldweight {
  3045. // // return
  3046. // // }
  3047. // var w float64
  3048. // var status int
  3049. // if weight < oldweight {
  3050. // if weight >= 0 {
  3051. // return
  3052. // }
  3053. // w = weight
  3054. // status = 0
  3055. // } else {
  3056. // if oldweight > 0 {
  3057. // return
  3058. // }
  3059. // w = weight
  3060. // status = 1
  3061. // }
  3062. // // fweight = w
  3063. // for _, lpp := range lpplanList {
  3064. // var fweight float64
  3065. // var lweight float64
  3066. // lpplandtl1List := make([]*lpplandtl1, 0)
  3067. // fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3068. // for _, lppland := range lpplandtl1AllList {
  3069. // if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3070. // lpplandtl1List = append(lpplandtl1List, lppland)
  3071. // }
  3072. // }
  3073. // if len(lpplandtl1List) == 0 {
  3074. // continue
  3075. // }
  3076. // for _, lppland := range lpplandtl1List {
  3077. // lweight += lppland.Lweight
  3078. // }
  3079. // if status == 0 {
  3080. // if lweight <= 0 {
  3081. // continue
  3082. // }
  3083. // } else {
  3084. // if lpp.Maxweight <= lweight {
  3085. // continue
  3086. // }
  3087. // }
  3088. // for _, lppland := range lpplandtl1List {
  3089. // if fpdid == lppland.Fpdid {
  3090. // if status == 1 {
  3091. // // if w <= lppland.Lweight {
  3092. // if lpp.Maxweight <= lweight {
  3093. // continue
  3094. // }
  3095. // if w+lweight <= lpp.Maxweight {
  3096. // lppland.Lweight += w
  3097. // lweight += w
  3098. // fweight += w
  3099. // w = 0
  3100. // } else {
  3101. // w = w - (lpp.Maxweight - lweight)
  3102. // n := (lpp.Maxweight - lweight)
  3103. // lppland.Lweight = lppland.Lweight + n
  3104. // lweight += n
  3105. // fweight += n
  3106. // }
  3107. // } else {
  3108. // if lppland.Lweight == 0 {
  3109. // continue
  3110. // }
  3111. // if w+lppland.Lweight >= 0 {
  3112. // lppland.Lweight = lppland.Lweight + w
  3113. // lweight = lweight + w
  3114. // fweight = fweight + w
  3115. // w = 0
  3116. // } else {
  3117. // w = w + lppland.Lweight
  3118. // lweight = lweight - lppland.Lweight
  3119. // fweight = fweight - lppland.Lweight
  3120. // lppland.Lweight = 0
  3121. // }
  3122. // }
  3123. // updateLppandList = append(updateLppandList, lppland)
  3124. // break
  3125. // }
  3126. // }
  3127. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3128. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3129. // WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3130. // if err != nil {
  3131. // // tx.Rollback()
  3132. // logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3133. // return
  3134. // }
  3135. // for _, lppland := range updateLppandList {
  3136. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3137. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3138. // if err != nil {
  3139. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3140. // // tx.Rollback()
  3141. // logs.Error(err, 3)
  3142. // return
  3143. // }
  3144. // // defer wg.Done()
  3145. // }
  3146. // updateLppandList = []*lpplandtl1{}
  3147. // if w == 0 {
  3148. // break
  3149. // }
  3150. // }
  3151. // }
  3152. // }(old, fpd)
  3153. // }
  3154. // }
  3155. // wg.Wait()
  3156. }
  3157. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3158. if err != nil {
  3159. logs.Error(err)
  3160. appG.Response(http.StatusOK, e.ERROR, false)
  3161. return
  3162. }
  3163. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3164. if err != nil {
  3165. logs.Error(err)
  3166. appG.Response(http.StatusOK, e.ERROR, false)
  3167. return
  3168. }
  3169. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3170. if err != nil {
  3171. logs.Error(err)
  3172. appG.Response(http.StatusOK, e.ERROR, false)
  3173. return
  3174. }
  3175. now := createdate
  3176. userId:= fsion.Get("userId").ValueStr()
  3177. // for _, oldFpd := range oldFpdDataList {
  3178. for _, newFpd := range newFpdDataList {
  3179. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3180. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3181. // go func() {
  3182. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3183. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3184. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3185. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  3186. if err != nil {
  3187. logs.Error(err)
  3188. appG.Response(http.StatusOK, e.ERROR, false)
  3189. return
  3190. }
  3191. // }()
  3192. }
  3193. // break
  3194. // }
  3195. // }
  3196. // }
  3197. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3198. for _, newLpplandtl1 := range newLpplandtl1List {
  3199. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3200. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3201. // go func() {
  3202. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3203. background,cowcount,ccountradio,lweighthis,userId,createdate)
  3204. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3205. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3206. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3207. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3208. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3209. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], userId,now ).Execute()
  3210. if err != nil {
  3211. logs.Error(err)
  3212. appG.Response(http.StatusOK, e.ERROR, false)
  3213. return
  3214. }
  3215. // }()
  3216. // }
  3217. // break
  3218. // }
  3219. // }
  3220. }
  3221. // for _, oldFeedp := range oldFeedpList {
  3222. for _, newFeedp := range newFeedpList {
  3223. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3224. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3225. // go func() {
  3226. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3227. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3228. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3229. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3230. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3231. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3232. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3233. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  3234. // fmt.Println(userId,"33333333333333333333333333333333333")
  3235. if err != nil {
  3236. logs.Error(err)
  3237. appG.Response(http.StatusOK, e.ERROR, false)
  3238. return
  3239. }
  3240. }
  3241. // ,,parammaps["ftid"])
  3242. // surplus, surplusId, id, pastureId string
  3243. // FtdetailSurplusFt(parammaps["ftid"].)
  3244. ftList1, err := tx.SQL(` SELECT
  3245. f.id,
  3246. f.surplus surplusId,
  3247. f.pastureid,
  3248. s.surplus
  3249. FROM
  3250. feedtemplet f
  3251. JOIN surplus s ON s.id = f.surplus
  3252. WHERE
  3253. f.id = ?`, parammaps["ftid"]).QueryString()
  3254. for _, ft := range ftList1 {
  3255. FtdetailSurplusFt(ft["surplus"], ft["surplusId"], ft["id"], ft["pastureid"])
  3256. }
  3257. appG.Response(http.StatusOK, e.SUCCESS, true)
  3258. }
  3259. type lpplandtlInfo struct {
  3260. Id int64 `xorm:"id"`
  3261. Pastureid int64 `xorm:"pastureid"`
  3262. Lppid int64 `xorm:"lppid"`
  3263. Barid int64 `xorm:"barid"`
  3264. Barname string `xorm:"barname"`
  3265. Fpdid int64 `xorm:"fpdid"`
  3266. Fttype int64 `xorm:"fttype"`
  3267. Lweight float64 `xorm:"lweight"`
  3268. Sort int64 `xorm:"sort"`
  3269. Tmrid int64 `xorm:"tmrid"`
  3270. Tmrname string `xorm:"tmrname"`
  3271. Cowcount int64 `xorm:"cowcount"`
  3272. Ccountradio float64 `xorm:"ccountradio"`
  3273. Background string `xorm:"background"`
  3274. Lweighthis float64 `xorm:"lweighthis"`
  3275. Maxweight float64 `xorm:"maxweight"`
  3276. }
  3277. func UpdateFpdetailBar(c *gin.Context) {
  3278. appG := app.Gin{C: c}
  3279. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3280. fsion := gofasion.NewFasion(string(dataByte))
  3281. pastureid := fsion.Get("pastureid").ValueStr()
  3282. id := fsion.Get("id").ValueStr()
  3283. tx := restful.Engine.NewSession()
  3284. tx.Begin()
  3285. 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 `,
  3286. pastureid, id).Query().List()
  3287. if err != nil {
  3288. logs.Error(err)
  3289. }
  3290. for _, fpd := range fpdList {
  3291. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3292. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3293. pastureid, fpd["id"]).Query().List()
  3294. if err != nil {
  3295. tx.Rollback()
  3296. logs.Error(err)
  3297. appG.Response(http.StatusOK, e.ERROR, false)
  3298. return
  3299. }
  3300. var lweight float64
  3301. for _, lppland := range lpplandList {
  3302. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3303. lweight += lweight1
  3304. }
  3305. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3306. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3307. if fpdweight >= ptuse && lweight == ptuse {
  3308. continue
  3309. } else {
  3310. if lweight <= fpdweight {
  3311. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3312. if err != nil {
  3313. tx.Rollback()
  3314. logs.Error(err)
  3315. appG.Response(http.StatusOK, e.ERROR, false)
  3316. return
  3317. }
  3318. } else {
  3319. weight := fpdweight - lweight
  3320. for _, lppland := range lpplandList {
  3321. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3322. if weight >= lpplandlweight {
  3323. weight = weight - lpplandlweight
  3324. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3325. if err != nil {
  3326. tx.Rollback()
  3327. logs.Error(err)
  3328. appG.Response(http.StatusOK, e.ERROR, false)
  3329. return
  3330. }
  3331. } else {
  3332. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3333. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3334. // if err != nil {
  3335. // tx.Rollback()
  3336. // logs.Error(err)
  3337. // appG.Response(http.StatusOK, e.ERROR, false)
  3338. // return
  3339. // }
  3340. weight = 0
  3341. break
  3342. }
  3343. }
  3344. }
  3345. }
  3346. }
  3347. fsionData := fsion.Get("data").Array()
  3348. for _, list := range fsionData {
  3349. ftmap := make(map[string]interface{})
  3350. ftmap["old"] = list.Get("old").ValueDefaultFloat64(0.0)
  3351. ftmap["new"] = list.Get("new").ValueDefaultFloat64(0.0)
  3352. ftmap["times"] = list.Get("times").ValueInt64()
  3353. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3354. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3355. // fmt.Println(ftmap)
  3356. // /*
  3357. count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3358. and find_in_set(barid,(select barid from feedp where id = ? )) and lweight > 0 `, pastureid, pastureid, ftmap["times"], id).Count()
  3359. if count == 1 {
  3360. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  3361. and find_in_set(barid,(select barid from feedp where id = ? )) `, pastureid, pastureid, ftmap["times"], id).Execute()
  3362. if err != nil {
  3363. tx.Rollback()
  3364. logs.Error(err)
  3365. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3366. return
  3367. }
  3368. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  3369. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where id = ? ) ) and times = ? `, pastureid, id, ftmap["times"]).Execute()
  3370. if err != nil {
  3371. tx.Rollback()
  3372. logs.Error(err)
  3373. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  3374. return
  3375. }
  3376. }
  3377. // */
  3378. fpdDataList, err := tx.SQL(`
  3379. 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 ,
  3380. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3381. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? `, pastureid, id, ftmap["times"]).Query().List()
  3382. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3383. if err != nil {
  3384. tx.Rollback()
  3385. logs.Error(err)
  3386. }
  3387. for _, fpd := range fpdDataList {
  3388. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string)) {
  3389. fttype := -1
  3390. if fpd["fttype"].(string) == "1" {
  3391. fttype = 1
  3392. }
  3393. var fweight float64
  3394. var lweight float64
  3395. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3396. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  3397. t.maxstirfeed,(select ifnull(volume,0) from tmr where id = lpp.tmrid ) *
  3398. (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  3399. join lpplandtl1 lppland on lpp.id = lppland.lppid
  3400. join tmr t on t.id = lpp.tmrid
  3401. where lppland.fpdid =?
  3402. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3403. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3404. if err != nil {
  3405. tx.Rollback()
  3406. logs.Error(err)
  3407. }
  3408. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3409. var w float64
  3410. var status int
  3411. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3412. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  3413. if weight >= 0 {
  3414. continue
  3415. }
  3416. w = weight
  3417. status = 0
  3418. } else {
  3419. // continue
  3420. if weight <= 0 {
  3421. continue
  3422. }
  3423. w = weight
  3424. status = 1
  3425. }
  3426. // for _, lppland := range lpplandtl1List {
  3427. // lweight += lppland.Lweight
  3428. // }
  3429. for _, lppland := range lpplandtl1List {
  3430. lpplandInfo := new(lpplandtlInfo)
  3431. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  3432. lweight = lpplandInfo.Lweight
  3433. if status == 1 {
  3434. // if w <= lppland.Lweight {
  3435. if lppland.Maxweight <= lweight {
  3436. continue
  3437. }
  3438. if w+lweight <= lppland.Maxweight {
  3439. lppland.Lweight += w
  3440. lweight += w
  3441. fweight += w
  3442. w = 0
  3443. } else {
  3444. w = w - (lppland.Maxweight - lweight)
  3445. n := (lppland.Maxweight - lweight)
  3446. lppland.Lweight = lppland.Lweight + n
  3447. lweight += n
  3448. fweight += n
  3449. }
  3450. } else {
  3451. if lppland.Lweight == 0 {
  3452. continue
  3453. }
  3454. if w+lppland.Lweight >= 0 {
  3455. lppland.Lweight = lppland.Lweight + w
  3456. lweight = lweight + w
  3457. fweight = fweight + w
  3458. w = 0
  3459. } else {
  3460. w = w + lppland.Lweight
  3461. lweight = lweight - lppland.Lweight
  3462. fweight = fweight - lppland.Lweight
  3463. lppland.Lweight = 0
  3464. }
  3465. }
  3466. if lppland.Lweight > 0 {
  3467. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3468. if err != nil {
  3469. tx.Rollback()
  3470. logs.Error(err)
  3471. return
  3472. }
  3473. } else {
  3474. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  3475. if err != nil {
  3476. tx.Rollback()
  3477. logs.Error(err)
  3478. return
  3479. }
  3480. }
  3481. if w == 0 {
  3482. break
  3483. }
  3484. // break
  3485. }
  3486. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3487. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3488. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3489. if err != nil {
  3490. tx.Rollback()
  3491. logs.Error(err)
  3492. }
  3493. if w == 0 {
  3494. break
  3495. }
  3496. }
  3497. }
  3498. }
  3499. tx.Commit()
  3500. now := time.Now()
  3501. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3502. if err != nil {
  3503. logs.Error(err)
  3504. appG.Response(http.StatusOK, e.ERROR, false)
  3505. return
  3506. }
  3507. for _, newLpplandtl1 := range newLpplandtl1List {
  3508. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3509. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3510. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3511. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3512. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3513. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3514. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3515. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3516. if err != nil {
  3517. logs.Error(err)
  3518. appG.Response(http.StatusOK, e.ERROR, false)
  3519. return
  3520. }
  3521. }
  3522. appG.Response(http.StatusOK, e.SUCCESS, true)
  3523. }
  3524. func GetProcessAnalysis(c *gin.Context) {
  3525. appG := app.Gin{C: c}
  3526. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3527. fsion := gofasion.NewFasion(string(dataByte))
  3528. sqlnamestr := fsion.Get("name").ValueStr()
  3529. offset := fsion.Get("offset").ValueDefaultInt(0)
  3530. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3531. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3532. parammaps := fsion.Get("parammaps")
  3533. tx := restful.Engine.NewSession()
  3534. err := tx.Begin()
  3535. defer func() {
  3536. switch {
  3537. case err != nil:
  3538. logging.Error("tx.Begin 事务启动失败__error:", err)
  3539. if tx != nil {
  3540. tx.Rollback()
  3541. }
  3542. default:
  3543. if tx != nil {
  3544. err = tx.Commit()
  3545. }
  3546. }
  3547. if tx != nil {
  3548. tx.Close()
  3549. }
  3550. }()
  3551. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3552. s_params := make([]interface{}, 0)
  3553. paramslist := strings.Split(p, ",")
  3554. if len(paramslist) > 0 && p != "" {
  3555. for _, value := range paramslist {
  3556. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3557. if tempv, exists := c.Get("jwt_username"); exists {
  3558. s_params = append(s_params, tempv.(string))
  3559. } else {
  3560. s_params = append(s_params, "")
  3561. }
  3562. } else {
  3563. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3564. }
  3565. }
  3566. }
  3567. tmrtnameStr := ""
  3568. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3569. if len(tmrtnameStr) == 0 {
  3570. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3571. } else {
  3572. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3573. }
  3574. }
  3575. if len(tmrtnameStr) > 0 {
  3576. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3577. }
  3578. sql += " ORDER BY d.intime"
  3579. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3580. if err != nil {
  3581. logging.Error("GetDataByName err: ", err)
  3582. msg := geterrmsg(err.Error())
  3583. appG.Response(http.StatusOK, e.ERROR, msg)
  3584. } else {
  3585. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3586. }
  3587. }
  3588. func UpdateFeedtempletStatus(c *gin.Context) {
  3589. appG := app.Gin{C: c}
  3590. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3591. fsion := gofasion.NewFasion(string(dataByte))
  3592. parammaps := fsion.Get("parammaps")
  3593. tx := restful.Engine.NewSession()
  3594. tx.Begin()
  3595. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3596. if err != nil {
  3597. tx.Rollback()
  3598. logs.Error(err)
  3599. appG.Response(http.StatusOK, e.ERROR, err)
  3600. return
  3601. }
  3602. tx.Commit()
  3603. appG.Response(http.StatusOK, e.SUCCESS, true)
  3604. }
  3605. func AddFtdry(c *gin.Context) {
  3606. appG := app.Gin{C: c}
  3607. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3608. fsion := gofasion.NewFasion(string(dataByte))
  3609. sqlnamestr := fsion.Get("name").ValueStr()
  3610. s_params := make([]interface{}, 0)
  3611. tx := restful.Engine.NewSession()
  3612. err := tx.Begin()
  3613. defer func() {
  3614. switch {
  3615. case err != nil:
  3616. if tx != nil {
  3617. tx.Rollback()
  3618. }
  3619. default:
  3620. if tx != nil {
  3621. err = tx.Commit()
  3622. }
  3623. }
  3624. if tx != nil {
  3625. tx.Close()
  3626. }
  3627. }()
  3628. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3629. if sql != "" {
  3630. parammaps := fsion.Get("parammaps")
  3631. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3632. paramslist := strings.Split(p, ",")
  3633. if len(paramslist) > 0 && p != "" {
  3634. for _, value := range paramslist {
  3635. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3636. if tempv, exists := c.Get("jwt_username"); exists {
  3637. s_params = append(s_params, tempv.(string))
  3638. } else {
  3639. s_params = append(s_params, "")
  3640. }
  3641. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3642. ids, err := setting.SnowIds.NextId()
  3643. if err != nil {
  3644. ids = time.Now().UnixNano()
  3645. logging.Info("create SnowIds err", err)
  3646. }
  3647. s_params = append(s_params, ids)
  3648. } else {
  3649. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3650. }
  3651. }
  3652. }
  3653. var actweight float64
  3654. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3655. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3656. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3657. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3658. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3659. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3660. 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()
  3661. if err != nil {
  3662. logging.Error("AddFtdry err: ", err)
  3663. msg := geterrmsg(err.Error())
  3664. appG.Response(http.StatusOK, e.ERROR, msg)
  3665. }
  3666. if len(actweightList) > 0 {
  3667. for _, item := range actweightList {
  3668. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3669. if err != nil {
  3670. logging.Error("AddFtdry err: ", err)
  3671. msg := geterrmsg(err.Error())
  3672. appG.Response(http.StatusOK, e.ERROR, msg)
  3673. }
  3674. actweight = fl
  3675. }
  3676. } else {
  3677. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3678. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3679. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3680. if err != nil {
  3681. logging.Error("AddFtdry err: ", err)
  3682. msg := geterrmsg(err.Error())
  3683. appG.Response(http.StatusOK, e.ERROR, msg)
  3684. }
  3685. for _, item := range dryList {
  3686. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3687. if err != nil {
  3688. logging.Error("AddFtdry err: ", err)
  3689. msg := geterrmsg(err.Error())
  3690. appG.Response(http.StatusOK, e.ERROR, msg)
  3691. }
  3692. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3693. }
  3694. }
  3695. if sqlnamestr == "insertFtdry" {
  3696. s_params = append(s_params, actweight)
  3697. } else if sqlnamestr == "updateFtdry" {
  3698. sql = fmt.Sprintf(sql, actweight)
  3699. }
  3700. queryData, err := execDataBySqlT(sql, s_params, tx)
  3701. if err != nil {
  3702. logging.Error("AddFtdry err: ", err)
  3703. msg := geterrmsg(err.Error())
  3704. appG.Response(http.StatusOK, e.ERROR, msg)
  3705. } else {
  3706. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3707. }
  3708. } else {
  3709. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3710. }
  3711. }
  3712. func CheckDates(c *gin.Context) {
  3713. tx := restful.Engine.NewSession()
  3714. defer tx.Close()
  3715. appG := app.Gin{C: c}
  3716. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3717. tempval_ := make(map[string]interface{})
  3718. tempCommon := make(map[string]interface{})
  3719. tempval := make([]map[string]interface{}, 0)
  3720. err := json.Unmarshal(dataByte, &tempval_)
  3721. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3722. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3723. if err != nil {
  3724. } else {
  3725. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3726. tempCommon = v
  3727. }
  3728. if v, ok := tempval_["data"].([]interface{}); ok {
  3729. for _, Tvalue := range v {
  3730. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3731. tempval = append(tempval, v1)
  3732. }
  3733. }
  3734. }
  3735. if err == nil {
  3736. if tempv, exists := c.Get("jwt_username"); exists {
  3737. tempCommon["jwt_username"] = tempv.(string)
  3738. }
  3739. for _, paramvalue := range tempval {
  3740. if _, ok := paramvalue["resultname"]; !ok {
  3741. paramvalue["resultname"] = paramvalue["name"]
  3742. }
  3743. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3744. if err != nil {
  3745. logging.Error("ExecDataParam error:", err)
  3746. }
  3747. }
  3748. if err == nil {
  3749. vmsg := ""
  3750. for _, item := range tempval {
  3751. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3752. for _, childrenList := range list.([]interface{}) {
  3753. for k, children := range childrenList.(map[string]interface{}) {
  3754. if k != "children" {
  3755. continue
  3756. }
  3757. for _, v := range children.([]map[string]interface{}) {
  3758. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3759. if k1 == "list" {
  3760. for _, v2 := range v1.([]map[string]interface{}) {
  3761. if v2["vmsg"].(string) != "1" {
  3762. if len(vmsg) == 0 {
  3763. vmsg = v2["vmsg"].(string)
  3764. } else {
  3765. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3766. }
  3767. }
  3768. }
  3769. }
  3770. }
  3771. }
  3772. }
  3773. }
  3774. }
  3775. }
  3776. if len(vmsg) > 0 {
  3777. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3778. } else {
  3779. appG.Response(http.StatusOK, e.SUCCESS, true)
  3780. }
  3781. } else {
  3782. msg := geterrmsg(err.Error())
  3783. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3784. }
  3785. }
  3786. }
  3787. if err != nil {
  3788. msg := geterrmsg(err.Error())
  3789. appG.Response(http.StatusOK, e.ERROR, msg)
  3790. }
  3791. }
  3792. 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) {
  3793. sqlname := fasion["name"].(string)
  3794. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3795. if v, ok := fasion["type"]; ok {
  3796. sqltype = v.(string)
  3797. }
  3798. sql := ""
  3799. p := ""
  3800. s_params := make([]interface{}, 0)
  3801. if sqltype != "" {
  3802. sql, p = restful.GetSqlByName(sqlname, tx)
  3803. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3804. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3805. paramslist := strings.Split(p, ",")
  3806. if len(paramslist) > 0 && p != "" {
  3807. for _, value := range paramslist {
  3808. ss := ""
  3809. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3810. ids, err := setting.SnowIds.NextId()
  3811. if err != nil {
  3812. ids = time.Now().UnixNano()
  3813. logging.Info("create SnowIds err", err)
  3814. }
  3815. s_params = append(s_params, ids)
  3816. } else {
  3817. if ss == "" && CommonParamMap != nil {
  3818. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3819. ss = valuestring
  3820. tempstrb := strings.IndexAny(valuestring, "@")
  3821. tempstre := strings.IndexAny(valuestring, ".")
  3822. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3823. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3824. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3825. }
  3826. } else {
  3827. ss = ""
  3828. }
  3829. }
  3830. }
  3831. if ss == "" && ParentParamMap != nil {
  3832. ss = getParamValue_(v, value, ParentParamMap)
  3833. }
  3834. if ss == "" && sameParamMap != nil {
  3835. ss = getParamValue(v, value, sameParamMap)
  3836. }
  3837. if ss == "" && ParamMap != nil {
  3838. ss = getParamValue(v, value, ParamMap)
  3839. }
  3840. s_params = append(s_params, ss)
  3841. }
  3842. }
  3843. }
  3844. }
  3845. }
  3846. if sql == "" {
  3847. sqltype = ""
  3848. }
  3849. if sql != "" {
  3850. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3851. if err != nil {
  3852. return nil, err
  3853. }
  3854. // fmt.Println(tempValParam)
  3855. return tempValParam.(map[string]interface{}), nil
  3856. } else {
  3857. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3858. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3859. if err != nil {
  3860. return nil, err
  3861. }
  3862. return nil, err
  3863. }
  3864. }
  3865. return nil, nil
  3866. }
  3867. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3868. var err error
  3869. subarray, ok := fasion["children"]
  3870. if ok {
  3871. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3872. tempVal_arrary := make([]map[string]interface{}, 0)
  3873. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3874. tempVal_ := make(map[string]interface{})
  3875. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3876. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3877. } else {
  3878. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3879. }
  3880. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3881. if err != nil {
  3882. return err
  3883. }
  3884. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3885. }
  3886. v.(map[string]interface{})["children"] = tempVal_arrary
  3887. }
  3888. }
  3889. return nil
  3890. }
  3891. func FpdImportExcel(c *gin.Context) {
  3892. appG := app.Gin{C: c}
  3893. inputdata := ""
  3894. c.Request.ParseForm()
  3895. params := c.Request.Form
  3896. file, _, err := c.Request.FormFile("file")
  3897. if err != nil {
  3898. appG.Response(http.StatusOK, e.ERROR, err)
  3899. return
  3900. }
  3901. sqlnamestrs := params.Get("name")
  3902. sheetname := params.Get("sheetname")
  3903. pastureid := params.Get("pastureid")
  3904. // importParams := params.Get("importParams")
  3905. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3906. // 必输项参数 (字符串格式 "field1,field2,field3")
  3907. requiredParams := params.Get("requiredParams")
  3908. // 日期参数
  3909. dateParams := params.Get("dateParams")
  3910. // 数字参数
  3911. numParams := params.Get("numParams")
  3912. //将字符串分割开
  3913. dateParamslist := strings.Split(dateParams, ",")
  3914. requiredParamslist := strings.Split(requiredParams, ",")
  3915. numParamslist := strings.Split(numParams, ",")
  3916. queryData := make([]interface{}, 0)
  3917. sqlslist := strings.Split(sqlnamestrs, ",")
  3918. xlsx1, err := excelize.OpenReader(file)
  3919. if err != nil {
  3920. fmt.Println(err)
  3921. return
  3922. }
  3923. ok := 0
  3924. error := 0
  3925. isdone := true
  3926. tx := restful.Engine.NewSession()
  3927. defer tx.Close()
  3928. languageStatus := GetLanguageStatus()
  3929. if languageStatus == "0" {
  3930. 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
  3931. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3932. if err != nil {
  3933. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3934. return
  3935. }
  3936. rows := xlsx1.GetRows(sheetname)
  3937. // 限制10000条,多余的截取掉
  3938. if len(rows) > 10000 {
  3939. rows = rows[:10000]
  3940. }
  3941. dataList := make(map[string][]*upFpdetail, 0)
  3942. for i, row := range rows {
  3943. if i > 0 {
  3944. entry := make(map[string]interface{})
  3945. outentry := make(map[string]interface{})
  3946. for j, colCell := range rows[0] {
  3947. for k, colCell1 := range row {
  3948. if j == k {
  3949. outentry[colCell] = colCell1
  3950. entry[colCell] = colCell1
  3951. }
  3952. }
  3953. }
  3954. inputdata = ""
  3955. a := ""
  3956. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3957. //校验日期格式
  3958. for _, v := range dateParamslist {
  3959. if v == "" {
  3960. continue
  3961. }
  3962. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3963. dtime, err := TransfTime(d.(string))
  3964. if err != nil {
  3965. a = strings.Trim(v, " ")
  3966. break
  3967. }
  3968. outentry[strings.Trim(v, " ")] = dtime
  3969. }
  3970. }
  3971. if a != "" {
  3972. outentry["error_msg"] = a + " 格式错误"
  3973. error++
  3974. queryData = append(queryData, outentry)
  3975. continue
  3976. }
  3977. a = ""
  3978. //校验必填格式
  3979. for _, v := range requiredParamslist {
  3980. if v == "" {
  3981. continue
  3982. }
  3983. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3984. a = strings.Trim(v, " ")
  3985. break
  3986. }
  3987. }
  3988. if a != "" {
  3989. outentry["error_msg"] = a + " 未填或格式错误"
  3990. error++
  3991. queryData = append(queryData, outentry)
  3992. continue
  3993. }
  3994. a = ""
  3995. //校验数字格式
  3996. for _, v := range numParamslist {
  3997. if v == "" {
  3998. continue
  3999. }
  4000. d, ok := outentry[strings.Trim(v, " ")]
  4001. if !ok || d == "" {
  4002. outentry[strings.Trim(v, " ")] = 0
  4003. } else {
  4004. var fl float64
  4005. switch d.(type) {
  4006. case string:
  4007. fl, err = strconv.ParseFloat(d.(string), 64)
  4008. }
  4009. if err != nil || fl < 0 {
  4010. a = strings.Trim(v, " ")
  4011. break
  4012. }
  4013. }
  4014. }
  4015. if a != "" {
  4016. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  4017. error++
  4018. queryData = append(queryData, outentry)
  4019. continue
  4020. }
  4021. errExist := false
  4022. for _, sqlnamestr := range sqlslist {
  4023. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4024. paramslist := strings.Split(paramslists, ",")
  4025. if len(paramslist) > 0 {
  4026. s_params := make([]interface{}, 0)
  4027. for _, value := range paramslist {
  4028. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4029. if tempv, exists := c.Get("jwt_username"); exists {
  4030. s_params = append(s_params, tempv.(string))
  4031. } else {
  4032. s_params = append(s_params, "")
  4033. }
  4034. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4035. s_params = append(s_params, pastureid)
  4036. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4037. ids, err := setting.SnowIds.NextId()
  4038. if err != nil {
  4039. ids = time.Now().UnixNano()
  4040. logging.Info("create SnowIds err", err)
  4041. }
  4042. s_params = append(s_params, ids)
  4043. } else {
  4044. if outentry[strings.Trim(value, " ")] == nil {
  4045. s_params = append(s_params, "")
  4046. } else {
  4047. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4048. }
  4049. }
  4050. }
  4051. outentry["input"] = inputdata
  4052. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4053. if err != nil {
  4054. errExist = true
  4055. // if tx != nil {
  4056. // tx.Rollback()
  4057. // }
  4058. // if tx != nil {
  4059. // tx.Close()
  4060. // }
  4061. msg := geterrmsg(err.Error())
  4062. outentry["error_msg"] = msg
  4063. error++
  4064. queryData = append(queryData, outentry)
  4065. isdone = true
  4066. break
  4067. } else {
  4068. if len(returnmsgmap1) > 0 {
  4069. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4070. // if tx != nil {
  4071. // tx.Rollback()
  4072. // }
  4073. // if tx != nil {
  4074. // tx.Close()
  4075. // }
  4076. msg := geterrmsg(va.(string))
  4077. outentry["error_msg"] = msg
  4078. error++
  4079. queryData = append(queryData, outentry)
  4080. isdone = true
  4081. break
  4082. }
  4083. }
  4084. isdone = false
  4085. }
  4086. }
  4087. }
  4088. fmt.Println(outentry["栏舍名称"])
  4089. if !errExist {
  4090. dataexcel := make(map[string]interface{}, 0)
  4091. if _, ok := outentry["栏舍名称"]; ok {
  4092. dataexcel["barname"] = outentry["栏舍名称"]
  4093. }
  4094. // if _, ok := outentry["实际牛头数"]; ok {
  4095. // dataexcel["ccount"] = outentry["实际牛头数"]
  4096. // }
  4097. if _, ok := outentry["实际羊只数"]; ok {
  4098. dataexcel["ccount"] = outentry["实际羊只数"]
  4099. }
  4100. if _, ok := outentry["系数(%)"]; ok {
  4101. dataexcel["ratio"] = outentry["系数(%)"]
  4102. }
  4103. if _, ok := outentry["配方模板"]; ok {
  4104. dataexcel["ftname"] = outentry["配方模板"]
  4105. }
  4106. if _, ok := outentry["补料配方"]; ok {
  4107. dataexcel["ptsfname"] = outentry["补料配方"]
  4108. }
  4109. if _, ok := outentry["第一班比例(%)"]; ok {
  4110. dataexcel["1"] = outentry["第一班比例(%)"]
  4111. if fmt.Sprintf("%v", dataexcel["1"]) == "" {
  4112. dataexcel["1"] = 0
  4113. }
  4114. } else {
  4115. dataexcel["1"] = 0
  4116. }
  4117. if _, ok := outentry["第二班比例(%)"]; ok {
  4118. dataexcel["2"] = outentry["第二班比例(%)"]
  4119. if fmt.Sprintf("%v", dataexcel["2"]) == "" {
  4120. dataexcel["2"] = 0
  4121. }
  4122. } else {
  4123. dataexcel["2"] = 0
  4124. }
  4125. if _, ok := outentry["第三班比例(%)"]; ok {
  4126. dataexcel["3"] = outentry["第三班比例(%)"]
  4127. if fmt.Sprintf("%v", dataexcel["3"]) == "" {
  4128. dataexcel["3"] = 0
  4129. }
  4130. } else {
  4131. dataexcel["3"] = 0
  4132. }
  4133. if _, ok := outentry["第四班比例(%)"]; ok {
  4134. dataexcel["4"] = outentry["第四班比例(%)"]
  4135. if fmt.Sprintf("%v", dataexcel["4"]) == "" {
  4136. dataexcel["4"] = 0
  4137. }
  4138. } else {
  4139. dataexcel["4"] = 0
  4140. }
  4141. if _, ok := outentry["第五班比例(%)"]; ok {
  4142. dataexcel["5"] = outentry["第五班比例(%)"]
  4143. if fmt.Sprintf("%v", dataexcel["5"]) == "" {
  4144. dataexcel["5"] = 0
  4145. }
  4146. } else {
  4147. dataexcel["5"] = 0
  4148. }
  4149. if _, ok := outentry["第六班比例(%)"]; ok {
  4150. dataexcel["6"] = outentry["第六班比例(%)"]
  4151. if fmt.Sprintf("%v", dataexcel["6"]) == "" {
  4152. dataexcel["6"] = 0
  4153. }
  4154. } else {
  4155. dataexcel["6"] = 0
  4156. }
  4157. dataWeight := new(models.FpdetailEdit)
  4158. // dataWeightMap := make(map[string]interface{}, 0)
  4159. if _, ok := outentry["第一班重量"]; ok {
  4160. // dataWeightMap["weight1"] = outentry["第一班重量"]
  4161. dataWeight.Weight1, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第一班重量"]), 64)
  4162. }
  4163. if _, ok := outentry["第二班重量"]; ok {
  4164. // dataWeightMap["weight2"] = outentry["第二班重量"]
  4165. dataWeight.Weight2, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第二班重量"]), 64)
  4166. }
  4167. if _, ok := outentry["第三班重量"]; ok {
  4168. // dataWeightMap["weight3"] = outentry["第三班重量"]
  4169. dataWeight.Weight3, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第三班重量"]), 64)
  4170. }
  4171. if _, ok := outentry["第四班重量"]; ok {
  4172. // dataWeightMap["weight4"] = outentry["第四班重量"]
  4173. dataWeight.Weight4, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第四班重量"]), 64)
  4174. }
  4175. if _, ok := outentry["第五班重量"]; ok {
  4176. // dataWeightMap["weight5"] = outentry["第五班重量"]
  4177. dataWeight.Weight5, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第五班重量"]), 64)
  4178. }
  4179. if _, ok := outentry["第六班重量"]; ok {
  4180. // dataWeightMap["weight6"] = outentry["第六班重量"]
  4181. dataWeight.Weight6, _ = strconv.ParseFloat(fmt.Sprintf("%v", outentry["第六班重量"]), 64)
  4182. }
  4183. // var json1 := jsoniterator.ConfigCompatibleWithStandardLibrary
  4184. // dataWeightByte, _ := json.Marshal(dataWeightMap)
  4185. // err = json1.Unmarshal(dataWeightByte, &dataWeight)
  4186. // fmt.Println(err)
  4187. if fmt.Sprintf("%v", dataexcel["ccount"]) == "0" {
  4188. dataWeight.Weight1 = 0
  4189. dataWeight.Weight2 = 0
  4190. dataWeight.Weight3 = 0
  4191. dataWeight.Weight4 = 0
  4192. dataWeight.Weight5 = 0
  4193. dataWeight.Weight6 = 0
  4194. }
  4195. weight := dataWeight.Weight1 + dataWeight.Weight2 + dataWeight.Weight3 + dataWeight.Weight4 + dataWeight.Weight5 + dataWeight.Weight6
  4196. if weight > 0 {
  4197. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4198. if err != nil {
  4199. logs.Error(err)
  4200. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4201. return
  4202. }
  4203. if !existbar {
  4204. continue
  4205. }
  4206. _, 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()
  4207. if err != nil {
  4208. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4209. return
  4210. }
  4211. _, 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()
  4212. if err != nil {
  4213. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4214. return
  4215. }
  4216. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4217. if err != nil {
  4218. logs.Error(err)
  4219. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4220. return
  4221. }
  4222. if !existft {
  4223. continue
  4224. }
  4225. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4226. if err != nil {
  4227. logs.Error(err)
  4228. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4229. return
  4230. }
  4231. if !ftexist {
  4232. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4233. tx.SQL(` delete from lpplandtl1 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. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4240. if err != nil {
  4241. logs.Error(err)
  4242. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4243. return
  4244. }
  4245. }
  4246. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4247. if err != nil {
  4248. logs.Error(err)
  4249. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4250. return
  4251. }
  4252. if !exist {
  4253. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4254. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4255. if err != nil {
  4256. logs.Error(err)
  4257. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4258. return
  4259. }
  4260. }
  4261. var feedpargs []interface{}
  4262. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4263. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4264. if _, ok := dataexcel["ftname"]; ok {
  4265. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4266. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4267. // upFeedpSql += `,ftweight = ? `
  4268. // feedpargs = append(feedpargs, weight)
  4269. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4270. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4271. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4272. } else {
  4273. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4274. }
  4275. if _, ok := dataexcel["ptsfname"]; ok {
  4276. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4277. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4278. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4279. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4280. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4281. } else {
  4282. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4283. }
  4284. upFeedpSql += " where barname = ? and pastureid = ? "
  4285. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4286. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4287. if err != nil {
  4288. logs.Error(err)
  4289. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4290. return
  4291. }
  4292. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4293. if err != nil {
  4294. logs.Error(err)
  4295. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4296. return
  4297. }
  4298. if !exist1 {
  4299. _, 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) `,
  4300. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4301. if err != nil {
  4302. logs.Error(err)
  4303. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4304. return
  4305. }
  4306. }
  4307. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4308. if err != nil {
  4309. logs.Error(err)
  4310. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4311. return
  4312. }
  4313. if !exist2 {
  4314. _, 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) `,
  4315. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4316. if err != nil {
  4317. logs.Error(err)
  4318. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4319. return
  4320. }
  4321. }
  4322. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4323. if err != nil {
  4324. logs.Error(err)
  4325. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4326. return
  4327. }
  4328. if !exist3 {
  4329. _, 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) `,
  4330. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4331. if err != nil {
  4332. logs.Error(err)
  4333. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4334. return
  4335. }
  4336. }
  4337. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4338. if err != nil {
  4339. logs.Error(err)
  4340. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4341. return
  4342. }
  4343. if !exist4 {
  4344. _, 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) `,
  4345. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4346. if err != nil {
  4347. logs.Error(err)
  4348. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4349. return
  4350. }
  4351. }
  4352. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4353. if err != nil {
  4354. logs.Error(err)
  4355. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4356. return
  4357. }
  4358. if !exist5 {
  4359. _, 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) `,
  4360. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4361. if err != nil {
  4362. logs.Error(err)
  4363. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4364. return
  4365. }
  4366. }
  4367. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4368. if err != nil {
  4369. logs.Error(err)
  4370. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4371. return
  4372. }
  4373. if !exist6 {
  4374. _, 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) `,
  4375. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4376. if err != nil {
  4377. logs.Error(err)
  4378. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4379. return
  4380. }
  4381. }
  4382. // dataexcel["ratio1"] = (dataWeight.Weight1 / weight) * 100
  4383. // dataexcel["ratio2"] = (dataWeight.Weight2 / weight) * 100
  4384. // dataexcel["ratio3"] = (dataWeight.Weight3 / weight) * 100
  4385. // dataexcel["ratio4"] = (dataWeight.Weight4 / weight) * 100
  4386. // dataexcel["ratio5"] = (dataWeight.Weight5 / weight) * 100
  4387. // dataexcel["ratio6"] = (dataWeight.Weight6 / weight) * 100
  4388. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  4389. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4390. and pastureid = ? and times = ?`
  4391. var fpdargs1 []interface{}
  4392. fpdargs1 = append(fpdargs1, dataWeight.Weight1, dataexcel["barname"], pastureid, dataWeight.Weight1, dataexcel["ccount"],
  4393. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4394. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4395. if err != nil {
  4396. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4397. return
  4398. }
  4399. var fpdargs2 []interface{}
  4400. fpdargs2 = append(fpdargs2, dataWeight.Weight2, dataexcel["barname"], pastureid, dataWeight.Weight2, dataexcel["ccount"],
  4401. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4402. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4403. if err != nil {
  4404. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4405. return
  4406. }
  4407. var fpdargs3 []interface{}
  4408. fpdargs3 = append(fpdargs3, dataWeight.Weight3, dataexcel["barname"], pastureid, dataWeight.Weight3, dataexcel["ccount"],
  4409. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4410. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4411. if err != nil {
  4412. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4413. return
  4414. }
  4415. var fpdargs4 []interface{}
  4416. fpdargs4 = append(fpdargs4, dataWeight.Weight4, dataexcel["barname"], pastureid, dataWeight.Weight4, dataexcel["ccount"],
  4417. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4418. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4419. if err != nil {
  4420. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4421. return
  4422. }
  4423. var fpdargs5 []interface{}
  4424. fpdargs5 = append(fpdargs5, dataWeight.Weight5, dataexcel["barname"], pastureid, dataWeight.Weight5, dataexcel["ccount"],
  4425. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4426. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4427. if err != nil {
  4428. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4429. return
  4430. }
  4431. var fpdargs6 []interface{}
  4432. fpdargs6 = append(fpdargs6, dataWeight.Weight6, dataexcel["barname"], pastureid, dataWeight.Weight6, dataexcel["ccount"],
  4433. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4434. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4435. if err != nil {
  4436. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4437. return
  4438. }
  4439. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4440. 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()
  4441. if err != nil {
  4442. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4443. return
  4444. }
  4445. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4446. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4447. upFpdetailList := make([]*upFpdetail, 0)
  4448. for _, newfpd := range newList {
  4449. for _, oldfpd := range oldFpdList {
  4450. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4451. var oldweight, newweight float64
  4452. if oldfpd["weight"] != nil {
  4453. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4454. }
  4455. if newfpd["weight"] != nil {
  4456. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4457. }
  4458. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4459. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4460. Old: oldweight,
  4461. New: newweight,
  4462. Times: newfpd["times"].(int64),
  4463. Ptid: newfpd["ptid"].(int64),
  4464. Fweight: fweight,
  4465. Id: oldfpd["id"].(int64),
  4466. })
  4467. break
  4468. }
  4469. }
  4470. }
  4471. // fmt.Println(dataexcel["barname"])
  4472. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4473. } else {
  4474. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4475. if err != nil {
  4476. logs.Error(err)
  4477. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4478. return
  4479. }
  4480. if !existbar {
  4481. continue
  4482. }
  4483. _, 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()
  4484. if err != nil {
  4485. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4486. return
  4487. }
  4488. _, 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()
  4489. if err != nil {
  4490. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4491. return
  4492. }
  4493. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  4494. if err != nil {
  4495. logs.Error(err)
  4496. appG.Response(http.StatusInternalServerError, e.ERROR, "配方不存在!")
  4497. return
  4498. }
  4499. if !existft {
  4500. continue
  4501. }
  4502. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4503. if err != nil {
  4504. logs.Error(err)
  4505. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4506. return
  4507. }
  4508. if !ftexist {
  4509. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4510. tx.SQL(` delete from lpplandtl1 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. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4517. if err != nil {
  4518. logs.Error(err)
  4519. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4520. return
  4521. }
  4522. }
  4523. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4524. if err != nil {
  4525. logs.Error(err)
  4526. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4527. return
  4528. }
  4529. if !exist {
  4530. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4531. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4532. if err != nil {
  4533. logs.Error(err)
  4534. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4535. return
  4536. }
  4537. }
  4538. var feedpargs []interface{}
  4539. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4540. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4541. if _, ok := dataexcel["ftname"]; ok {
  4542. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4543. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4544. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4545. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4546. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4547. } else {
  4548. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4549. }
  4550. if _, ok := dataexcel["ptsfname"]; ok {
  4551. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4552. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4553. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4554. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4555. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4556. } else {
  4557. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4558. }
  4559. upFeedpSql += " where barname = ? and pastureid = ? "
  4560. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4561. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4562. if err != nil {
  4563. logs.Error(err)
  4564. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4565. return
  4566. }
  4567. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4568. if err != nil {
  4569. logs.Error(err)
  4570. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4571. return
  4572. }
  4573. if !exist1 {
  4574. _, 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) `,
  4575. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4576. if err != nil {
  4577. logs.Error(err)
  4578. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4579. return
  4580. }
  4581. }
  4582. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4583. if err != nil {
  4584. logs.Error(err)
  4585. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4586. return
  4587. }
  4588. if !exist2 {
  4589. _, 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) `,
  4590. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4591. if err != nil {
  4592. logs.Error(err)
  4593. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4594. return
  4595. }
  4596. }
  4597. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4598. if err != nil {
  4599. logs.Error(err)
  4600. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4601. return
  4602. }
  4603. if !exist3 {
  4604. _, 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) `,
  4605. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4606. if err != nil {
  4607. logs.Error(err)
  4608. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4609. return
  4610. }
  4611. }
  4612. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4613. if err != nil {
  4614. logs.Error(err)
  4615. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4616. return
  4617. }
  4618. if !exist4 {
  4619. _, 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) `,
  4620. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4621. if err != nil {
  4622. logs.Error(err)
  4623. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4624. return
  4625. }
  4626. }
  4627. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4628. if err != nil {
  4629. logs.Error(err)
  4630. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4631. return
  4632. }
  4633. if !exist5 {
  4634. _, 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) `,
  4635. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4636. if err != nil {
  4637. logs.Error(err)
  4638. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4639. return
  4640. }
  4641. }
  4642. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4643. if err != nil {
  4644. logs.Error(err)
  4645. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4646. return
  4647. }
  4648. if !exist6 {
  4649. _, 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) `,
  4650. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4651. if err != nil {
  4652. logs.Error(err)
  4653. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4654. return
  4655. }
  4656. }
  4657. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4658. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4659. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4660. and pastureid = ? and times = ?`
  4661. var fpdargs1 []interface{}
  4662. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4663. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4664. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4665. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4666. if err != nil {
  4667. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4668. return
  4669. }
  4670. var fpdargs2 []interface{}
  4671. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4672. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4673. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4674. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4675. if err != nil {
  4676. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4677. return
  4678. }
  4679. var fpdargs3 []interface{}
  4680. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4681. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4682. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4683. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4684. if err != nil {
  4685. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4686. return
  4687. }
  4688. var fpdargs4 []interface{}
  4689. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4690. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4691. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4692. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4693. if err != nil {
  4694. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4695. return
  4696. }
  4697. var fpdargs5 []interface{}
  4698. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4699. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4700. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4701. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4702. if err != nil {
  4703. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4704. return
  4705. }
  4706. var fpdargs6 []interface{}
  4707. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4708. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4709. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4710. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4711. if err != nil {
  4712. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4713. return
  4714. }
  4715. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4716. 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()
  4717. if err != nil {
  4718. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4719. return
  4720. }
  4721. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4722. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4723. upFpdetailList := make([]*upFpdetail, 0)
  4724. for _, newfpd := range newList {
  4725. for _, oldfpd := range oldFpdList {
  4726. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4727. var oldweight, newweight float64
  4728. if oldfpd["weight"] != nil {
  4729. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4730. }
  4731. if newfpd["weight"] != nil {
  4732. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4733. }
  4734. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4735. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4736. Old: oldweight,
  4737. New: newweight,
  4738. Times: newfpd["times"].(int64),
  4739. Ptid: newfpd["ptid"].(int64),
  4740. Fweight: fweight,
  4741. Id: oldfpd["id"].(int64),
  4742. })
  4743. break
  4744. }
  4745. }
  4746. }
  4747. // fmt.Println(dataexcel["barname"])
  4748. dataList[dataexcel["barname"].(string)] = upFpdetailList
  4749. }
  4750. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4751. }
  4752. }
  4753. if !isdone {
  4754. ok++
  4755. isdone = true
  4756. }
  4757. }
  4758. for barname, v := range dataList {
  4759. // for _, v1 := range v {
  4760. // count, err := tx.SQL(` select count(1) from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4761. // and find_in_set(barid,(select barid from feedp where barname = ? )) and lweight > 0 `, pastureid, pastureid, v1.Times, barname).Count()
  4762. // if count == 1 {
  4763. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ? )
  4764. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, v1.Times, barname).Execute()
  4765. // if err != nil {
  4766. // logs.Error(err)
  4767. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4768. // return
  4769. // }
  4770. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4771. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) and times= ? `, pastureid, barname, v1.Times).Execute()
  4772. // if err != nil {
  4773. // logs.Error(err)
  4774. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4775. // return
  4776. // }
  4777. // }
  4778. // }
  4779. // /*
  4780. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  4781. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  4782. if err != nil {
  4783. logs.Error(err)
  4784. return
  4785. }
  4786. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4787. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  4788. if err != nil {
  4789. logs.Error(err)
  4790. return
  4791. }
  4792. // */
  4793. updateFpdetailByBar(pastureid, barname, v)
  4794. }
  4795. } else {
  4796. 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
  4797. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4798. if err != nil {
  4799. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4800. return
  4801. }
  4802. rows := xlsx1.GetRows(sheetname)
  4803. // 限制10000条,多余的截取掉
  4804. if len(rows) > 10000 {
  4805. rows = rows[:10000]
  4806. }
  4807. dataList := make(map[string][]*upFpdetail, 0)
  4808. for i, row := range rows {
  4809. if i > 0 {
  4810. entry := make(map[string]interface{})
  4811. outentry := make(map[string]interface{})
  4812. for j, colCell := range rows[0] {
  4813. for k, colCell1 := range row {
  4814. if j == k {
  4815. outentry[colCell] = colCell1
  4816. entry[colCell] = colCell1
  4817. }
  4818. }
  4819. }
  4820. inputdata = ""
  4821. a := ""
  4822. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  4823. //校验日期格式
  4824. for _, v := range dateParamslist {
  4825. if v == "" {
  4826. continue
  4827. }
  4828. if d, ok := outentry[v]; ok {
  4829. dtime, err := TransfTime(d.(string))
  4830. if err != nil {
  4831. a = v
  4832. break
  4833. }
  4834. outentry[v] = dtime
  4835. }
  4836. }
  4837. if a != "" {
  4838. outentry["error_msg"] = a + " format error"
  4839. error++
  4840. queryData = append(queryData, outentry)
  4841. continue
  4842. }
  4843. a = ""
  4844. //校验必填格式
  4845. for _, v := range requiredParamslist {
  4846. if v == "" {
  4847. continue
  4848. }
  4849. if d, ok := outentry[v]; !ok || d == "" {
  4850. a = v
  4851. break
  4852. }
  4853. }
  4854. if a != "" {
  4855. outentry["error_msg"] = a + " Unfilled or formatted incorrectly"
  4856. error++
  4857. queryData = append(queryData, outentry)
  4858. continue
  4859. }
  4860. a = ""
  4861. //校验数字格式
  4862. for _, v := range numParamslist {
  4863. if v == "" {
  4864. continue
  4865. }
  4866. d, ok := outentry[v]
  4867. if !ok || d == "" {
  4868. outentry[v] = 0
  4869. } else {
  4870. var fl float64
  4871. switch d.(type) {
  4872. case string:
  4873. fl, err = strconv.ParseFloat(d.(string), 64)
  4874. }
  4875. if err != nil || fl < 0 {
  4876. a = v
  4877. break
  4878. }
  4879. }
  4880. }
  4881. if a != "" {
  4882. outentry["error_msg"] = a + " Numerical type and cannot be negative"
  4883. error++
  4884. queryData = append(queryData, outentry)
  4885. continue
  4886. }
  4887. errExist := false
  4888. for _, sqlnamestr := range sqlslist {
  4889. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  4890. paramslist := strings.Split(paramslists, ",")
  4891. if len(paramslist) > 0 {
  4892. s_params := make([]interface{}, 0)
  4893. for _, value := range paramslist {
  4894. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  4895. if tempv, exists := c.Get("jwt_username"); exists {
  4896. s_params = append(s_params, tempv.(string))
  4897. } else {
  4898. s_params = append(s_params, "")
  4899. }
  4900. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  4901. s_params = append(s_params, pastureid)
  4902. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  4903. ids, err := setting.SnowIds.NextId()
  4904. if err != nil {
  4905. ids = time.Now().UnixNano()
  4906. logging.Info("create SnowIds err", err)
  4907. }
  4908. s_params = append(s_params, ids)
  4909. } else {
  4910. if outentry[strings.Trim(value, " ")] == nil {
  4911. s_params = append(s_params, "")
  4912. } else {
  4913. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  4914. }
  4915. }
  4916. }
  4917. outentry["input"] = inputdata
  4918. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  4919. if err != nil {
  4920. errExist = true
  4921. // if tx != nil {
  4922. // tx.Rollback()
  4923. // }
  4924. // if tx != nil {
  4925. // tx.Close()
  4926. // }
  4927. msg := geterrmsg(err.Error())
  4928. outentry["error_msg"] = msg
  4929. error++
  4930. queryData = append(queryData, outentry)
  4931. isdone = true
  4932. break
  4933. } else {
  4934. if len(returnmsgmap1) > 0 {
  4935. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  4936. // if tx != nil {
  4937. // tx.Rollback()
  4938. // }
  4939. // if tx != nil {
  4940. // tx.Close()
  4941. // }
  4942. msg := geterrmsg(va.(string))
  4943. outentry["error_msg"] = msg
  4944. error++
  4945. queryData = append(queryData, outentry)
  4946. isdone = true
  4947. break
  4948. }
  4949. }
  4950. isdone = false
  4951. }
  4952. }
  4953. }
  4954. if !errExist {
  4955. dataexcel := make(map[string]interface{}, 0)
  4956. if _, ok := outentry["Pen Name"]; ok {
  4957. dataexcel["barname"] = outentry["Pen Name"]
  4958. }
  4959. if _, ok := outentry["Actual Cattle Number"]; ok {
  4960. dataexcel["ccount"] = outentry["Actual Cattle Number"]
  4961. }
  4962. if _, ok := outentry["Coefficient(%)"]; ok {
  4963. dataexcel["ratio"] = outentry["Coefficient(%)"]
  4964. }
  4965. if _, ok := outentry["Formula Template"]; ok {
  4966. dataexcel["ftname"] = outentry["Formula Template"]
  4967. }
  4968. if _, ok := outentry["Supplement Formula"]; ok {
  4969. dataexcel["ptsfname"] = outentry["Supplement Formula"]
  4970. }
  4971. if _, ok := outentry["First Shift Ratio(%)"]; ok {
  4972. dataexcel["1"] = outentry["First Shift Ratio(%)"]
  4973. }
  4974. if _, ok := outentry["Second Shift Ratio(%)"]; ok {
  4975. dataexcel["2"] = outentry["Second Shift Ratio(%)"]
  4976. }
  4977. if _, ok := outentry["Third Shift Ratio(%)"]; ok {
  4978. dataexcel["3"] = outentry["Third Shift Ratio(%)"]
  4979. }
  4980. if _, ok := outentry["Fourth Shift Ratio(%)"]; ok {
  4981. dataexcel["4"] = outentry["Fourth Shift Ratio(%)"]
  4982. }
  4983. if _, ok := outentry["Fifth Shift Ratio(%)"]; ok {
  4984. dataexcel["5"] = outentry["Fifth Shift Ratio(%)"]
  4985. }
  4986. if _, ok := outentry["Sixth shift Ratio(%)"]; ok {
  4987. dataexcel["6"] = outentry["Sixth shift Ratio(%)"]
  4988. }
  4989. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4990. if err != nil {
  4991. logs.Error(err)
  4992. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4993. return
  4994. }
  4995. if !existbar {
  4996. continue
  4997. }
  4998. _, 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()
  4999. if err != nil {
  5000. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5001. return
  5002. }
  5003. _, 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()
  5004. if err != nil {
  5005. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5006. return
  5007. }
  5008. existft, err := tx.SQL(` select id from feedtemplet where tname = ? and pastureid = ? `, dataexcel["ftname"], pastureid).Exist()
  5009. if err != nil {
  5010. logs.Error(err)
  5011. appG.Response(http.StatusInternalServerError, e.ERROR, "Formula does not exist")
  5012. return
  5013. }
  5014. if !existft {
  5015. continue
  5016. }
  5017. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  5018. if err != nil {
  5019. logs.Error(err)
  5020. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5021. return
  5022. }
  5023. if !ftexist {
  5024. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  5025. tx.SQL(` delete from lpplandtl1 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. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5032. if err != nil {
  5033. logs.Error(err)
  5034. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5035. return
  5036. }
  5037. }
  5038. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  5039. if err != nil {
  5040. logs.Error(err)
  5041. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5042. return
  5043. }
  5044. if !exist {
  5045. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  5046. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  5047. if err != nil {
  5048. logs.Error(err)
  5049. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5050. return
  5051. }
  5052. }
  5053. var feedpargs []interface{}
  5054. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  5055. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  5056. if _, ok := dataexcel["ftname"]; ok {
  5057. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  5058. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  5059. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  5060. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  5061. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5062. } else {
  5063. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  5064. }
  5065. if _, ok := dataexcel["ptsfname"]; ok {
  5066. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  5067. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  5068. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  5069. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  5070. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  5071. } else {
  5072. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  5073. }
  5074. upFeedpSql += " where barname = ? and pastureid = ? "
  5075. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  5076. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  5077. if err != nil {
  5078. logs.Error(err)
  5079. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5080. return
  5081. }
  5082. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  5083. if err != nil {
  5084. logs.Error(err)
  5085. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5086. return
  5087. }
  5088. if !exist1 {
  5089. _, 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) `,
  5090. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5091. if err != nil {
  5092. logs.Error(err)
  5093. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5094. return
  5095. }
  5096. }
  5097. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  5098. if err != nil {
  5099. logs.Error(err)
  5100. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5101. return
  5102. }
  5103. if !exist2 {
  5104. _, 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) `,
  5105. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5106. if err != nil {
  5107. logs.Error(err)
  5108. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5109. return
  5110. }
  5111. }
  5112. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  5113. if err != nil {
  5114. logs.Error(err)
  5115. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5116. return
  5117. }
  5118. if !exist3 {
  5119. _, 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) `,
  5120. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5121. if err != nil {
  5122. logs.Error(err)
  5123. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5124. return
  5125. }
  5126. }
  5127. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  5128. if err != nil {
  5129. logs.Error(err)
  5130. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5131. return
  5132. }
  5133. if !exist4 {
  5134. _, 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) `,
  5135. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5136. if err != nil {
  5137. logs.Error(err)
  5138. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5139. return
  5140. }
  5141. }
  5142. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  5143. if err != nil {
  5144. logs.Error(err)
  5145. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5146. return
  5147. }
  5148. if !exist5 {
  5149. _, 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) `,
  5150. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5151. if err != nil {
  5152. logs.Error(err)
  5153. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5154. return
  5155. }
  5156. }
  5157. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  5158. if err != nil {
  5159. logs.Error(err)
  5160. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5161. return
  5162. }
  5163. if !exist6 {
  5164. _, 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) `,
  5165. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  5166. if err != nil {
  5167. logs.Error(err)
  5168. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5169. return
  5170. }
  5171. }
  5172. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  5173. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  5174. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  5175. and pastureid = ? and times = ?`
  5176. var fpdargs1 []interface{}
  5177. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  5178. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5179. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  5180. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  5181. if err != nil {
  5182. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5183. return
  5184. }
  5185. var fpdargs2 []interface{}
  5186. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  5187. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5188. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  5189. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  5190. if err != nil {
  5191. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5192. return
  5193. }
  5194. var fpdargs3 []interface{}
  5195. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  5196. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5197. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  5198. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  5199. if err != nil {
  5200. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5201. return
  5202. }
  5203. var fpdargs4 []interface{}
  5204. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  5205. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5206. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  5207. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  5208. if err != nil {
  5209. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5210. return
  5211. }
  5212. var fpdargs5 []interface{}
  5213. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  5214. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5215. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  5216. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  5217. if err != nil {
  5218. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5219. return
  5220. }
  5221. var fpdargs6 []interface{}
  5222. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  5223. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  5224. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  5225. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  5226. if err != nil {
  5227. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5228. return
  5229. }
  5230. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  5231. 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()
  5232. if err != nil {
  5233. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  5234. return
  5235. }
  5236. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  5237. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  5238. upFpdetailList := make([]*upFpdetail, 0)
  5239. for _, newfpd := range newList {
  5240. for _, oldfpd := range oldFpdList {
  5241. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  5242. var oldweight, newweight float64
  5243. if oldfpd["weight"] != nil {
  5244. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  5245. }
  5246. if newfpd["weight"] != nil {
  5247. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  5248. }
  5249. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  5250. upFpdetailList = append(upFpdetailList, &upFpdetail{
  5251. Old: oldweight,
  5252. New: newweight,
  5253. Times: newfpd["times"].(int64),
  5254. Ptid: newfpd["ptid"].(int64),
  5255. Fweight: fweight,
  5256. Id: oldfpd["id"].(int64),
  5257. })
  5258. break
  5259. }
  5260. }
  5261. }
  5262. // fmt.Println(dataexcel["barname"])
  5263. dataList[dataexcel["barname"].(string)] = upFpdetailList
  5264. // updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  5265. }
  5266. }
  5267. if !isdone {
  5268. ok++
  5269. isdone = true
  5270. }
  5271. }
  5272. for barname, v := range dataList {
  5273. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  5274. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, barname).Execute()
  5275. if err != nil {
  5276. logs.Error(err)
  5277. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5278. return
  5279. }
  5280. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5281. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, barname).Execute()
  5282. if err != nil {
  5283. logs.Error(err)
  5284. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5285. return
  5286. }
  5287. updateFpdetailByBar(pastureid, barname, v)
  5288. }
  5289. }
  5290. data := make(map[string]interface{})
  5291. data["result"] = queryData
  5292. data["success"] = ok
  5293. data["err_count"] = error
  5294. appG.Response(http.StatusOK, e.SUCCESS, data)
  5295. }
  5296. type upFpdetail struct {
  5297. Old float64
  5298. New float64
  5299. Times int64
  5300. Ptid int64
  5301. Fweight float64
  5302. Id int64
  5303. // Ptsid string
  5304. }
  5305. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  5306. tx := restful.Engine.NewSession()
  5307. defer tx.Close()
  5308. tx.Begin()
  5309. 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 `,
  5310. pastureid, barname).Query().List()
  5311. if err != nil {
  5312. logs.Error(err)
  5313. }
  5314. for _, fpd := range fpdList {
  5315. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  5316. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  5317. pastureid, fpd["id"], fpd["times"]).Query().List()
  5318. if err != nil {
  5319. tx.Rollback()
  5320. logs.Error(err)
  5321. return err
  5322. }
  5323. var lweight float64
  5324. for _, lppland := range lpplandList {
  5325. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5326. lweight += lweight1
  5327. }
  5328. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5329. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  5330. if fpdweight >= ptuse && lweight == ptuse {
  5331. continue
  5332. } else {
  5333. if lweight <= fpdweight {
  5334. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  5335. if err != nil {
  5336. tx.Rollback()
  5337. logs.Error(err)
  5338. return err
  5339. }
  5340. } else {
  5341. weight := lweight - fpdweight
  5342. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  5343. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  5344. if err != nil {
  5345. tx.Rollback()
  5346. logs.Error(err)
  5347. return err
  5348. }
  5349. for _, lppland := range lpplandList {
  5350. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5351. if weight >= lpplandlweight {
  5352. weight = weight - lpplandlweight
  5353. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  5354. if err != nil {
  5355. tx.Rollback()
  5356. logs.Error(err)
  5357. return err
  5358. }
  5359. } else {
  5360. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  5361. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  5362. if err != nil {
  5363. tx.Rollback()
  5364. logs.Error(err)
  5365. return err
  5366. }
  5367. weight = 0
  5368. break
  5369. }
  5370. }
  5371. }
  5372. }
  5373. }
  5374. for _, list := range dataList {
  5375. ftmap := make(map[string]interface{})
  5376. ftmap["old"] = list.Old
  5377. ftmap["new"] = list.New
  5378. ftmap["times"] = list.Times
  5379. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  5380. ftmap["ptsid"] = ""
  5381. // fmt.Println(ftmap)
  5382. // 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 ,
  5383. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  5384. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  5385. // UNION
  5386. fpdDataList, err := tx.SQL(`
  5387. 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 ,
  5388. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  5389. WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
  5390. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  5391. if err != nil {
  5392. tx.Rollback()
  5393. logs.Error(err)
  5394. }
  5395. for _, fpd := range fpdDataList {
  5396. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  5397. // fttype := -1
  5398. // if fpd["fttype"].(string) == "1" {
  5399. fttype := 1
  5400. // }
  5401. var fweight float64
  5402. var lweight float64
  5403. lpplandtl1List := make([]*lpplandtlInfo, 0)
  5404. err = tx.SQL(`select lppland.*,if((SELECT inforvalue FROM sysopt WHERE inforname = 'tmrOrVolume' AND pastureid =lpp.pastureid ) = 0 ,
  5405. t.maxstirfeed,t.volume * (select ifnull(volume,0) from feedtemplet where id = lpp.ftid) ) maxweight from lpplan lpp
  5406. join lpplandtl1 lppland on lpp.id = lppland.lppid
  5407. join tmr t on t.id = lpp.tmrid
  5408. where lppland.fpdid =?
  5409. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  5410. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  5411. if err != nil {
  5412. tx.Rollback()
  5413. logs.Error(err)
  5414. }
  5415. // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
  5416. // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
  5417. // 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
  5418. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  5419. var w float64
  5420. var status int
  5421. if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
  5422. if weight >= 0 {
  5423. continue
  5424. }
  5425. w = weight
  5426. status = 0
  5427. } else {
  5428. // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  5429. // continue
  5430. // }
  5431. w = weight
  5432. status = 1
  5433. }
  5434. // for _, lppland := range lpplandtl1List {
  5435. // lweight += lppland.Lweight
  5436. // }
  5437. for _, lppland := range lpplandtl1List {
  5438. lpplandInfo := new(lpplandtlInfo)
  5439. err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
  5440. lweight = lpplandInfo.Lweight
  5441. if status == 1 {
  5442. // if w <= lppland.Lweight {
  5443. if lppland.Maxweight <= lweight {
  5444. continue
  5445. }
  5446. if w+lweight <= lppland.Maxweight {
  5447. lppland.Lweight += w
  5448. lweight += w
  5449. fweight += w
  5450. w = 0
  5451. } else {
  5452. w = w - (lppland.Maxweight - lweight)
  5453. n := (lppland.Maxweight - lweight)
  5454. lppland.Lweight = lppland.Lweight + n
  5455. lweight += n
  5456. fweight += n
  5457. }
  5458. } else {
  5459. if lppland.Lweight == 0 {
  5460. continue
  5461. }
  5462. if w+lppland.Lweight >= 0 {
  5463. lppland.Lweight = lppland.Lweight + w
  5464. lweight = lweight + w
  5465. fweight = fweight + w
  5466. w = 0
  5467. } else {
  5468. w = w + lppland.Lweight
  5469. lweight = lweight - lppland.Lweight
  5470. fweight = fweight - lppland.Lweight
  5471. lppland.Lweight = 0
  5472. }
  5473. }
  5474. if lppland.Lweight > 0 {
  5475. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  5476. if err != nil {
  5477. tx.Rollback()
  5478. logs.Error(err)
  5479. return err
  5480. }
  5481. } else {
  5482. _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
  5483. if err != nil {
  5484. tx.Rollback()
  5485. logs.Error(err)
  5486. return err
  5487. }
  5488. }
  5489. if w == 0 {
  5490. break
  5491. }
  5492. }
  5493. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  5494. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5495. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  5496. if err != nil {
  5497. tx.Rollback()
  5498. logs.Error(err)
  5499. }
  5500. if w == 0 {
  5501. break
  5502. }
  5503. }
  5504. }
  5505. }
  5506. err = tx.Commit()
  5507. if err != nil {
  5508. logs.Error(err)
  5509. tx.Rollback()
  5510. return err
  5511. }
  5512. now := time.Now()
  5513. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5514. if err != nil {
  5515. logs.Error(err)
  5516. return nil
  5517. }
  5518. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5519. if err != nil {
  5520. logs.Error(err)
  5521. return nil
  5522. }
  5523. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  5524. if err != nil {
  5525. logs.Error(err)
  5526. return nil
  5527. }
  5528. for _, newLpplandtl1 := range newLpplandtl1List {
  5529. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5530. background,cowcount,ccountradio,lweighthis,createdate)
  5531. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5532. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  5533. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  5534. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  5535. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  5536. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  5537. if err != nil {
  5538. logs.Error(err)
  5539. // appG.Response(http.StatusOK, e.ERROR, false)
  5540. return err
  5541. }
  5542. }
  5543. for _, newFpd := range newFpdDataList {
  5544. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  5545. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  5546. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  5547. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  5548. if err != nil {
  5549. logs.Error(err)
  5550. // appG.Response(http.StatusOK, e.ERROR, false)
  5551. return err
  5552. }
  5553. }
  5554. for _, newFeedp := range newFeedpList {
  5555. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  5556. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  5557. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5558. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  5559. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  5560. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  5561. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  5562. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  5563. if err != nil {
  5564. logs.Error(err)
  5565. // appG.Response(http.StatusOK, e.ERROR, false)
  5566. return err
  5567. }
  5568. }
  5569. return nil
  5570. }
  5571. func DeleteFTdetail(c *gin.Context) {
  5572. appG := app.Gin{C: c}
  5573. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5574. fsion := gofasion.NewFasion(string(dataByte))
  5575. parammaps := fsion.Get("parammaps")
  5576. pastureid := parammaps.Get("pastureid").ValueStr()
  5577. ftid := parammaps.Get("ftid").ValueStr()
  5578. tx := restful.Engine.NewSession()
  5579. defer tx.Close()
  5580. tx.Begin()
  5581. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  5582. if err != nil {
  5583. tx.Rollback()
  5584. logs.Error(err)
  5585. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5586. return
  5587. }
  5588. if parammaps.Get("type").ValueStr() == "1" {
  5589. _, err := tx.SQL(`UPDATE feedp fp
  5590. set
  5591. fp.ftweight= IFNULL(IF(
  5592. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5593. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5594. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5595. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5596. ),0),fp.feedweight = IFNULL(IF(
  5597. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5598. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5599. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5600. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5601. ),0) +ifnull(fp.supplyweight,0)
  5602. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5603. if err != nil {
  5604. tx.Rollback()
  5605. logs.Error(err)
  5606. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5607. return
  5608. }
  5609. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  5610. _, err = tx.SQL(`
  5611. UPDATE fpdetail fpd
  5612. INNER JOIN feedp fp
  5613. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5614. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5615. ptuse= 0
  5616. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  5617. if err != nil {
  5618. tx.Rollback()
  5619. logs.Error(err)
  5620. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5621. return
  5622. }
  5623. } else {
  5624. _, err := tx.SQL(`UPDATE feedp fp
  5625. SET
  5626. fp.supplyweight= IFNULL(IF(
  5627. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5628. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5629. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5630. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5631. ),0),fp.feedweight = IFNULL(IF(
  5632. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  5633. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  5634. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  5635. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  5636. ),0) + ifnull(fp.supplyweight,0)
  5637. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5638. if err != nil {
  5639. tx.Rollback()
  5640. logs.Error(err)
  5641. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5642. return
  5643. }
  5644. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  5645. _, err = tx.SQL(`
  5646. UPDATE fpdetail fpd
  5647. INNER JOIN feedp fp
  5648. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  5649. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  5650. ptsrate = 0
  5651. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  5652. if err != nil {
  5653. tx.Rollback()
  5654. logs.Error(err)
  5655. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5656. return
  5657. }
  5658. }
  5659. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  5660. if err != nil {
  5661. tx.Rollback()
  5662. logs.Error(err)
  5663. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5664. return
  5665. }
  5666. err = tx.Commit()
  5667. if err != nil {
  5668. tx.Rollback()
  5669. logs.Error(err)
  5670. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5671. return
  5672. }
  5673. appG.Response(http.StatusOK, e.SUCCESS, true)
  5674. }
  5675. func DeleteSpillageAll(c *gin.Context) {
  5676. appG := app.Gin{C: c}
  5677. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5678. fsion := gofasion.NewFasion(string(dataByte))
  5679. parammaps := fsion.Get("parammaps")
  5680. pastureid := parammaps.Get("pastureid").ValueStr()
  5681. times := parammaps.Get("times").ValueStr()
  5682. barid := parammaps.Get("barid").ValueStr()
  5683. tx := restful.Engine.NewSession()
  5684. defer tx.Close()
  5685. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  5686. if err != nil {
  5687. logs.Error(err)
  5688. appG.Response(http.StatusOK, e.ERROR, false)
  5689. return
  5690. }
  5691. now := time.Now()
  5692. for _, item := range lpplandtl1List {
  5693. go func(item map[string]interface{}) {
  5694. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  5695. background,cowcount,ccountradio,lweighthis,createdate)
  5696. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  5697. item["pastureid"], item["lppid"], item["barid"],
  5698. item["barname"], item["fpdid"], item["fttype"],
  5699. item["lweight"], item["sort"], item["tmrid"],
  5700. item["tmrname"], item["background"], item["cowcount"],
  5701. item["ccountradio"], item["lweighthis"], now).Execute()
  5702. if err != nil {
  5703. logs.Error(err)
  5704. appG.Response(http.StatusOK, e.ERROR, false)
  5705. return
  5706. }
  5707. }(item)
  5708. }
  5709. tx.Begin()
  5710. _, 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()
  5711. if err != nil {
  5712. tx.Rollback()
  5713. logs.Error(err)
  5714. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5715. return
  5716. }
  5717. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  5718. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  5719. if err != nil {
  5720. tx.Rollback()
  5721. logs.Error(err)
  5722. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5723. return
  5724. }
  5725. err = tx.Commit()
  5726. if err != nil {
  5727. tx.Rollback()
  5728. logs.Error(err)
  5729. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5730. return
  5731. }
  5732. appG.Response(http.StatusOK, e.SUCCESS, true)
  5733. }
  5734. func GetTMRListEnableTypeAll(c *gin.Context) {
  5735. appG := app.Gin{C: c}
  5736. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5737. fsion := gofasion.NewFasion(string(dataByte))
  5738. parammaps := fsion.Get("parammaps")
  5739. pastureid := parammaps.Get("pastureid").ValueStr()
  5740. tx := restful.Engine.NewSession()
  5741. defer tx.Close()
  5742. dataList, err := tx.SQL(`SELECT
  5743. eqcode,
  5744. tname,
  5745. datacaptureno,
  5746. trim(tclassid) tclassid,
  5747. concat(tname,' / ',eqcode) tmrmix,
  5748. d.label tclassname,
  5749. maxstirfeed,
  5750. remark,
  5751. tmr.enable,
  5752. TRIM(tmr.id) id,
  5753. TRIM(tmr.pastureid)pastureid
  5754. FROM
  5755. tmr
  5756. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  5757. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  5758. ORDER BY id DESC`, pastureid).Query().List()
  5759. if err != nil {
  5760. logs.Error(err)
  5761. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5762. return
  5763. }
  5764. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  5765. if err != nil {
  5766. logs.Error(err)
  5767. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5768. return
  5769. }
  5770. var carNum int64
  5771. for _, sysopt := range sysoptData {
  5772. if sysopt["inforvalue"] == nil {
  5773. carNum = 1
  5774. } else {
  5775. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  5776. }
  5777. }
  5778. id := 200
  5779. n := 0
  5780. for i := carNum; i > 0; i-- {
  5781. id++
  5782. n++
  5783. data := make(map[string]interface{}, 0)
  5784. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  5785. data["tname"] = fmt.Sprintf("任意车%d", n)
  5786. data["datacaptureno"] = -2
  5787. data["tclassid"] = -2
  5788. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  5789. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  5790. data["maxstirfeed"] = 100000
  5791. data["remark"] = fmt.Sprintf("任意车%d", n)
  5792. data["enable"] = 1
  5793. data["id"] = fmt.Sprintf("%d", id)
  5794. data["pastureid"] = pastureid
  5795. // data := make(map[string]interface{}, 0)
  5796. // data["eqcode"] = fmt.Sprintf("AnyCar%d", n)
  5797. // data["tname"] = fmt.Sprintf("AnyCar%d", n)
  5798. // data["datacaptureno"] = -2
  5799. // data["tclassid"] = -2
  5800. // data["tmrmix"] = fmt.Sprintf("AnyCar%d", n)
  5801. // data["tclassname"] = fmt.Sprintf("AnyCar%d", n)
  5802. // data["maxstirfeed"] = 100000
  5803. // data["remark"] = fmt.Sprintf("AnyCar%d", n)
  5804. // data["enable"] = 1
  5805. // data["id"] = fmt.Sprintf("%d", id)
  5806. // data["pastureid"] = pastureid
  5807. dataList = append(dataList, data)
  5808. }
  5809. // UNION ALL
  5810. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  5811. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5812. }
  5813. func GetFeedpHistory(c *gin.Context) {
  5814. appG := app.Gin{C: c}
  5815. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5816. fsion := gofasion.NewFasion(string(dataByte))
  5817. // parammaps := fsion.Get("parammaps")
  5818. bar := fsion.Get("barname").ValueStr()
  5819. startDate := fsion.Get("startDate").ValueStr()
  5820. endDate := fsion.Get("endDate").ValueStr()
  5821. tx := restful.Engine.NewSession()
  5822. defer tx.Close()
  5823. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5824. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  5825. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  5826. if err != nil {
  5827. logs.Error(err)
  5828. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5829. return
  5830. }
  5831. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  5832. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  5833. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  5834. if err != nil {
  5835. logs.Error(err)
  5836. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5837. return
  5838. }
  5839. for _, feedp := range feedpList {
  5840. // LastftList, err := tx.SQL(` select tname ,id
  5841. // from feedtemplethistory where id = ?
  5842. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  5843. // if err != nil {
  5844. // logs.Error(err)
  5845. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5846. // return
  5847. // }
  5848. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  5849. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  5850. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  5851. if err != nil {
  5852. logs.Error(err)
  5853. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5854. return
  5855. }
  5856. var ftname interface{}
  5857. ftnamestatus := 0
  5858. ftname = feedp["ftname"]
  5859. var lastftid int64
  5860. if len(nextfeedpList) > 0 {
  5861. for _, ft := range nextfeedpList {
  5862. if ft["ftname"].(string) != feedp["ftname"].(string) {
  5863. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  5864. lastftid = ft["ftid"].(int64)
  5865. ftnamestatus = 1
  5866. break
  5867. }
  5868. }
  5869. }
  5870. for i, fpd := range fpdList {
  5871. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5872. fpd["weightstatus"] = 0
  5873. fpd["tratiostatus"] = 0
  5874. fpd["ftnamestatus"] = ftnamestatus
  5875. for k, fpd2 := range fpdList {
  5876. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5877. if fpd["weight"].(string) != fpd2["weight"].(string) {
  5878. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5879. fpd["weightstatus"] = 1
  5880. }
  5881. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  5882. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  5883. fpd["tratiostatus"] = 1
  5884. }
  5885. break
  5886. }
  5887. }
  5888. fpd["barid"] = feedp["barid"]
  5889. fpd["barname"] = feedp["barname"]
  5890. fpd["ccount"] = feedp["ccount"]
  5891. fpd["ratio"] = feedp["ratio"]
  5892. fpd["ccountratio"] = feedp["ccountratio"]
  5893. fpd["ftid"] = feedp["ftid"]
  5894. fpd["ftname"] = ftname
  5895. fpd["ccountstatus"] = 0
  5896. fpd["ccountratiostatus"] = 0
  5897. fpd["ratiostatus"] = 0
  5898. fpd["ftnamestatus"] = 0
  5899. fpd["lastftid"] = lastftid
  5900. for _, next := range nextfeedpList {
  5901. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  5902. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  5903. fpd["ccountstatus"] = 1
  5904. }
  5905. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  5906. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  5907. fpd["ccountratiostatus"] = 1
  5908. }
  5909. if next["ratio"].(string) != fpd["ratio"].(string) {
  5910. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  5911. fpd["ratiostatus"] = 1
  5912. }
  5913. // if next["ftname"].(string) != fpd["ftname"].(string) {
  5914. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  5915. // fpd["ftnamestatus"] = 1
  5916. // }
  5917. }
  5918. }
  5919. }
  5920. }
  5921. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  5922. }
  5923. // func GetLpplandtl1History(c *gin.Context) {
  5924. // appG := app.Gin{C: c}
  5925. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5926. // fsion := gofasion.NewFasion(string(dataByte))
  5927. // // parammaps := fsion.Get("parammaps")
  5928. // barid := fsion.Get("barid").ValueStr()
  5929. // startDate := fsion.Get("startDate").ValueStr()
  5930. // endDate := fsion.Get("endDate").ValueStr()
  5931. // tx := restful.Engine.NewSession()
  5932. // defer tx.Close()
  5933. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  5934. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  5935. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  5936. // // if err != nil {
  5937. // // logs.Error(err)
  5938. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5939. // // return
  5940. // // }
  5941. // // for _, feedp := range feedpList {
  5942. // // fmt.Println(feedp)
  5943. // // for i, fpd := range fpdList {
  5944. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5945. // // for k, fpd2 := range fpdList {
  5946. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5947. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5948. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5949. // // }
  5950. // // break
  5951. // // }
  5952. // // }
  5953. // // fpd["barid"] = feedp["barid"]
  5954. // // fpd["barname"] = feedp["barname"]
  5955. // // fpd["ccount"] = feedp["ccount"]
  5956. // // fpd["ratio"] = feedp["ratio"]
  5957. // // fpd["ccountratio"] = feedp["ccountratio"]
  5958. // // fpd["ftid"] = feedp["ftid"]
  5959. // // fpd["ftname"] = feedp["ftname"]
  5960. // // }
  5961. // // }
  5962. // // }
  5963. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5964. // }
  5965. func GetRemind(c *gin.Context) {
  5966. appG := app.Gin{C: c}
  5967. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5968. fsion := gofasion.NewFasion(string(dataByte))
  5969. parammaps := fsion.Get("parammaps")
  5970. pastureid := parammaps.Get("pastureid").ValueStr()
  5971. tx := restful.Engine.NewSession()
  5972. defer tx.Close()
  5973. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5974. if err != nil {
  5975. logs.Error(err)
  5976. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5977. return
  5978. }
  5979. // pastureid = "3"
  5980. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5981. if err != nil {
  5982. logs.Error(err)
  5983. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5984. return
  5985. }
  5986. defer resp.Body.Close()
  5987. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5988. buf.ReadFrom(resp.Body)
  5989. fmt.Println(string(buf.Bytes()))
  5990. respMap := make(map[string]interface{}, 0)
  5991. err = json.Unmarshal(buf.Bytes(), &respMap)
  5992. if err != nil {
  5993. logs.Error(err)
  5994. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5995. return
  5996. }
  5997. for _, data := range dataList {
  5998. r := make(map[string]interface{}, 0)
  5999. r["sys_name"] = ""
  6000. r["service_id"] = ""
  6001. r["pasture_id"] = ""
  6002. r["type_name"] = ""
  6003. r["remind_type_id"] = ""
  6004. r["remind_type"] = ""
  6005. r["push_date"] = ""
  6006. r["push_time"] = ""
  6007. r["interval_time"] = ""
  6008. r["push_limit"] = ""
  6009. r["template_id"] = ""
  6010. r["roles_id"] = ""
  6011. r["users_id"] = ""
  6012. r["date_type"] = ""
  6013. r["cycle_type"] = ""
  6014. data["data"] = r
  6015. for _, resp := range respMap["data"].([]interface{}) {
  6016. resp1 := resp.(map[string]interface{})
  6017. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  6018. if resp1["push_time"] == nil {
  6019. resp1["push_time"] = ""
  6020. }
  6021. data["data"] = resp1
  6022. break
  6023. }
  6024. }
  6025. }
  6026. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  6027. }
  6028. type NoticeMsgtype struct {
  6029. SysName string `json:"sys_name"`
  6030. PastureId int64 `json:"pasture_id"`
  6031. ServiceId int64 `json:"service_id"`
  6032. TypeName string `json:"type_name"`
  6033. RemindType int64 `json:"remind_type"`
  6034. PushDate int64 `json:"push_date"`
  6035. PushTime string `json:"push_time"`
  6036. IntervalTime int64 `json:"interval_time"`
  6037. PushLimit int64 `json:"push_limit"`
  6038. TemplateId string `json:"template_id"`
  6039. UsersId string `json:"users_id"`
  6040. DateType int64 `json:"date_type"`
  6041. CycleType int64 `json:"cycle_type"`
  6042. DelayTime int64 `json:"delay_time"`
  6043. Status int64 `json:"status"`
  6044. }
  6045. func UpdateRemind(c *gin.Context) {
  6046. appG := app.Gin{C: c}
  6047. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6048. parammaps := gofasion.NewFasion(string(dataByte))
  6049. // parammaps := fsion.Get("parammaps")
  6050. // user := parammaps.Get("user").ValueStr()
  6051. id := parammaps.Get("id").ValueInt64()
  6052. noticeMsgtype := new(NoticeMsgtype)
  6053. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  6054. noticeMsgtype.ServiceId = id
  6055. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  6056. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  6057. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  6058. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  6059. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  6060. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  6061. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  6062. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  6063. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  6064. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  6065. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  6066. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  6067. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  6068. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  6069. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  6070. //TODO
  6071. noticeMsgtype.SysName = "tmrWatch"
  6072. userList := parammaps.Get("user").Array()
  6073. var userstr []string
  6074. for _, user := range userList {
  6075. userstr = append(userstr, user.ValueStr())
  6076. }
  6077. tx := restful.Engine.NewSession()
  6078. defer tx.Close()
  6079. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  6080. if err != nil {
  6081. logs.Error(err)
  6082. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6083. return
  6084. }
  6085. // var jsonStr = []byte(noticeMsgtype
  6086. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  6087. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  6088. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  6089. req.Header.Set("Content-Type", "application/json")
  6090. client := &http.Client{}
  6091. resp, err := client.Do(req)
  6092. if err != nil {
  6093. logs.Error(err)
  6094. }
  6095. defer resp.Body.Close()
  6096. body, _ := ioutil.ReadAll(resp.Body)
  6097. fmt.Println("response Body:", string(body))
  6098. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  6099. if err != nil {
  6100. logs.Error(err)
  6101. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6102. return
  6103. }
  6104. defer getresp.Body.Close()
  6105. buf := bytes.NewBuffer(make([]byte, 0, 512))
  6106. buf.ReadFrom(getresp.Body)
  6107. // fmt.Println(string(buf.Bytes()))
  6108. respMap := make(map[string]interface{}, 0)
  6109. err = json.Unmarshal(buf.Bytes(), &respMap)
  6110. if err != nil {
  6111. logs.Error(err)
  6112. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6113. return
  6114. }
  6115. for _, resp := range respMap["data"].([]interface{}) {
  6116. resp1 := resp.(map[string]interface{})
  6117. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  6118. if err != nil {
  6119. logs.Error(err)
  6120. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6121. return
  6122. }
  6123. }
  6124. appG.Response(http.StatusOK, e.SUCCESS, true)
  6125. }
  6126. func GetSpillageallHistory(c *gin.Context) {
  6127. appG := app.Gin{C: c}
  6128. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6129. parammaps := gofasion.NewFasion(string(dataByte))
  6130. barname := parammaps.Get("barname").ValueStr()
  6131. pastureid := parammaps.Get("pastureid").ValueStr()
  6132. startdate := parammaps.Get("startDate").ValueStr()
  6133. enddate := parammaps.Get("endDate").ValueStr()
  6134. tx := restful.Engine.NewSession()
  6135. defer tx.Close()
  6136. historyList, err := tx.SQL(` select lpp.id,lpp.times,lppland.lweight,lppland.tmrid,lppland.tmrname,lpp.sort,
  6137. DATE_FORMAT(lppland.createdate,'%Y-%m-%d %H:%i:%s') as createdate ,u.username
  6138. from lpplandtl1history lppland
  6139. join lpplan lpp on lpp.id = lppland.lppid
  6140. left join user u on u.id = lppland.userId
  6141. where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  6142. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  6143. if err != nil {
  6144. logs.Error(err)
  6145. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6146. return
  6147. }
  6148. respMap := make([]map[string]interface{}, 0)
  6149. data := make(map[interface{}]interface{})
  6150. for _, history := range historyList {
  6151. data[history["createdate"]] = history["createdate"]
  6152. }
  6153. createList := []string{}
  6154. for _, v := range data {
  6155. createList = append(createList, v.(string))
  6156. }
  6157. // sort.Sort()
  6158. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  6159. sort.Slice(createList, func(i, j int) bool {
  6160. return createList[i] > createList[j]
  6161. })
  6162. for _, v := range createList {
  6163. a := make(map[string]interface{})
  6164. a["createdate"] = data[v]
  6165. // createList = append(createList, v.(string))
  6166. respMap = append(respMap, a)
  6167. }
  6168. number := 0
  6169. dataMap := make([]interface{}, 0)
  6170. for k, resp := range respMap {
  6171. createdate := resp["createdate"].(string)
  6172. var nextcreatedate string
  6173. if len(respMap) > k+1 {
  6174. nextcreatedate = respMap[k+1]["createdate"].(string)
  6175. }
  6176. // dataList := make(map[string][]interface{})
  6177. // list := make(map[string]interface{})
  6178. times := make(map[interface{}]int)
  6179. for _, history := range historyList {
  6180. // List := make(map[interface{}][]interface{})
  6181. i := 0
  6182. if history["createdate"].(string) == createdate {
  6183. times[history["times"]]++
  6184. data := make(map[string]interface{})
  6185. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  6186. // exist := false
  6187. if nextcreatedate != "" {
  6188. for _, history1 := range historyList {
  6189. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  6190. history1["times"].(int64) == history["times"].(int64) {
  6191. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", history1["lweight"], history["lweight"])
  6192. break
  6193. // exist = true
  6194. }
  6195. }
  6196. }
  6197. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6198. i++
  6199. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  6200. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  6201. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  6202. // resp["times"] = history["times"]
  6203. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6204. data1 := make(map[string]interface{})
  6205. data1["times"] = history["times"]
  6206. data1["empname"] = history["username"]
  6207. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  6208. data1["createdate"] = resp["createdate"]
  6209. // fmt.Println(dataList)
  6210. dataMap = append(dataMap, data1)
  6211. }
  6212. if i > number {
  6213. number = i
  6214. }
  6215. // respMap = append(respMap, dataList)
  6216. }
  6217. // for k, data := range dataList {
  6218. // resp[k] = data
  6219. // }
  6220. // resp["data"] = dataList
  6221. }
  6222. // resp := make(map[string]interface{})
  6223. // sort.Strings(createList)
  6224. //
  6225. // for _, create := range createList {
  6226. // for _, r := range respMap {
  6227. // if create == r["createdate"].(string) {
  6228. // resp[create] = r
  6229. // break
  6230. // }
  6231. // }
  6232. // }
  6233. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  6234. var trainsList []interface{}
  6235. for i := 0; i < number; i++ {
  6236. trains := make(map[string]interface{})
  6237. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  6238. trains["prop"] = fmt.Sprintf("a%d", i+1)
  6239. trainsList = append(trainsList, trains)
  6240. }
  6241. respdata := make(map[string]interface{})
  6242. respdata["data"] = dataMap
  6243. respdata["trains"] = trainsList
  6244. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  6245. }
  6246. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  6247. appG := app.Gin{C: c}
  6248. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6249. parammaps := gofasion.NewFasion(string(dataByte))
  6250. ftid := parammaps.Get("ftid").ValueInt64()
  6251. lastftid := parammaps.Get("lastftid").ValueInt64()
  6252. pastureid := parammaps.Get("pastureid").ValueInt64()
  6253. // createdate := parammaps.Get("createdate").ValueStr()
  6254. tx := restful.Engine.NewSession()
  6255. defer tx.Close()
  6256. data := make(map[string]interface{})
  6257. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6258. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  6259. if err != nil {
  6260. logs.Error(err)
  6261. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6262. return
  6263. }
  6264. feedtemplet := make(map[string]interface{})
  6265. for _, f := range feedtempletList {
  6266. feedtemplet = f
  6267. }
  6268. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  6269. if err != nil {
  6270. logs.Error(err)
  6271. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6272. return
  6273. }
  6274. feedtemplet["fit"] = fitList
  6275. data["current"] = feedtemplet
  6276. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  6277. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  6278. if err != nil {
  6279. logs.Error(err)
  6280. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6281. return
  6282. }
  6283. lastfeedtemplet := make(map[string]interface{})
  6284. for _, f := range lastfeedtempletList {
  6285. lastfeedtemplet = f
  6286. }
  6287. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  6288. if err != nil {
  6289. logs.Error(err)
  6290. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6291. return
  6292. }
  6293. lastfeedtemplet["fit"] = lastfitList
  6294. data["last"] = lastfeedtemplet
  6295. appG.Response(http.StatusOK, e.SUCCESS, data)
  6296. }
  6297. func GetFeedtempletHistory(c *gin.Context) {
  6298. appG := app.Gin{C: c}
  6299. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6300. parammaps := gofasion.NewFasion(string(dataByte))
  6301. ftid := parammaps.Get("ftid").ValueStr()
  6302. pastureid := parammaps.Get("pastureid").ValueInt64()
  6303. start := parammaps.Get("startdate").ValueStr()
  6304. end := parammaps.Get("enddate").ValueStr()
  6305. tx := restful.Engine.NewSession()
  6306. defer tx.Close()
  6307. 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 ?
  6308. and id = ? and pastureid = ? order by createdate desc `,
  6309. start, end, ftid, pastureid).Query().List()
  6310. if err != nil {
  6311. logs.Error(err)
  6312. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6313. return
  6314. }
  6315. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  6316. ftid, pastureid).Query().List()
  6317. if err != nil {
  6318. logs.Error(err)
  6319. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6320. return
  6321. }
  6322. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  6323. for i, ft := range ftList {
  6324. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  6325. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  6326. (select empname from user where id = fit.userId) empname,
  6327. 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
  6328. where fit.fitid = ?
  6329. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  6330. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  6331. if err != nil {
  6332. logs.Error(err)
  6333. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6334. return
  6335. }
  6336. ft["createdate"] = ft["createdate1"]
  6337. // data["tname"] = ft["tname"]
  6338. // data["tcode"] = ft["tcode"]
  6339. // data["tcolor"] = ft["tcolor"]
  6340. // data["fttype"] = ft["fttype"]
  6341. // data["ccname"] = ft["ccname"]
  6342. // data["source"] = ft["source"]
  6343. // data["version"] = ft["version"]
  6344. // data["remark"] = ft["remark"]
  6345. for n, ft2 := range ftList {
  6346. if i < n {
  6347. if ft["tname"].(string) != ft2["tname"].(string) {
  6348. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  6349. }
  6350. if _, ok := ft["tcode"]; ok {
  6351. if _, ok := ft2["tcode"]; ok {
  6352. if ft["tcode"].(string) != ft2["tcode"].(string) {
  6353. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  6354. }
  6355. }
  6356. }
  6357. if _, ok := ft["tcolor"]; ok {
  6358. if _, ok := ft2["tcolor"]; ok {
  6359. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  6360. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  6361. }
  6362. }
  6363. }
  6364. if _, ok := ft["fttype"]; ok {
  6365. if _, ok := ft2["fttype"]; ok {
  6366. if ft["fttype"].(string) != ft2["fttype"].(string) {
  6367. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  6368. }
  6369. }
  6370. }
  6371. if _, ok := ft["ccname"]; ok {
  6372. if _, ok := ft2["ccname"]; ok {
  6373. if ft["ccname"].(string) != ft2["ccname"].(string) {
  6374. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  6375. }
  6376. }
  6377. }
  6378. if _, ok := ft["source"]; ok {
  6379. if _, ok := ft2["source"]; ok {
  6380. if ft["source"].(string) != ft2["source"].(string) {
  6381. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  6382. }
  6383. }
  6384. }
  6385. if _, ok := ft["version"]; ok {
  6386. if _, ok := ft2["version"]; ok {
  6387. if ft["version"].(int64) != ft2["version"].(int64) {
  6388. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  6389. }
  6390. }
  6391. }
  6392. if _, ok := ft["remark"]; ok {
  6393. if _, ok := ft2["remark"]; ok {
  6394. if ft["remark"].(string) != ft2["remark"].(string) {
  6395. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  6396. }
  6397. }
  6398. }
  6399. break
  6400. }
  6401. }
  6402. dataList := make([]map[string]interface{}, 0)
  6403. if len(fithisList) > 0 {
  6404. for _, fit := range fithisList {
  6405. data := make(map[string]interface{})
  6406. data["feedgroup"] = fit["feedgroup"]
  6407. data["fname"] = fit["fname"]
  6408. data["empname"] = fit["empname"]
  6409. if fit["Eweight"] != nil {
  6410. if fit["Eweight"].(string) != fit["weight"].(string) {
  6411. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  6412. } else {
  6413. data["fweight"] = fit["Eweight"]
  6414. }
  6415. data["fweightstatus"] = 1
  6416. } else {
  6417. data["fweight"] = fit["weight"]
  6418. data["fweightstatus"] = 0
  6419. }
  6420. data["autosecond"] = fit["autosecond"]
  6421. // data["tname"] = ft["tname"]
  6422. // data["tcode"] = ft["tcode"]
  6423. // data["tcolor"] = ft["tcolor"]
  6424. // data["fttype"] = ft["fttype"]
  6425. // data["ccname"] = ft["ccname"]
  6426. // data["source"] = ft["source"]
  6427. // data["version"] = ft["version"]
  6428. // data["remark"] = ft["remark"]
  6429. // data["createdate"] = ft["createdate1"]
  6430. // ft["fit"] = data
  6431. dataList = append(dataList, data)
  6432. }
  6433. } else {
  6434. for _, fit := range ftdetailList {
  6435. data := make(map[string]interface{})
  6436. data["feedgroup"] = fit["feedgroup"]
  6437. data["fname"] = fit["fname"]
  6438. // if fit["Eweight"] != nil {
  6439. // data["weight"] = fit["Eweight"]
  6440. // } else {
  6441. data["fweight"] = fit["fweight"]
  6442. // }
  6443. data["autosecond"] = fit["autosecond"]
  6444. // ft["fit"] = data
  6445. dataList = append(dataList, data)
  6446. }
  6447. }
  6448. ft["fit"] = dataList
  6449. }
  6450. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  6451. }
  6452. func UpdateMaterialTMR(c *gin.Context) {
  6453. appG := app.Gin{C: c}
  6454. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6455. parammaps := gofasion.NewFasion(string(dataByte))
  6456. tmrid := parammaps.Get("tmrid").ValueStr()
  6457. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6458. lppid := parammaps.Get("lppid").ValueStr()
  6459. times := parammaps.Get("times").ValueStr()
  6460. pastureid := parammaps.Get("pastureid").ValueStr()
  6461. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  6462. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6463. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6464. tx := restful.Engine.NewSession()
  6465. defer tx.Close()
  6466. tx.Begin()
  6467. if tmrid != "1000" {
  6468. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6469. if err != nil {
  6470. logs.Error(err)
  6471. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6472. return
  6473. }
  6474. var maxstirfeed float64
  6475. for _, tmr := range tmrList {
  6476. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6477. }
  6478. if status == 0 {
  6479. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6480. if err != nil {
  6481. tx.Rollback()
  6482. logs.Error(err)
  6483. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6484. return
  6485. }
  6486. var lweight float64
  6487. for _, item := range lpplandtl1List {
  6488. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6489. lweight += fl
  6490. }
  6491. if lweight > maxstirfeed {
  6492. lweight = lweight - maxstirfeed
  6493. } else {
  6494. lweight = 0
  6495. }
  6496. if lweight > 0 {
  6497. lweight1 := lweight / float64(len(lpplandtl1List))
  6498. number := 0
  6499. for _, item := range lpplandtl1List {
  6500. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6501. if lweight1 >= fl {
  6502. number++
  6503. }
  6504. }
  6505. lweight := lweight / float64((len(lpplandtl1List) - number))
  6506. for _, item := range lpplandtl1List {
  6507. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6508. if lweight1 >= fl {
  6509. continue
  6510. }
  6511. if tmrtype == "1" {
  6512. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  6513. if err != nil {
  6514. tx.Rollback()
  6515. logs.Error(err)
  6516. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6517. return
  6518. }
  6519. } else if tmrtype == "2" {
  6520. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  6521. if err != nil {
  6522. tx.Rollback()
  6523. logs.Error(err)
  6524. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6525. return
  6526. }
  6527. }
  6528. if item["fttype"].(int64) == 0 {
  6529. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6530. if err != nil {
  6531. tx.Rollback()
  6532. logs.Error(err)
  6533. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6534. return
  6535. }
  6536. } else {
  6537. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6538. if err != nil {
  6539. tx.Rollback()
  6540. logs.Error(err)
  6541. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6542. return
  6543. }
  6544. }
  6545. }
  6546. } else {
  6547. for _, item := range lpplandtl1List {
  6548. // 自走式
  6549. if tmrtype == "1" {
  6550. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6551. if err != nil {
  6552. logs.Error(err)
  6553. tx.Rollback()
  6554. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6555. return
  6556. }
  6557. } else if tmrtype == "2" {
  6558. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6559. if err != nil {
  6560. logs.Error(err)
  6561. tx.Rollback()
  6562. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6563. return
  6564. }
  6565. }
  6566. }
  6567. }
  6568. } else if status == 1 {
  6569. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  6570. if err != nil {
  6571. logs.Error(err)
  6572. tx.Rollback()
  6573. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6574. return
  6575. }
  6576. var lweight float64
  6577. for _, item := range lpplandtl1List {
  6578. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6579. lweight += fl
  6580. }
  6581. if lweight > maxstirfeed {
  6582. lweight = lweight - maxstirfeed
  6583. } else {
  6584. lweight = 0
  6585. }
  6586. for _, item := range lpplandtl1List {
  6587. if lweight > 0 {
  6588. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6589. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6590. if fl >= lweight {
  6591. item["lweight"] = fl - lweight
  6592. lweight = 0
  6593. if tmrtype == "1" {
  6594. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  6595. if err != nil {
  6596. logs.Error(err)
  6597. tx.Rollback()
  6598. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6599. return
  6600. }
  6601. } else if tmrtype == "2" {
  6602. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  6603. if err != nil {
  6604. logs.Error(err)
  6605. tx.Rollback()
  6606. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6607. return
  6608. }
  6609. }
  6610. if item["fttype"].(int64) == 0 {
  6611. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6612. if err != nil {
  6613. logs.Error(err)
  6614. tx.Rollback()
  6615. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6616. return
  6617. }
  6618. } else {
  6619. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  6620. if err != nil {
  6621. logs.Error(err)
  6622. tx.Rollback()
  6623. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6624. return
  6625. }
  6626. }
  6627. } else {
  6628. lweight = lweight - fl
  6629. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  6630. if err != nil {
  6631. logs.Error(err)
  6632. tx.Rollback()
  6633. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6634. return
  6635. }
  6636. if item["fttype"].(int64) == 0 {
  6637. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6638. if err != nil {
  6639. logs.Error(err)
  6640. tx.Rollback()
  6641. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6642. return
  6643. }
  6644. } else {
  6645. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6646. if err != nil {
  6647. logs.Error(err)
  6648. tx.Rollback()
  6649. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6650. return
  6651. }
  6652. }
  6653. }
  6654. } else {
  6655. // 自走式
  6656. if tmrtype == "1" {
  6657. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  6658. if err != nil {
  6659. logs.Error(err)
  6660. tx.Rollback()
  6661. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6662. return
  6663. }
  6664. } else if tmrtype == "2" {
  6665. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  6666. if err != nil {
  6667. logs.Error(err)
  6668. tx.Rollback()
  6669. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6670. return
  6671. }
  6672. }
  6673. }
  6674. }
  6675. } else {
  6676. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  6677. if err != nil {
  6678. logs.Error(err)
  6679. tx.Rollback()
  6680. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6681. return
  6682. }
  6683. for _, item := range lpplandtl1List {
  6684. if item["fttype"].(int64) == 0 {
  6685. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6686. if err != nil {
  6687. logs.Error(err)
  6688. tx.Rollback()
  6689. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6690. return
  6691. }
  6692. } else {
  6693. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6694. if err != nil {
  6695. logs.Error(err)
  6696. tx.Rollback()
  6697. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6698. return
  6699. }
  6700. }
  6701. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  6702. if err != nil {
  6703. logs.Error(err)
  6704. tx.Rollback()
  6705. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6706. return
  6707. }
  6708. }
  6709. }
  6710. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  6711. if err != nil {
  6712. logs.Error(err)
  6713. tx.Rollback()
  6714. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6715. return
  6716. }
  6717. } else {
  6718. if status == 2 {
  6719. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  6720. if err != nil {
  6721. logs.Error(err)
  6722. tx.Rollback()
  6723. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6724. return
  6725. }
  6726. for _, item := range lpplandtl1List {
  6727. if item["fttype"].(int64) == 0 {
  6728. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6729. if err != nil {
  6730. logs.Error(err)
  6731. tx.Rollback()
  6732. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6733. return
  6734. }
  6735. } else {
  6736. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  6737. if err != nil {
  6738. logs.Error(err)
  6739. tx.Rollback()
  6740. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6741. return
  6742. }
  6743. }
  6744. }
  6745. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  6746. if err != nil {
  6747. logs.Error(err)
  6748. tx.Rollback()
  6749. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6750. return
  6751. }
  6752. } else {
  6753. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  6754. if err != nil {
  6755. logs.Error(err)
  6756. tx.Rollback()
  6757. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6758. return
  6759. }
  6760. }
  6761. }
  6762. err := tx.Commit()
  6763. if err != nil {
  6764. logs.Error(err)
  6765. tx.Rollback()
  6766. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6767. return
  6768. }
  6769. appG.Response(http.StatusOK, e.SUCCESS, true)
  6770. }
  6771. func UpdateMaterialTMRDate(c *gin.Context) {
  6772. appG := app.Gin{C: c}
  6773. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6774. parammaps := gofasion.NewFasion(string(dataByte))
  6775. tmrid := parammaps.Get("tmrid").ValueStr()
  6776. tmrtype := parammaps.Get("tmrtype").ValueStr()
  6777. lppid := parammaps.Get("lppid").ValueStr()
  6778. times := parammaps.Get("times").ValueStr()
  6779. pastureid := parammaps.Get("pastureid").ValueStr()
  6780. date := parammaps.Get("date").ValueStr()
  6781. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  6782. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  6783. tx := restful.Engine.NewSession()
  6784. defer tx.Close()
  6785. tx.Begin()
  6786. if tmrid != "1000" {
  6787. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  6788. if err != nil {
  6789. logs.Error(err)
  6790. tx.Rollback()
  6791. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6792. return
  6793. }
  6794. var maxstirfeed float64
  6795. for _, tmr := range tmrList {
  6796. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  6797. }
  6798. if status == 0 {
  6799. 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()
  6800. if err != nil {
  6801. logs.Error(err)
  6802. tx.Rollback()
  6803. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6804. return
  6805. }
  6806. var lweight float64
  6807. for _, item := range lpplandtl1List {
  6808. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6809. lweight += fl
  6810. }
  6811. if lweight > maxstirfeed {
  6812. lweight = lweight - maxstirfeed
  6813. } else {
  6814. lweight = 0
  6815. }
  6816. if lweight > 0 {
  6817. lweight1 := lweight / float64(len(lpplandtl1List))
  6818. number := 0
  6819. for _, item := range lpplandtl1List {
  6820. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6821. if lweight1 >= fl {
  6822. number++
  6823. }
  6824. }
  6825. lweight := lweight / float64((len(lpplandtl1List) - number))
  6826. for _, item := range lpplandtl1List {
  6827. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6828. if lweight1 >= fl {
  6829. continue
  6830. }
  6831. if tmrtype == "1" {
  6832. _, 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()
  6833. if err != nil {
  6834. logs.Error(err)
  6835. tx.Rollback()
  6836. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6837. return
  6838. }
  6839. } else if tmrtype == "2" {
  6840. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  6841. if err != nil {
  6842. logs.Error(err)
  6843. tx.Rollback()
  6844. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6845. return
  6846. }
  6847. }
  6848. if item["fttype"].(int64) == 0 {
  6849. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6850. if err != nil {
  6851. logs.Error(err)
  6852. tx.Rollback()
  6853. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6854. return
  6855. }
  6856. } else {
  6857. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6858. if err != nil {
  6859. logs.Error(err)
  6860. tx.Rollback()
  6861. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6862. return
  6863. }
  6864. }
  6865. }
  6866. } else {
  6867. for _, item := range lpplandtl1List {
  6868. // 自走式
  6869. if tmrtype == "1" {
  6870. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6871. if err != nil {
  6872. logs.Error(err)
  6873. tx.Rollback()
  6874. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6875. return
  6876. }
  6877. } else if tmrtype == "2" {
  6878. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6879. if err != nil {
  6880. logs.Error(err)
  6881. tx.Rollback()
  6882. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6883. return
  6884. }
  6885. }
  6886. }
  6887. }
  6888. } else if status == 1 {
  6889. 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()
  6890. if err != nil {
  6891. logs.Error(err)
  6892. tx.Rollback()
  6893. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6894. return
  6895. }
  6896. var lweight float64
  6897. for _, item := range lpplandtl1List {
  6898. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6899. lweight += fl
  6900. }
  6901. if lweight > maxstirfeed {
  6902. lweight = lweight - maxstirfeed
  6903. } else {
  6904. lweight = 0
  6905. }
  6906. for _, item := range lpplandtl1List {
  6907. if lweight > 0 {
  6908. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  6909. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  6910. if fl >= lweight {
  6911. item["lweight"] = fl - lweight
  6912. lweight = 0
  6913. if tmrtype == "1" {
  6914. _, 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()
  6915. if err != nil {
  6916. logs.Error(err)
  6917. tx.Rollback()
  6918. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6919. return
  6920. }
  6921. } else if tmrtype == "2" {
  6922. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  6923. if err != nil {
  6924. logs.Error(err)
  6925. tx.Rollback()
  6926. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6927. return
  6928. }
  6929. }
  6930. if item["fttype"].(int64) == 0 {
  6931. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6932. if err != nil {
  6933. logs.Error(err)
  6934. tx.Rollback()
  6935. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6936. return
  6937. }
  6938. } else {
  6939. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  6940. if err != nil {
  6941. logs.Error(err)
  6942. tx.Rollback()
  6943. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6944. return
  6945. }
  6946. }
  6947. } else {
  6948. lweight = lweight - fl
  6949. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6950. if err != nil {
  6951. logs.Error(err)
  6952. tx.Rollback()
  6953. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6954. return
  6955. }
  6956. if item["fttype"].(int64) == 0 {
  6957. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6958. if err != nil {
  6959. logs.Error(err)
  6960. tx.Rollback()
  6961. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6962. return
  6963. }
  6964. } else {
  6965. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6966. if err != nil {
  6967. logs.Error(err)
  6968. tx.Rollback()
  6969. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6970. return
  6971. }
  6972. }
  6973. }
  6974. } else {
  6975. // 自走式
  6976. if tmrtype == "1" {
  6977. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6978. if err != nil {
  6979. logs.Error(err)
  6980. tx.Rollback()
  6981. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6982. return
  6983. }
  6984. } else if tmrtype == "2" {
  6985. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6986. if err != nil {
  6987. logs.Error(err)
  6988. tx.Rollback()
  6989. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6990. return
  6991. }
  6992. }
  6993. }
  6994. }
  6995. } else {
  6996. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6997. if err != nil {
  6998. logs.Error(err)
  6999. tx.Rollback()
  7000. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7001. return
  7002. }
  7003. for _, item := range lpplandtl1List {
  7004. if item["fttype"].(int64) == 0 {
  7005. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7006. if err != nil {
  7007. logs.Error(err)
  7008. tx.Rollback()
  7009. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7010. return
  7011. }
  7012. } else {
  7013. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7014. if err != nil {
  7015. logs.Error(err)
  7016. tx.Rollback()
  7017. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7018. return
  7019. }
  7020. }
  7021. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  7022. if err != nil {
  7023. logs.Error(err)
  7024. tx.Rollback()
  7025. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7026. return
  7027. }
  7028. }
  7029. }
  7030. _, 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()
  7031. if err != nil {
  7032. logs.Error(err)
  7033. tx.Rollback()
  7034. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7035. return
  7036. }
  7037. } else {
  7038. if status == 2 {
  7039. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  7040. if err != nil {
  7041. logs.Error(err)
  7042. tx.Rollback()
  7043. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7044. return
  7045. }
  7046. for _, item := range lpplandtl1List {
  7047. if item["fttype"].(int64) == 0 {
  7048. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7049. if err != nil {
  7050. logs.Error(err)
  7051. tx.Rollback()
  7052. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7053. return
  7054. }
  7055. } else {
  7056. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  7057. if err != nil {
  7058. logs.Error(err)
  7059. tx.Rollback()
  7060. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7061. return
  7062. }
  7063. }
  7064. }
  7065. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  7066. if err != nil {
  7067. logs.Error(err)
  7068. tx.Rollback()
  7069. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7070. return
  7071. }
  7072. } else {
  7073. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  7074. if err != nil {
  7075. logs.Error(err)
  7076. tx.Rollback()
  7077. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7078. return
  7079. }
  7080. }
  7081. }
  7082. err := tx.Commit()
  7083. if err != nil {
  7084. logs.Error(err)
  7085. tx.Rollback()
  7086. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7087. return
  7088. }
  7089. appG.Response(http.StatusOK, e.SUCCESS, true)
  7090. }
  7091. func Decimal(value float64) float64 {
  7092. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  7093. return value
  7094. }
  7095. func UpdateDailyData(c *gin.Context) {
  7096. appG := app.Gin{C: c}
  7097. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7098. parammaps := gofasion.NewFasion(string(dataByte))
  7099. pid := parammaps.Get("pid").ValueDefaultStr("0")
  7100. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  7101. sort := parammaps.Get("sort").ValueDefaultStr("0")
  7102. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  7103. date := parammaps.Get("date").ValueStr()
  7104. tx := restful.Engine.NewSession()
  7105. defer tx.Close()
  7106. 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()
  7107. if err != nil {
  7108. logs.Error("UpdateDailyData-error-0:", err)
  7109. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7110. return
  7111. }
  7112. if count > 0 {
  7113. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("该计划已开始执行,禁止修改!"))
  7114. return
  7115. }
  7116. tx.Begin()
  7117. if location == 0 {
  7118. fid := parammaps.Get("fid").ValueStr()
  7119. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  7120. if err != nil {
  7121. logs.Error("UpdateDailyData-error-1:", err)
  7122. tx.Rollback()
  7123. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7124. return
  7125. }
  7126. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7127. if err != nil {
  7128. logs.Error("UpdateDailyData-error-1:", err)
  7129. tx.Rollback()
  7130. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7131. return
  7132. }
  7133. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  7134. if err != nil {
  7135. fmt.Println("Error:", err)
  7136. return
  7137. }
  7138. actualWeight := weight - num
  7139. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  7140. if err != nil {
  7141. logs.Error("UpdateDailyData-error-2:", err)
  7142. tx.Rollback()
  7143. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7144. return
  7145. }
  7146. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  7147. if err != nil {
  7148. logs.Error("UpdateDailyData-error-3:", err)
  7149. tx.Rollback()
  7150. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7151. return
  7152. }
  7153. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7154. if err != nil {
  7155. logs.Error("UpdateDailyData-error-4:", err)
  7156. tx.Rollback()
  7157. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7158. return
  7159. }
  7160. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7161. if err != nil {
  7162. logs.Error("UpdateDailyData-error-5:", err)
  7163. tx.Rollback()
  7164. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7165. return
  7166. }
  7167. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7168. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7169. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7170. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7171. if err != nil {
  7172. fmt.Println("Error:", err)
  7173. return
  7174. }
  7175. // actual := actualWeight / float64(len(downloadedplanList))
  7176. for _, item := range downloadedplanList {
  7177. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7178. if err != nil {
  7179. fmt.Println("Error:", err)
  7180. return
  7181. }
  7182. actual := itemLweight / lweight * actualWeight
  7183. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7184. if err != nil {
  7185. logs.Error("UpdateDailyData-error-6:", err)
  7186. tx.Rollback()
  7187. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7188. return
  7189. }
  7190. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7191. if err != nil {
  7192. logs.Error("UpdateDailyData-error-7:", err)
  7193. tx.Rollback()
  7194. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7195. return
  7196. }
  7197. _, 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()
  7198. if err != nil {
  7199. logs.Error("UpdateDailyData-error-8:", err)
  7200. tx.Rollback()
  7201. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7202. return
  7203. }
  7204. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  7205. if err != nil {
  7206. logs.Error("UpdateDailyData-error-9:", err)
  7207. tx.Rollback()
  7208. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7209. return
  7210. }
  7211. }
  7212. } else {
  7213. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7214. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7215. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7216. // if err != nil {
  7217. // fmt.Println("Error:", err)
  7218. // return
  7219. // }
  7220. for _, item := range downloadedplanList {
  7221. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7222. if err != nil {
  7223. logs.Error("UpdateDailyData-error-6:", err)
  7224. tx.Rollback()
  7225. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7226. return
  7227. }
  7228. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7229. item["lweight"], actualWeight, item["id"]).Execute()
  7230. if err != nil {
  7231. logs.Error("UpdateDailyData-error-7:", err)
  7232. tx.Rollback()
  7233. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7234. return
  7235. }
  7236. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7237. where pid = ?`, item["id"]).Execute()
  7238. if err != nil {
  7239. logs.Error("UpdateDailyData-error-8:", err)
  7240. tx.Rollback()
  7241. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7242. return
  7243. }
  7244. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7245. if err != nil {
  7246. logs.Error("UpdateDailyData-error-9:", err)
  7247. tx.Rollback()
  7248. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7249. return
  7250. }
  7251. }
  7252. }
  7253. } else {
  7254. fbarid := parammaps.Get("fbarid").ValueStr()
  7255. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  7256. if err != nil {
  7257. logs.Error("UpdateDailyData-error-10:", err)
  7258. tx.Rollback()
  7259. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7260. return
  7261. }
  7262. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  7263. if err != nil {
  7264. logs.Error("UpdateDailyData-error-1:", err)
  7265. tx.Rollback()
  7266. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7267. return
  7268. }
  7269. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  7270. if err != nil {
  7271. fmt.Println("Error:", err)
  7272. return
  7273. }
  7274. actualWeight := weight - num
  7275. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  7276. if err != nil {
  7277. logs.Error("UpdateDailyData-error-11:", err)
  7278. tx.Rollback()
  7279. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7280. return
  7281. }
  7282. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  7283. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  7284. if err != nil {
  7285. logs.Error("UpdateDailyData-error-12:", err)
  7286. tx.Rollback()
  7287. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7288. return
  7289. }
  7290. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7291. where pid = ? `, pid).Execute()
  7292. if err != nil {
  7293. logs.Error("UpdateDailyData-error-13:", err)
  7294. tx.Rollback()
  7295. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7296. return
  7297. }
  7298. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  7299. if err != nil {
  7300. logs.Error("UpdateDailyData-error-14:", err)
  7301. tx.Rollback()
  7302. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  7303. return
  7304. }
  7305. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  7306. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7307. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  7308. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  7309. if err != nil {
  7310. fmt.Println("Error:", err)
  7311. return
  7312. }
  7313. for _, item := range downloadedplanList {
  7314. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7315. if err != nil {
  7316. fmt.Println("Error:", err)
  7317. return
  7318. }
  7319. actual := itemLweight / lweight * actualWeight
  7320. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  7321. if err != nil {
  7322. logs.Error("UpdateDailyData-error-6:", err)
  7323. tx.Rollback()
  7324. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7325. return
  7326. }
  7327. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7328. if err != nil {
  7329. logs.Error("UpdateDailyData-error-7:", err)
  7330. tx.Rollback()
  7331. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7332. return
  7333. }
  7334. _, 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()
  7335. if err != nil {
  7336. logs.Error("UpdateDailyData-error-8:", err)
  7337. tx.Rollback()
  7338. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7339. return
  7340. }
  7341. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  7342. if err != nil {
  7343. logs.Error("UpdateDailyData-error-9:", err)
  7344. tx.Rollback()
  7345. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7346. return
  7347. }
  7348. }
  7349. } else {
  7350. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  7351. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  7352. for _, item := range downloadedplanList {
  7353. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  7354. // if err != nil {
  7355. // fmt.Println("Error:", err)
  7356. // return
  7357. // }
  7358. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  7359. if err != nil {
  7360. logs.Error("UpdateDailyData-error-6:", err)
  7361. tx.Rollback()
  7362. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7363. return
  7364. }
  7365. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  7366. item["lweight"], actualWeight, item["id"]).Execute()
  7367. if err != nil {
  7368. logs.Error("UpdateDailyData-error-7:", err)
  7369. tx.Rollback()
  7370. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7371. return
  7372. }
  7373. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  7374. where pid = ?`, item["id"]).Execute()
  7375. if err != nil {
  7376. logs.Error("UpdateDailyData-error-8:", err)
  7377. tx.Rollback()
  7378. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7379. return
  7380. }
  7381. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  7382. if err != nil {
  7383. logs.Error("UpdateDailyData-error-9:", err)
  7384. tx.Rollback()
  7385. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  7386. return
  7387. }
  7388. }
  7389. }
  7390. }
  7391. err = tx.Commit()
  7392. if err != nil {
  7393. logs.Error("UpdateDailyData-error-20:", err)
  7394. tx.Rollback()
  7395. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  7396. return
  7397. }
  7398. appG.Response(http.StatusOK, e.SUCCESS, true)
  7399. }
  7400. func GetFormulaStatistics(c *gin.Context) {
  7401. appG := app.Gin{C: c}
  7402. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7403. parammaps := gofasion.NewFasion(string(dataByte))
  7404. startTime := parammaps.Get("startTime").ValueStr()
  7405. endTime := parammaps.Get("endTime").ValueStr()
  7406. pastureId := parammaps.Get("pastureId").ValueStr()
  7407. tx := restful.Engine.NewSession()
  7408. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  7409. if err != nil {
  7410. logs.Error("GetFormulaStatistics-error-1:", err)
  7411. tx.Rollback()
  7412. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7413. return
  7414. }
  7415. var feedtemplet, dateList []string
  7416. for _, f := range feedtempletList {
  7417. feedtemplet = append(feedtemplet, f["tname"].(string))
  7418. }
  7419. layout := "2006-01-02"
  7420. // s := "2023-05-01"
  7421. // e := "2023-05-23"
  7422. start, err := time.Parse(layout, startTime)
  7423. if err != nil {
  7424. fmt.Println(err)
  7425. return
  7426. }
  7427. end, err := time.Parse(layout, endTime)
  7428. if err != nil {
  7429. fmt.Println(err)
  7430. return
  7431. }
  7432. end = end.AddDate(0, 0, 1)
  7433. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  7434. dateList = append(dateList, d.Format("2006-01-02"))
  7435. }
  7436. downloadedplanList, err := tx.SQL(`select count(1) total,ftd.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  7437. 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= ?
  7438. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  7439. if err != nil {
  7440. logs.Error("GetFormulaStatistics-error-2:", err)
  7441. tx.Rollback()
  7442. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  7443. return
  7444. }
  7445. var data2 [][]interface{}
  7446. for _, f := range feedtemplet {
  7447. var data1 []interface{}
  7448. for _, date := range dateList {
  7449. exist := false
  7450. for _, item := range downloadedplanList {
  7451. if date == item["mydate"].(string) && f == item["tname"].(string) {
  7452. data1 = append(data1, item["total"])
  7453. exist = true
  7454. break
  7455. }
  7456. }
  7457. if !exist {
  7458. data1 = append(data1, 0)
  7459. }
  7460. }
  7461. data2 = append(data2, data1)
  7462. }
  7463. //前端让加的
  7464. feedtemplet = append(feedtemplet, "")
  7465. {
  7466. var data1 []interface{}
  7467. for _, f := range dateList {
  7468. // f = f + "\n"
  7469. fmt.Println(f)
  7470. data1 = append(data1, 0)
  7471. }
  7472. data2 = append(data2, data1)
  7473. }
  7474. resp := make(map[string]interface{}, 0)
  7475. resp["xdata"] = dateList
  7476. resp["data1"] = feedtemplet
  7477. resp["data2"] = data2
  7478. appG.Response(http.StatusOK, e.SUCCESS, resp)
  7479. }
  7480. func GetPlanData(c *gin.Context) {
  7481. appG := app.Gin{C: c}
  7482. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7483. fsion := gofasion.NewFasion(string(dataByte))
  7484. sqlnamestr := fsion.Get("name").ValueStr()
  7485. sqlnamestr1 := fsion.Get("name1").ValueStr()
  7486. offset := fsion.Get("offset").ValueDefaultInt(0)
  7487. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  7488. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7489. month := fsion.Get("month").ValueDefaultStr("map")
  7490. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  7491. tx := restful.Engine.NewSession()
  7492. err := tx.Begin()
  7493. defer func() {
  7494. switch {
  7495. case err != nil:
  7496. if tx != nil {
  7497. tx.Rollback()
  7498. }
  7499. default:
  7500. if tx != nil {
  7501. err = tx.Commit()
  7502. }
  7503. }
  7504. if tx != nil {
  7505. tx.Close()
  7506. }
  7507. }()
  7508. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7509. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  7510. if sql != "" {
  7511. s_params := make([]interface{}, 0)
  7512. if fsion.HasKey("parammaps") {
  7513. parammaps := fsion.Get("parammaps")
  7514. paramslist := strings.Split(p, ",")
  7515. if len(paramslist) > 0 && p != "" {
  7516. for _, value := range paramslist {
  7517. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7518. if tempv, exists := c.Get("jwt_username"); exists {
  7519. s_params = append(s_params, tempv.(string))
  7520. } else {
  7521. s_params = append(s_params, "")
  7522. }
  7523. } else {
  7524. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7525. }
  7526. }
  7527. }
  7528. }
  7529. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7530. if err != nil {
  7531. appG.Response(http.StatusOK, e.ERROR, err.Error())
  7532. } else {
  7533. paramslist1 := strings.Split(p1, ",")
  7534. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7535. s_params1 := make([]interface{}, 0)
  7536. if len(paramslist1) > 0 && p1 != "" {
  7537. for _, v := range paramslist1 {
  7538. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  7539. }
  7540. }
  7541. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  7542. for _, item := range arr {
  7543. trgaddressList := []string{}
  7544. if _, ok := item["trgaddress"]; ok {
  7545. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7546. for _, str := range trgaddressList1 {
  7547. if str != "" {
  7548. trgaddressList = append(trgaddressList, str)
  7549. }
  7550. }
  7551. }
  7552. item["trgaddressList"] = trgaddressList
  7553. }
  7554. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  7555. }
  7556. // var wg sync.WaitGroup
  7557. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7558. // wg.Add(1)
  7559. // go func(value map[string]interface{}) {
  7560. // defer wg.Done()
  7561. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  7562. // }(value)
  7563. // }
  7564. // wg.Wait()
  7565. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7566. }
  7567. } else {
  7568. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7569. }
  7570. }
  7571. func PostPlanData(c *gin.Context) {
  7572. appG := app.Gin{C: c}
  7573. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7574. fsion := gofasion.NewFasion(string(dataByte))
  7575. logging.Info("PostRJSBData err: ", string(dataByte))
  7576. s_params := make([]interface{}, 0)
  7577. tx := restful.Engine.NewSession()
  7578. err := tx.Begin()
  7579. defer func() {
  7580. switch {
  7581. case err != nil:
  7582. if tx != nil {
  7583. tx.Rollback()
  7584. }
  7585. default:
  7586. if tx != nil {
  7587. err = tx.Commit()
  7588. }
  7589. }
  7590. if tx != nil {
  7591. tx.Close()
  7592. }
  7593. }()
  7594. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  7595. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  7596. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  7597. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  7598. if !fsion.HasKey("parammaps") {
  7599. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  7600. return
  7601. }
  7602. parammaps := fsion.Get("parammaps")
  7603. // paramslist := strings.Split(p, ",")
  7604. // if len(paramslist) > 0 && p != "" {
  7605. // for _, value := range paramslist {
  7606. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7607. // }
  7608. // }
  7609. // _, err = tx.SQL(sql, s_params...).Execute()
  7610. // if err != nil {
  7611. // logging.Error("PostRJSBData err: ", err)
  7612. // msg := geterrmsg(err.Error())
  7613. // appG.Response(http.StatusOK, e.ERROR, msg)
  7614. // return
  7615. // }
  7616. s_params = make([]interface{}, 0)
  7617. paramslist := strings.Split(p1, ",")
  7618. if len(paramslist) > 0 && p1 != "" {
  7619. for _, value := range paramslist {
  7620. // if value == "ID" {
  7621. // id := parammaps.Get("ID").ValueStr()
  7622. // pastureid := parammaps.Get("pastureid").ValueStr()
  7623. // 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
  7624. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7625. // if err != nil {
  7626. // logging.Error("PostRJSBData err: ", err)
  7627. // msg := geterrmsg(err.Error())
  7628. // appG.Response(http.StatusOK, e.ERROR, msg)
  7629. // return
  7630. // }
  7631. // for _, item := range datalist {
  7632. // id = item["id"]
  7633. // }
  7634. // s_params = append(s_params, id)
  7635. // } else {
  7636. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7637. // }
  7638. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7639. }
  7640. }
  7641. _, err = tx.SQL(sql1, s_params...).Execute()
  7642. if err != nil {
  7643. logging.Error("PostRJSBData1 err: ", err)
  7644. msg := geterrmsg(err.Error())
  7645. appG.Response(http.StatusOK, e.ERROR, msg)
  7646. return
  7647. }
  7648. s_params = make([]interface{}, 0)
  7649. paramslist = strings.Split(p2, ",")
  7650. if len(paramslist) > 0 && p2 != "" {
  7651. for _, value := range paramslist {
  7652. if value == "ID" {
  7653. id := parammaps.Get("ID").ValueStr()
  7654. pastureid := parammaps.Get("pastureid").ValueStr()
  7655. 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
  7656. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  7657. if err != nil {
  7658. logging.Error("PostRJSBData err: ", err)
  7659. msg := geterrmsg(err.Error())
  7660. appG.Response(http.StatusOK, e.ERROR, msg)
  7661. return
  7662. }
  7663. for _, item := range datalist {
  7664. id = item["id"]
  7665. }
  7666. s_params = append(s_params, id)
  7667. } else {
  7668. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7669. }
  7670. }
  7671. }
  7672. _, err = tx.SQL(sql2, s_params...).Execute()
  7673. if err != nil {
  7674. logging.Error("PostRJSBData2 err: ", err)
  7675. msg := geterrmsg(err.Error())
  7676. appG.Response(http.StatusOK, e.ERROR, msg)
  7677. return
  7678. }
  7679. s_params = make([]interface{}, 0)
  7680. paramslist = strings.Split(p3, ",")
  7681. if len(paramslist) > 0 && p3 != "" {
  7682. for _, value := range paramslist {
  7683. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7684. }
  7685. }
  7686. _, err = tx.SQL(sql3, s_params...).Execute()
  7687. if err != nil {
  7688. logging.Error("PostRJSBData3 err: ", err)
  7689. msg := geterrmsg(err.Error())
  7690. appG.Response(http.StatusOK, e.ERROR, msg)
  7691. return
  7692. }
  7693. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7694. }
  7695. func CheckFeedTrgaddress(c *gin.Context) {
  7696. appG := app.Gin{C: c}
  7697. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7698. fsion := gofasion.NewFasion(string(dataByte))
  7699. fclassid := fsion.Get("fclassid").ValueStr()
  7700. feedId := fsion.Get("feedId").ValueStr()
  7701. backup1 := fsion.Get("backup1").ValueStr()
  7702. backup1List := strings.Split(backup1, ",")
  7703. tx := restful.Engine.NewSession()
  7704. defer tx.Close()
  7705. // if backup1 != "" {
  7706. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  7707. for _, feed := range feedList {
  7708. if feed["backup1"] == "" {
  7709. continue
  7710. }
  7711. feedbackupList := strings.Split(feed["backup1"], ",")
  7712. for _, feedbackup := range feedbackupList {
  7713. for _, backup := range backup1List {
  7714. if feedbackup == backup {
  7715. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  7716. return
  7717. }
  7718. }
  7719. }
  7720. }
  7721. // }
  7722. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  7723. }
  7724. func ThiGetDataByName(c *gin.Context) {
  7725. appG := app.Gin{C: c}
  7726. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7727. fsion := gofasion.NewFasion(string(dataByte))
  7728. sqlnamestr := fsion.Get("name").ValueStr()
  7729. offset := fsion.Get("offset").ValueDefaultInt(0)
  7730. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  7731. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  7732. tx := restful.Engine.NewSession()
  7733. err := tx.Begin()
  7734. defer func() {
  7735. switch {
  7736. case err != nil:
  7737. logging.Error("tx.Begin 事务启动失败__error:", err)
  7738. if tx != nil {
  7739. tx.Rollback()
  7740. }
  7741. default:
  7742. if tx != nil {
  7743. err = tx.Commit()
  7744. }
  7745. }
  7746. if tx != nil {
  7747. tx.Close()
  7748. }
  7749. }()
  7750. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  7751. if sql != "" {
  7752. s_params := make([]interface{}, 0)
  7753. if fsion.HasKey("parammaps") {
  7754. parammaps := fsion.Get("parammaps")
  7755. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  7756. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  7757. }
  7758. paramslist := strings.Split(p, ",")
  7759. if len(paramslist) > 0 && p != "" {
  7760. for _, value := range paramslist {
  7761. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  7762. if tempv, exists := c.Get("jwt_username"); exists {
  7763. s_params = append(s_params, tempv.(string))
  7764. } else {
  7765. s_params = append(s_params, "")
  7766. }
  7767. } else {
  7768. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  7769. }
  7770. }
  7771. }
  7772. } else if fsion.HasKey("params") {
  7773. params := fsion.Get("params").Array()
  7774. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  7775. for _, v_params := range params {
  7776. s_params = append(s_params, v_params.ValueStr())
  7777. }
  7778. }
  7779. if returntype == "xlsx" {
  7780. var xlsxfile *xlsx.File
  7781. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  7782. //c.File("c:/dd.xlsx")
  7783. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  7784. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  7785. c.Header("Content-Transfer-Encoding", "binary")
  7786. _ = xlsxfile.Write(c.Writer)
  7787. } else {
  7788. if sqlnamestr == "getHomepageStr" {
  7789. parammaps := fsion.Get("parammaps")
  7790. pastureid := parammaps.Get("pastureid").ValueStr()
  7791. var montimeList []float64
  7792. var montime float64
  7793. var wg sync.WaitGroup
  7794. now := time.Now()
  7795. for i := 0; i < 30; i++ {
  7796. wg.Add(1)
  7797. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  7798. go func(nowstr string) {
  7799. defer wg.Done()
  7800. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  7801. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  7802. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  7803. montimeList = append(montimeList, m)
  7804. }(nowstr)
  7805. }
  7806. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7807. if err != nil {
  7808. logging.Error("GetDataByName err: ", err)
  7809. msg := geterrmsg(err.Error())
  7810. appG.Response(http.StatusOK, e.ERROR, msg)
  7811. }
  7812. wg.Wait()
  7813. for _, m := range montimeList {
  7814. montime += m
  7815. }
  7816. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  7817. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7818. return
  7819. }
  7820. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  7821. if err != nil {
  7822. logging.Error("GetDataByName err: ", err)
  7823. msg := geterrmsg(err.Error())
  7824. appG.Response(http.StatusOK, e.ERROR, msg)
  7825. } else {
  7826. if sqlnamestr == "getFeedTrgaddressList" {
  7827. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  7828. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  7829. trgaddressList := []string{}
  7830. for _, str := range trgaddressList1 {
  7831. if str != "" {
  7832. trgaddressList = append(trgaddressList, str)
  7833. }
  7834. }
  7835. item["trgaddressList"] = trgaddressList
  7836. }
  7837. }
  7838. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  7839. }
  7840. }
  7841. } else {
  7842. appG.Response(http.StatusOK, e.SUCCESS, nil)
  7843. }
  7844. }
  7845. // func ToggleCcount(c *gin.Context) {
  7846. // appG := app.Gin{C: c}
  7847. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  7848. // fsion := gofasion.NewFasion(string(dataByte))
  7849. // // 0 实际 1 软件
  7850. // status := fsion.Get("status").ValueDefaultInt64(0)
  7851. // pastureId := fsion.Get("pastureId").ValueStr()
  7852. // tx := restful.Engine.NewSession()
  7853. // err := tx.Begin()
  7854. // defer func() {
  7855. // switch {
  7856. // case err != nil:
  7857. // logging.Error("tx.Begin 事务启动失败__error:", err)
  7858. // if tx != nil {
  7859. // tx.Rollback()
  7860. // }
  7861. // default:
  7862. // if tx != nil {
  7863. // err = tx.Commit()
  7864. // }
  7865. // }
  7866. // if tx != nil {
  7867. // tx.Close()
  7868. // }
  7869. // }()
  7870. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  7871. // if err != nil {
  7872. // logs.Error(err)
  7873. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7874. // return
  7875. // }
  7876. // for _, bar := range barList {
  7877. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  7878. // if err != nil {
  7879. // logs.Error(err)
  7880. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7881. // return
  7882. // }
  7883. // if !exist {
  7884. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  7885. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  7886. // if err != nil {
  7887. // logs.Error(err)
  7888. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7889. // return
  7890. // }
  7891. // }
  7892. // }
  7893. // if status == 0 {
  7894. // tx.Exec(`update feedp set ccount = actualcount `)
  7895. // }else{
  7896. // tx.Exec(`update feedp set ccount = softccount `)
  7897. // }
  7898. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  7899. // if err != nil {
  7900. // logs.Error(err)
  7901. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7902. // return
  7903. // }
  7904. // for _, feedpData :=range feedpList{
  7905. // var feedpargs []interface{}
  7906. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  7907. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  7908. // if _, ok := feedpData["ftname"]; ok {
  7909. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  7910. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  7911. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  7912. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  7913. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7914. // } else {
  7915. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  7916. // }
  7917. // if _, ok := feedpData["ptsfname"]; ok {
  7918. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  7919. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  7920. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  7921. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  7922. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  7923. // } else {
  7924. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  7925. // }
  7926. // upFeedpSql += " where barname = ? and pastureid = ? "
  7927. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  7928. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  7929. // if err != nil {
  7930. // logs.Error(err)
  7931. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7932. // return
  7933. // }
  7934. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  7935. // if err != nil {
  7936. // logs.Error(err)
  7937. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7938. // return
  7939. // }
  7940. // if !exist1 {
  7941. // _, 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) `,
  7942. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7943. // if err != nil {
  7944. // logs.Error(err)
  7945. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7946. // return
  7947. // }
  7948. // }
  7949. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  7950. // if err != nil {
  7951. // logs.Error(err)
  7952. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7953. // return
  7954. // }
  7955. // if !exist2 {
  7956. // _, 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) `,
  7957. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7958. // if err != nil {
  7959. // logs.Error(err)
  7960. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7961. // return
  7962. // }
  7963. // }
  7964. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7965. // if err != nil {
  7966. // logs.Error(err)
  7967. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7968. // return
  7969. // }
  7970. // if !exist3 {
  7971. // _, 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) `,
  7972. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7973. // if err != nil {
  7974. // logs.Error(err)
  7975. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7976. // return
  7977. // }
  7978. // }
  7979. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7980. // if err != nil {
  7981. // logs.Error(err)
  7982. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7983. // return
  7984. // }
  7985. // if !exist4 {
  7986. // _, 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) `,
  7987. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7988. // if err != nil {
  7989. // logs.Error(err)
  7990. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7991. // return
  7992. // }
  7993. // }
  7994. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7995. // if err != nil {
  7996. // logs.Error(err)
  7997. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7998. // return
  7999. // }
  8000. // if !exist5 {
  8001. // _, 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) `,
  8002. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  8003. // if err != nil {
  8004. // logs.Error(err)
  8005. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8006. // return
  8007. // }
  8008. // }
  8009. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  8010. // if err != nil {
  8011. // logs.Error(err)
  8012. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8013. // return
  8014. // }
  8015. // if !exist6 {
  8016. // _, 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) `,
  8017. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  8018. // if err != nil {
  8019. // logs.Error(err)
  8020. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8021. // return
  8022. // }
  8023. // }
  8024. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8025. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8026. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8027. // and pastureid = ? and times = ?`
  8028. // var fpdargs1 []interface{}
  8029. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8030. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8031. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8032. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8033. // if err != nil {
  8034. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8035. // return
  8036. // }
  8037. // var fpdargs2 []interface{}
  8038. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8039. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8040. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8041. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8042. // if err != nil {
  8043. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8044. // return
  8045. // }
  8046. // var fpdargs3 []interface{}
  8047. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8048. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8049. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8050. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8051. // if err != nil {
  8052. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8053. // return
  8054. // }
  8055. // var fpdargs4 []interface{}
  8056. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8057. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8058. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8059. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8060. // if err != nil {
  8061. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8062. // return
  8063. // }
  8064. // var fpdargs5 []interface{}
  8065. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8066. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8067. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8068. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8069. // if err != nil {
  8070. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8071. // return
  8072. // }
  8073. // var fpdargs6 []interface{}
  8074. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8075. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8076. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8077. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8078. // if err != nil {
  8079. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8080. // return
  8081. // }
  8082. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8083. // 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()
  8084. // if err != nil {
  8085. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8086. // return
  8087. // }
  8088. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8089. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8090. // upFpdetailList := make([]*upFpdetail, 0)
  8091. // for _, newfpd := range newList {
  8092. // for _, oldfpd := range oldFpdList {
  8093. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8094. // var oldweight, newweight float64
  8095. // if oldfpd["weight"] != nil {
  8096. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8097. // }
  8098. // if newfpd["weight"] != nil {
  8099. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8100. // }
  8101. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8102. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  8103. // Old: oldweight,
  8104. // New: newweight,
  8105. // Times: newfpd["times"].(int64),
  8106. // Ptid: newfpd["ptid"].(int64),
  8107. // Fweight: fweight,
  8108. // Id: oldfpd["id"].(int64),
  8109. // })
  8110. // break
  8111. // }
  8112. // }
  8113. // }
  8114. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  8115. // }
  8116. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  8117. // }
  8118. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  8119. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  8120. if err != nil {
  8121. return err
  8122. }
  8123. for _, item := range feedpList {
  8124. // if item["ftid"].(string) != data["ftid"].(string) {
  8125. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  8126. if err != nil {
  8127. return err
  8128. }
  8129. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8130. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  8131. if err != nil {
  8132. return err
  8133. }
  8134. // }
  8135. }
  8136. return nil
  8137. }
  8138. func PostPlanDatas(c *gin.Context) {
  8139. appG := app.Gin{C: c}
  8140. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8141. fsions := gofasion.NewFasion(string(dataByte))
  8142. logging.Info("PostRJSBDatas err: ", string(dataByte))
  8143. tx := restful.Engine.NewSession()
  8144. err := tx.Begin()
  8145. defer func() {
  8146. switch {
  8147. case err != nil:
  8148. if tx != nil {
  8149. tx.Rollback()
  8150. }
  8151. default:
  8152. if tx != nil {
  8153. err = tx.Commit()
  8154. }
  8155. }
  8156. if tx != nil {
  8157. tx.Close()
  8158. }
  8159. }()
  8160. pastureId := fsions.Get("pastureid").ValueStr()
  8161. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8162. // sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  8163. // sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  8164. // sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  8165. // sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  8166. sql1, p1 := restful.GetSqlByNameDBT("updated1YJXY", tx)
  8167. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJXY", tx)
  8168. sql3, p3 := restful.GetSqlByNameDBT("updated2YJXY", tx)
  8169. for _, parammaps := range fsions.Get("arrList").Array() {
  8170. fmt.Println(parammaps.Json())
  8171. if parammaps.Json() == "null" {
  8172. continue
  8173. }
  8174. // if !fsion.HasKey("arrList") {
  8175. // appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  8176. // return
  8177. // continue
  8178. // }
  8179. // parammaps := fsion.Get("arrList")
  8180. s_params := make([]interface{}, 0)
  8181. // paramslist := strings.Split(p, ",")
  8182. // if len(paramslist) > 0 && p != "" {
  8183. // for _, value := range paramslist {
  8184. // if value == "pastureid" {
  8185. // s_params = append(s_params, pastureId)
  8186. // } else {
  8187. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8188. // }
  8189. // }
  8190. // }
  8191. // _, err = tx.SQL(sql, s_params...).Execute()
  8192. // if err != nil {
  8193. // logging.Error("PostRJSBData err: ", err)
  8194. // msg := geterrmsg(err.Error())
  8195. // appG.Response(http.StatusOK, e.ERROR, msg)
  8196. // return
  8197. // }
  8198. s_params = make([]interface{}, 0)
  8199. paramslist := strings.Split(p1, ",")
  8200. if len(paramslist) > 0 && p1 != "" {
  8201. for _, value := range paramslist {
  8202. // if value == "ID" {
  8203. // id := parammaps.Get("ID").ValueStr()
  8204. // pastureid := parammaps.Get("pastureid").ValueStr()
  8205. // 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
  8206. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8207. // if err != nil {
  8208. // logging.Error("PostRJSBData err: ", err)
  8209. // msg := geterrmsg(err.Error())
  8210. // appG.Response(http.StatusOK, e.ERROR, msg)
  8211. // return
  8212. // }
  8213. // for _, item := range datalist {
  8214. // id = item["id"]
  8215. // }
  8216. // s_params = append(s_params, id)
  8217. // } else {
  8218. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8219. // }
  8220. if value == "pastureid" {
  8221. s_params = append(s_params, pastureId)
  8222. } else {
  8223. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8224. }
  8225. }
  8226. }
  8227. _, err = tx.SQL(sql1, s_params...).Execute()
  8228. if err != nil {
  8229. logging.Error("PostRJSBData1 err: ", err)
  8230. msg := geterrmsg(err.Error())
  8231. appG.Response(http.StatusOK, e.ERROR, msg)
  8232. return
  8233. }
  8234. s_params = make([]interface{}, 0)
  8235. paramslist = strings.Split(p2, ",")
  8236. if len(paramslist) > 0 && p2 != "" {
  8237. for _, value := range paramslist {
  8238. if value == "ID" {
  8239. id := parammaps.Get("ID").ValueStr()
  8240. pastureid := parammaps.Get("pastureid").ValueStr()
  8241. 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
  8242. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  8243. if err != nil {
  8244. logging.Error("PostRJSBData err: ", err)
  8245. msg := geterrmsg(err.Error())
  8246. appG.Response(http.StatusOK, e.ERROR, msg)
  8247. return
  8248. }
  8249. for _, item := range datalist {
  8250. id = item["id"]
  8251. }
  8252. s_params = append(s_params, id)
  8253. } else if value == "pastureid" {
  8254. s_params = append(s_params, pastureId)
  8255. } else {
  8256. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8257. }
  8258. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8259. }
  8260. }
  8261. _, err = tx.SQL(sql2, s_params...).Execute()
  8262. if err != nil {
  8263. logging.Error("PostRJSBData2 err: ", err)
  8264. msg := geterrmsg(err.Error())
  8265. appG.Response(http.StatusOK, e.ERROR, msg)
  8266. return
  8267. }
  8268. s_params = make([]interface{}, 0)
  8269. paramslist = strings.Split(p3, ",")
  8270. if len(paramslist) > 0 && p3 != "" {
  8271. for _, value := range paramslist {
  8272. if value == "pastureid" {
  8273. s_params = append(s_params, pastureId)
  8274. } else {
  8275. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  8276. }
  8277. }
  8278. }
  8279. _, err = tx.SQL(sql3, s_params...).Execute()
  8280. if err != nil {
  8281. logging.Error("PostRJSBData3 err: ", err)
  8282. msg := geterrmsg(err.Error())
  8283. appG.Response(http.StatusOK, e.ERROR, msg)
  8284. return
  8285. }
  8286. }
  8287. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8288. }
  8289. func FpdBatchEdit(c *gin.Context) {
  8290. appG := app.Gin{C: c}
  8291. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8292. fsions := gofasion.NewFasion(string(dataByte))
  8293. barList := fsions.Get("barList").Array()
  8294. pastureid := fsions.Get("pastureId").ValueStr()
  8295. tx := restful.Engine.NewSession()
  8296. defer tx.Close()
  8297. 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
  8298. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8299. if err != nil {
  8300. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8301. return
  8302. }
  8303. for _, barFsions := range barList {
  8304. dataexcel := make(map[string]interface{}, 0)
  8305. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  8306. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  8307. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  8308. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  8309. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  8310. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  8311. continue
  8312. }
  8313. // /*
  8314. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  8315. and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  8316. if err != nil {
  8317. logs.Error(err)
  8318. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8319. return
  8320. }
  8321. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  8322. WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  8323. if err != nil {
  8324. logs.Error(err)
  8325. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  8326. return
  8327. }
  8328. // */
  8329. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  8330. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  8331. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  8332. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  8333. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  8334. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  8335. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  8336. if err != nil {
  8337. logs.Error(err)
  8338. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8339. return
  8340. }
  8341. if !ftexist {
  8342. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  8343. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8344. if err != nil {
  8345. logs.Error(err)
  8346. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8347. return
  8348. }
  8349. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8350. if err != nil {
  8351. logs.Error(err)
  8352. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8353. return
  8354. }
  8355. }
  8356. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  8357. if err != nil {
  8358. logs.Error(err)
  8359. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8360. return
  8361. }
  8362. if !exist {
  8363. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  8364. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  8365. if err != nil {
  8366. logs.Error(err)
  8367. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8368. return
  8369. }
  8370. }
  8371. var feedpargs []interface{}
  8372. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  8373. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  8374. if _, ok := dataexcel["ftname"]; ok {
  8375. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  8376. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  8377. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  8378. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  8379. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8380. } else {
  8381. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  8382. }
  8383. if _, ok := dataexcel["ptsfname"]; ok {
  8384. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  8385. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  8386. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  8387. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  8388. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  8389. } else {
  8390. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  8391. }
  8392. upFeedpSql += " where barname = ? and pastureid = ? "
  8393. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  8394. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  8395. if err != nil {
  8396. logs.Error(err)
  8397. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8398. return
  8399. }
  8400. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  8401. if err != nil {
  8402. logs.Error(err)
  8403. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8404. return
  8405. }
  8406. if !exist1 {
  8407. _, 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) `,
  8408. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8409. if err != nil {
  8410. logs.Error(err)
  8411. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8412. return
  8413. }
  8414. }
  8415. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  8416. if err != nil {
  8417. logs.Error(err)
  8418. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8419. return
  8420. }
  8421. if !exist2 {
  8422. _, 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) `,
  8423. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8424. if err != nil {
  8425. logs.Error(err)
  8426. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8427. return
  8428. }
  8429. }
  8430. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  8431. if err != nil {
  8432. logs.Error(err)
  8433. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8434. return
  8435. }
  8436. if !exist3 {
  8437. _, 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) `,
  8438. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8439. if err != nil {
  8440. logs.Error(err)
  8441. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8442. return
  8443. }
  8444. }
  8445. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  8446. if err != nil {
  8447. logs.Error(err)
  8448. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8449. return
  8450. }
  8451. if !exist4 {
  8452. _, 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) `,
  8453. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8454. if err != nil {
  8455. logs.Error(err)
  8456. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8457. return
  8458. }
  8459. }
  8460. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  8461. if err != nil {
  8462. logs.Error(err)
  8463. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8464. return
  8465. }
  8466. if !exist5 {
  8467. _, 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) `,
  8468. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8469. if err != nil {
  8470. logs.Error(err)
  8471. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8472. return
  8473. }
  8474. }
  8475. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  8476. if err != nil {
  8477. logs.Error(err)
  8478. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8479. return
  8480. }
  8481. if !exist6 {
  8482. _, 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) `,
  8483. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  8484. if err != nil {
  8485. logs.Error(err)
  8486. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8487. return
  8488. }
  8489. }
  8490. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  8491. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  8492. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  8493. and pastureid = ? and times = ?`
  8494. var fpdargs1 []interface{}
  8495. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  8496. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8497. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  8498. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  8499. if err != nil {
  8500. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8501. return
  8502. }
  8503. var fpdargs2 []interface{}
  8504. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  8505. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8506. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  8507. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  8508. if err != nil {
  8509. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8510. return
  8511. }
  8512. var fpdargs3 []interface{}
  8513. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  8514. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8515. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  8516. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  8517. if err != nil {
  8518. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8519. return
  8520. }
  8521. var fpdargs4 []interface{}
  8522. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  8523. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8524. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  8525. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  8526. if err != nil {
  8527. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8528. return
  8529. }
  8530. var fpdargs5 []interface{}
  8531. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  8532. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8533. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  8534. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  8535. if err != nil {
  8536. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8537. return
  8538. }
  8539. var fpdargs6 []interface{}
  8540. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  8541. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  8542. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  8543. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  8544. if err != nil {
  8545. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8546. return
  8547. }
  8548. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  8549. 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()
  8550. if err != nil {
  8551. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  8552. return
  8553. }
  8554. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  8555. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  8556. upFpdetailList := make([]*upFpdetail, 0)
  8557. for _, newfpd := range newList {
  8558. for _, oldfpd := range oldFpdList {
  8559. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  8560. var oldweight, newweight float64
  8561. if oldfpd["weight"] != nil {
  8562. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  8563. }
  8564. if newfpd["weight"] != nil {
  8565. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  8566. }
  8567. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  8568. upFpdetailList = append(upFpdetailList, &upFpdetail{
  8569. Old: oldweight,
  8570. New: newweight,
  8571. Times: newfpd["times"].(int64),
  8572. Ptid: newfpd["ptid"].(int64),
  8573. Fweight: fweight,
  8574. Id: oldfpd["id"].(int64),
  8575. })
  8576. break
  8577. }
  8578. }
  8579. }
  8580. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  8581. }
  8582. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8583. }
  8584. func UdBarSync(c *gin.Context) {
  8585. appG := app.Gin{C: c}
  8586. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8587. fsions := gofasion.NewFasion(string(dataByte))
  8588. pastureid := fsions.Get("pastureId").ValueStr()
  8589. tx := restful.Engine.NewSession()
  8590. defer tx.Close()
  8591. pastureinfo := new(udPastureInfo)
  8592. err := tx.SQL(`select werks from pasture where pastureid = ? `, pastureid).GetFirst(pastureinfo).Error
  8593. if err != nil {
  8594. logs.Error(err)
  8595. return
  8596. }
  8597. // gm.UdBarSync(pastureid, pastureinfo.Werks)
  8598. jpud.UdBarSync(pastureid, pastureinfo.Werks)
  8599. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8600. }
  8601. func UdFeedSync(c *gin.Context) {
  8602. appG := app.Gin{C: c}
  8603. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8604. fsions := gofasion.NewFasion(string(dataByte))
  8605. pastureid := fsions.Get("pastureId").ValueStr()
  8606. tx := restful.Engine.NewSession()
  8607. defer tx.Close()
  8608. pastureinfo := new(udPastureInfo)
  8609. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8610. if err != nil {
  8611. logs.Error(err)
  8612. return
  8613. }
  8614. // gm.UdFeedSync(pastureid, pastureinfo.Werks)
  8615. jpud.UdFeedSync(pastureid, pastureinfo.Werks)
  8616. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8617. }
  8618. func UdFeedtempletPush(c *gin.Context) {
  8619. appG := app.Gin{C: c}
  8620. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8621. fsions := gofasion.NewFasion(string(dataByte))
  8622. pastureid := fsions.Get("pastureId").ValueStr()
  8623. date := fsions.Get("date").ValueStr()
  8624. tx := restful.Engine.NewSession()
  8625. defer tx.Close()
  8626. pastureinfo := new(udPastureInfo)
  8627. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8628. if err != nil {
  8629. logs.Error(err)
  8630. return
  8631. }
  8632. // gm.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8633. jpud.UdFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8634. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8635. }
  8636. func UdUtirPush(c *gin.Context) {
  8637. appG := app.Gin{C: c}
  8638. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8639. fsions := gofasion.NewFasion(string(dataByte))
  8640. pastureid := fsions.Get("pastureId").ValueStr()
  8641. date := fsions.Get("date").ValueStr()
  8642. tx := restful.Engine.NewSession()
  8643. defer tx.Close()
  8644. pastureinfo := new(udPastureInfo)
  8645. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8646. if err != nil {
  8647. logs.Error(err)
  8648. return
  8649. }
  8650. // gm.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8651. jpud.UdUtirPush(pastureid, pastureinfo.Werks, date)
  8652. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8653. }
  8654. func UdBarFeedRemainPush(c *gin.Context) {
  8655. appG := app.Gin{C: c}
  8656. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8657. fsions := gofasion.NewFasion(string(dataByte))
  8658. pastureid := fsions.Get("pastureId").ValueStr()
  8659. date := fsions.Get("date").ValueStr()
  8660. tx := restful.Engine.NewSession()
  8661. defer tx.Close()
  8662. pastureinfo := new(udPastureInfo)
  8663. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8664. if err != nil {
  8665. logs.Error(err)
  8666. return
  8667. }
  8668. // gm.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8669. jpud.UdBarFeedRemainPush(pastureid, pastureinfo.Werks, date)
  8670. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8671. }
  8672. func UdMaterialIssuePush(c *gin.Context) {
  8673. appG := app.Gin{C: c}
  8674. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8675. fsions := gofasion.NewFasion(string(dataByte))
  8676. pastureid := fsions.Get("pastureId").ValueStr()
  8677. date := fsions.Get("date").ValueStr()
  8678. tx := restful.Engine.NewSession()
  8679. defer tx.Close()
  8680. pastureinfo := new(udPastureInfo)
  8681. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8682. if err != nil {
  8683. logs.Error(err)
  8684. return
  8685. }
  8686. // gm.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8687. jpud.UdMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8688. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8689. }
  8690. //搅拌
  8691. func YmyUtirPush(c *gin.Context) {
  8692. appG := app.Gin{C: c}
  8693. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8694. fsions := gofasion.NewFasion(string(dataByte))
  8695. pastureid := fsions.Get("pastureId").ValueStr()
  8696. date := fsions.Get("date").ValueStr()
  8697. tx := restful.Engine.NewSession()
  8698. defer tx.Close()
  8699. pastureinfo := new(udPastureInfo)
  8700. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8701. if err != nil {
  8702. logs.Error(err)
  8703. return
  8704. }
  8705. ymy.YmyUtirPush(pastureid, pastureinfo.Werks, date)
  8706. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8707. }
  8708. //撒料
  8709. func YmyMaterialIssuePush(c *gin.Context) {
  8710. appG := app.Gin{C: c}
  8711. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8712. fsions := gofasion.NewFasion(string(dataByte))
  8713. pastureid := fsions.Get("pastureId").ValueStr()
  8714. date := fsions.Get("date").ValueStr()
  8715. tx := restful.Engine.NewSession()
  8716. defer tx.Close()
  8717. pastureinfo := new(udPastureInfo)
  8718. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8719. if err != nil {
  8720. logs.Error(err)
  8721. return
  8722. }
  8723. ymy.YmyMaterialIssuePush(pastureid, pastureinfo.Werks, date)
  8724. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8725. }
  8726. func YmyFeedtempletPush(c *gin.Context) {
  8727. appG := app.Gin{C: c}
  8728. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8729. fsions := gofasion.NewFasion(string(dataByte))
  8730. pastureid := fsions.Get("pastureId").ValueStr()
  8731. date := fsions.Get("date").ValueStr()
  8732. tx := restful.Engine.NewSession()
  8733. defer tx.Close()
  8734. pastureinfo := new(udPastureInfo)
  8735. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8736. if err != nil {
  8737. logs.Error(err)
  8738. return
  8739. }
  8740. ymy.YmyFeedtempletPush(pastureid, pastureinfo.Werks, date)
  8741. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8742. }
  8743. //饲料
  8744. func YmySyncFeed(c *gin.Context) {
  8745. appG := app.Gin{C: c}
  8746. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8747. fsions := gofasion.NewFasion(string(dataByte))
  8748. pastureid := fsions.Get("pastureId").ValueStr()
  8749. // date := fsions.Get("date").ValueStr()
  8750. tx := restful.Engine.NewSession()
  8751. defer tx.Close()
  8752. ymy.YmySyncFeed(pastureid)
  8753. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8754. }
  8755. // 栏舍
  8756. func YmySyncBar(c *gin.Context) {
  8757. appG := app.Gin{C: c}
  8758. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8759. fsions := gofasion.NewFasion(string(dataByte))
  8760. pastureid := fsions.Get("pastureId").ValueStr()
  8761. // date := fsions.Get("date").ValueStr()
  8762. tx := restful.Engine.NewSession()
  8763. defer tx.Close()
  8764. pastureinfo := new(udPastureInfo)
  8765. err := tx.SQL(`select werks from pasture where pastureid = ?`, pastureid).GetFirst(pastureinfo).Error
  8766. if err != nil {
  8767. logs.Error(err)
  8768. return
  8769. }
  8770. ymy.YmySyncBar(pastureinfo.Werks, pastureid)
  8771. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8772. }
  8773. func DelFeedTemplet(c *gin.Context) {
  8774. appG := app.Gin{C: c}
  8775. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  8776. fsions := gofasion.NewFasion(string(dataByte))
  8777. ftId := fsions.Get("ftId").ValueStr()
  8778. // userId := fsions.Get("userId").ValueStr()
  8779. tx := restful.Engine.NewSession()
  8780. defer tx.Close()
  8781. _, err := tx.Exec(` delete from feedtemplet where id = ? `, ftId)
  8782. if err != nil {
  8783. logs.Error(err)
  8784. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8785. return
  8786. }
  8787. /*
  8788. _, err := tx.Exec(` update feedtemplet set enable = 1 , isdelete = 1 where id = ? `, ftId)
  8789. if err != nil {
  8790. logs.Error(err)
  8791. appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8792. return
  8793. }
  8794. */
  8795. _, err = tx.Exec(` update feedp set ftid = 0 , ftname = '',feedweight = 0,ftweight = 0 where ftid = ? `, ftId)
  8796. if err != nil {
  8797. logs.Error(err)
  8798. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8799. return
  8800. }
  8801. _, err = tx.Exec(` update fpdetail set weight = 0 ,ptid = 0,ptuse= 0 where ptid = ? `, ftId)
  8802. if err != nil {
  8803. logs.Error(err)
  8804. appG.Response(http.StatusOK, e.ERROR, errors.New("删除栏舍配方失败"))
  8805. return
  8806. }
  8807. count, _ := tx.SQL(`select count(1) from lpplan where ftid = ? `, ftId).Count()
  8808. if count > 0 {
  8809. _, err = tx.Exec(` delete from lpplandtl1 where lppid in(select id from lpplan where ftid = ? ) `, ftId)
  8810. if err != nil {
  8811. logs.Error(err)
  8812. appG.Response(http.StatusOK, e.ERROR, errors.New("删除子计划失败"))
  8813. return
  8814. }
  8815. }
  8816. _, err = tx.Exec(` delete from lpplan where ftid = ? `, ftId)
  8817. if err != nil {
  8818. logs.Error(err)
  8819. appG.Response(http.StatusOK, e.ERROR, errors.New("删除计划失败"))
  8820. return
  8821. }
  8822. // var barIdStr []string
  8823. // for _, bar := range barIdList {
  8824. // barIdStr = append(barIdStr, bar["barid"])
  8825. // }
  8826. // if len(barIdStr) > 0 {
  8827. // newFpdDataList, err := tx.Table("fpdetail").Where(`barid in(?)`, barIdStr).Query().List()
  8828. // if err != nil {
  8829. // logs.Error(err)
  8830. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8831. // return
  8832. // }
  8833. // newFeedpList, err := tx.Table("feedp").Where(`barid in(?)`, barIdStr).Query().List()
  8834. // if err != nil {
  8835. // logs.Error(err)
  8836. // appG.Response(http.StatusOK, e.ERROR, errors.New("删除失败!!!"))
  8837. // return
  8838. // }
  8839. // now := time.Now()
  8840. // for _, newFpd := range newFpdDataList {
  8841. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  8842. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  8843. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  8844. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, userId).Execute()
  8845. // if err != nil {
  8846. // logs.Error(err)
  8847. // appG.Response(http.StatusOK, e.ERROR, false)
  8848. // return
  8849. // }
  8850. // }
  8851. // for _, newFeedp := range newFeedpList {
  8852. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  8853. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  8854. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  8855. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  8856. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  8857. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  8858. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  8859. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, userId).Execute()
  8860. // if err != nil {
  8861. // logs.Error(err)
  8862. // appG.Response(http.StatusOK, e.ERROR, false)
  8863. // return
  8864. // }
  8865. // }
  8866. // }
  8867. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  8868. }
  8869. func checkPlan(tx *xorm.Session, fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, number int) {
  8870. sysOpt := new(models.SysOpt)
  8871. tx.Table("sysopt").Where("inforname = ?", "separateVehicles").Get(sysOpt)
  8872. lweight := 0.0
  8873. if sysOpt.InforValue != "" {
  8874. lweight, _ = strconv.ParseFloat(sysOpt.InforValue, 64)
  8875. } else if sysOpt.InforValue == "" || sysOpt.InforValue == "0" {
  8876. return
  8877. }
  8878. fmt.Println(sysOpt)
  8879. data := fasion["parammaps"].(map[string]interface{})
  8880. // plancount, err := tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype in(2) ").Count()
  8881. downloadedplanList := make([]*models.DownloadedPlan, 0)
  8882. tx.Table("downloadedplan").Where(" mydate = ? ", data["startTime"]).Where(" havebutton = 0 ").Where(" lpplantype = 2 ").Find(&downloadedplanList)
  8883. fmt.Println(lweight)
  8884. for _, downloadedplan := range downloadedplanList {
  8885. if downloadedplan.LWeight < lweight {
  8886. break
  8887. }
  8888. downloadplandtl1List := make([]*models.DownloadPlanDtl1, 0)
  8889. downloadplandtl1ExecList := make([]*models.DownloadPlanDtl1Exec, 0)
  8890. downloadplandtl2List := make([]*models.DownloadPlanDtl2, 0)
  8891. tx.Table("downloadplandtl1").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1List)
  8892. tx.Table("downloadplandtl2").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl2List)
  8893. tx.Table("downloadplandtl1_exec").Where(" pid = ? ", downloadedplan.ID).Find(&downloadplandtl1ExecList)
  8894. lweightCount := math.Floor(downloadedplan.LWeight / lweight)
  8895. for i := 0; i <= int(lweightCount); i++ {
  8896. if i == 0 {
  8897. tx.Exec(` update downloadedplan set lweight = ? where id = ? `, lweight, downloadedplan.ID)
  8898. for _, downloadplandtl1 := range downloadplandtl1List {
  8899. tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl1.LWeight, downloadplandtl1.ID)
  8900. }
  8901. for _, downloadplandtl2 := range downloadplandtl2List {
  8902. tx.Exec(` update downloadplandtl2 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8903. }
  8904. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  8905. tx.Exec(` update downloadplandtl1_exec set lweight = ? where id = ? `, lweight/downloadedplan.LWeight*downloadplandtl2.LWeight, downloadplandtl2.ID)
  8906. }
  8907. // && downloadedplan.LWeight >lweight
  8908. } else if i < int(lweightCount) {
  8909. parts := strings.Split(downloadedplan.ProjName, ".")
  8910. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  8911. data := &models.DownloadedPlan{
  8912. PastureID: downloadedplan.PastureID,
  8913. MyDate: downloadedplan.MyDate,
  8914. ProjName: strings.Join(parts, "."),
  8915. DataCaptureNo: downloadedplan.DataCaptureNo,
  8916. TmrID: downloadedplan.TmrID,
  8917. TmrtName: downloadedplan.TmrtName,
  8918. HaveButton: downloadedplan.HaveButton,
  8919. InButtonType: downloadedplan.InButtonType,
  8920. PlanTime: downloadedplan.PlanTime,
  8921. InTime: downloadedplan.InTime,
  8922. CompletedTime: downloadedplan.CompletedTime,
  8923. IsCompleted: downloadedplan.IsCompleted,
  8924. LpPlanType: downloadedplan.LpPlanType,
  8925. Times: downloadedplan.Times,
  8926. Sort: downloadedplan.Sort,
  8927. Remark: downloadedplan.Remark,
  8928. ItemNum: downloadedplan.ItemNum,
  8929. OutItems: downloadedplan.OutItems,
  8930. FeedPName: downloadedplan.FeedPName,
  8931. FeedPCount: downloadedplan.FeedPCount,
  8932. Pid: downloadedplan.Pid,
  8933. TempID: downloadedplan.TempID,
  8934. TempletName: downloadedplan.TempletName,
  8935. PtsTempID: downloadedplan.PtsTempID,
  8936. PtsTempletName: downloadedplan.PtsTempletName,
  8937. ThoWeight: downloadedplan.ThoWeight,
  8938. FpWeight: downloadedplan.FpWeight,
  8939. LWeight: lweight,
  8940. IWeight: downloadedplan.IWeight,
  8941. OWeight: downloadedplan.OWeight,
  8942. TVersion: downloadedplan.TVersion,
  8943. PtVersion: downloadedplan.PtVersion,
  8944. Enable: downloadedplan.Enable,
  8945. IsUse: downloadedplan.IsUse,
  8946. OldTmrID: downloadedplan.OldTmrID,
  8947. DriverID: downloadedplan.DriverID,
  8948. Artificial: downloadedplan.Artificial,
  8949. }
  8950. _, err := tx.Insert(data)
  8951. fmt.Println(data, err)
  8952. for _, downloadplandtl1 := range downloadplandtl1List {
  8953. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8954. d1 := &models.DownloadPlanDtl1{
  8955. PastureID: downloadplandtl1.PastureID,
  8956. Pid: data.ID,
  8957. Flpid: downloadplandtl1.Flpid,
  8958. Fid: downloadplandtl1.Fid,
  8959. LWeight: lweight / downloadedplan.LWeight * downloadplandtl1.LWeight,
  8960. Sort: downloadplandtl1.Sort,
  8961. ButtonType: downloadplandtl1.ButtonType,
  8962. OptDevice: downloadplandtl1.OptDevice,
  8963. FeedCode: downloadplandtl1.FeedCode,
  8964. FName: downloadplandtl1.FName,
  8965. FeedSort: downloadplandtl1.FeedSort,
  8966. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  8967. StirDelay: downloadplandtl1.StirDelay,
  8968. FWeight: downloadplandtl1.FWeight,
  8969. TmrLoadName: downloadplandtl1.TmrLoadName,
  8970. DryFeed: downloadplandtl1.DryFeed,
  8971. PriceFeed: downloadplandtl1.PriceFeed,
  8972. OutWeight: downloadplandtl1.OutWeight,
  8973. ErrRatio: downloadplandtl1.ErrRatio,
  8974. Date: downloadplandtl1.Date,
  8975. ButtonSucc: downloadplandtl1.ButtonSucc,
  8976. Type: downloadplandtl1.Type,
  8977. Deviation: downloadplandtl1.Deviation,
  8978. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  8979. }
  8980. tx.Insert(d1)
  8981. }
  8982. for _, downloadplandtl2 := range downloadplandtl2List {
  8983. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  8984. d2 := &models.DownloadPlanDtl2{
  8985. PastureID: downloadplandtl2.PastureID,
  8986. Pid: data.ID,
  8987. Flpid: downloadplandtl2.Flpid,
  8988. Fbarid: downloadplandtl2.Fbarid,
  8989. FName: downloadplandtl2.FName,
  8990. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8991. LWeightHis: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  8992. RemainLeftW: downloadplandtl2.RemainLeftW,
  8993. AllowRW: downloadplandtl2.AllowRW,
  8994. Sort: downloadplandtl2.Sort,
  8995. HaveButton: downloadplandtl2.HaveButton,
  8996. BeginTag: downloadplandtl2.BeginTag,
  8997. EndTag: downloadplandtl2.EndTag,
  8998. ButtonType: downloadplandtl2.ButtonType,
  8999. OptDevice: downloadplandtl2.OptDevice,
  9000. CowCount: downloadplandtl2.CowCount,
  9001. CowClassID: downloadplandtl2.CowClassID,
  9002. CowClassName: downloadplandtl2.CowClassName,
  9003. BigCowName: downloadplandtl2.BigCowName,
  9004. PWeight: downloadplandtl2.PWeight,
  9005. CCountRatio: downloadplandtl2.CCountRatio,
  9006. SumRTime: downloadplandtl2.SumRTime,
  9007. FeedTempletID: downloadplandtl2.FeedTempletID,
  9008. FeedTempletName: downloadplandtl2.FeedTempletName,
  9009. DryWeight: downloadplandtl2.DryWeight,
  9010. SumWeight: downloadplandtl2.SumWeight,
  9011. PriceWeight: downloadplandtl2.PriceWeight,
  9012. // ProcessTime :downloadplandtl2.ProcessTime ,
  9013. Fpid: downloadplandtl2.Fpid,
  9014. UseInBarType: downloadplandtl2.UseInBarType,
  9015. Date: downloadplandtl2.Date,
  9016. AllowRatio: downloadplandtl2.AllowRatio,
  9017. ErrRatio: downloadplandtl2.ErrRatio,
  9018. ButtonSucc: downloadplandtl2.ButtonSucc,
  9019. Type: downloadplandtl2.Type,
  9020. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9021. XxwBarCode: downloadplandtl2.XxwBarCode,
  9022. }
  9023. _, err := tx.Insert(d2)
  9024. fmt.Println(err)
  9025. }
  9026. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9027. d2 := &models.DownloadPlanDtl1Exec{
  9028. PastureID: downloadplandtl2.PastureID,
  9029. Pid: data.ID,
  9030. Flpid: downloadplandtl2.Flpid,
  9031. LWeight: lweight / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9032. HaveButton: downloadplandtl2.HaveButton,
  9033. ButtonType: downloadplandtl2.ButtonType,
  9034. OptDevice: downloadplandtl2.OptDevice,
  9035. Sort: downloadplandtl2.Sort,
  9036. FName: downloadplandtl2.FName,
  9037. FCount: downloadplandtl2.FCount,
  9038. TmrLoadName: downloadplandtl2.TmrLoadName,
  9039. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9040. StirDelay: downloadplandtl2.StirDelay,
  9041. ButtonSucc: downloadplandtl2.ButtonSucc,
  9042. ErrRatio: downloadplandtl2.ErrRatio,
  9043. Date: downloadplandtl2.Date,
  9044. Type: downloadplandtl2.Type,
  9045. Deviation: downloadplandtl2.Deviation,
  9046. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9047. }
  9048. _, err := tx.Insert(d2)
  9049. fmt.Println(err)
  9050. }
  9051. } else {
  9052. parts := strings.Split(downloadedplan.ProjName, ".")
  9053. parts[len(parts)-1] = fmt.Sprintf("%d", i+1)
  9054. if downloadedplan.LWeight-float64(i)*lweight <= 0 {
  9055. continue
  9056. }
  9057. data := &models.DownloadedPlan{
  9058. PastureID: downloadedplan.PastureID,
  9059. MyDate: downloadedplan.MyDate,
  9060. ProjName: strings.Join(parts, "."),
  9061. DataCaptureNo: downloadedplan.DataCaptureNo,
  9062. TmrID: downloadedplan.TmrID,
  9063. TmrtName: downloadedplan.TmrtName,
  9064. HaveButton: downloadedplan.HaveButton,
  9065. InButtonType: downloadedplan.InButtonType,
  9066. PlanTime: downloadedplan.PlanTime,
  9067. InTime: downloadedplan.InTime,
  9068. CompletedTime: downloadedplan.CompletedTime,
  9069. IsCompleted: downloadedplan.IsCompleted,
  9070. LpPlanType: downloadedplan.LpPlanType,
  9071. Times: downloadedplan.Times,
  9072. Sort: downloadedplan.Sort,
  9073. Remark: downloadedplan.Remark,
  9074. ItemNum: downloadedplan.ItemNum,
  9075. OutItems: downloadedplan.OutItems,
  9076. FeedPName: downloadedplan.FeedPName,
  9077. FeedPCount: downloadedplan.FeedPCount,
  9078. Pid: downloadedplan.Pid,
  9079. TempID: downloadedplan.TempID,
  9080. TempletName: downloadedplan.TempletName,
  9081. PtsTempID: downloadedplan.PtsTempID,
  9082. PtsTempletName: downloadedplan.PtsTempletName,
  9083. ThoWeight: downloadedplan.ThoWeight,
  9084. FpWeight: downloadedplan.FpWeight,
  9085. LWeight: downloadedplan.LWeight - float64(i)*lweight,
  9086. IWeight: downloadedplan.IWeight,
  9087. OWeight: downloadedplan.OWeight,
  9088. TVersion: downloadedplan.TVersion,
  9089. PtVersion: downloadedplan.PtVersion,
  9090. Enable: downloadedplan.Enable,
  9091. IsUse: downloadedplan.IsUse,
  9092. OldTmrID: downloadedplan.OldTmrID,
  9093. DriverID: downloadedplan.DriverID,
  9094. Artificial: downloadedplan.Artificial,
  9095. }
  9096. _, err := tx.Insert(data)
  9097. fmt.Println(data, err)
  9098. for _, downloadplandtl1 := range downloadplandtl1List {
  9099. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9100. d1 := &models.DownloadPlanDtl1{
  9101. PastureID: downloadplandtl1.PastureID,
  9102. Pid: data.ID,
  9103. Flpid: downloadplandtl1.Flpid,
  9104. Fid: downloadplandtl1.Fid,
  9105. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl1.LWeight,
  9106. Sort: downloadplandtl1.Sort,
  9107. ButtonType: downloadplandtl1.ButtonType,
  9108. OptDevice: downloadplandtl1.OptDevice,
  9109. FeedCode: downloadplandtl1.FeedCode,
  9110. FName: downloadplandtl1.FName,
  9111. FeedSort: downloadplandtl1.FeedSort,
  9112. FeedAllowRatio: downloadplandtl1.FeedAllowRatio,
  9113. StirDelay: downloadplandtl1.StirDelay,
  9114. FWeight: downloadplandtl1.FWeight,
  9115. TmrLoadName: downloadplandtl1.TmrLoadName,
  9116. DryFeed: downloadplandtl1.DryFeed,
  9117. PriceFeed: downloadplandtl1.PriceFeed,
  9118. OutWeight: downloadplandtl1.OutWeight,
  9119. ErrRatio: downloadplandtl1.ErrRatio,
  9120. Date: downloadplandtl1.Date,
  9121. ButtonSucc: downloadplandtl1.ButtonSucc,
  9122. Type: downloadplandtl1.Type,
  9123. Deviation: downloadplandtl1.Deviation,
  9124. XxwFeedCode: downloadplandtl1.XxwFeedCode,
  9125. }
  9126. tx.Insert(d1)
  9127. }
  9128. for _, downloadplandtl2 := range downloadplandtl2List {
  9129. // tx.Exec(` update downloadplandtl1 set lweight = ? where id = ? `, lweight/downloadedplan.LWeight * downloadplandtl1.LWeight, downloadplandtl1.ID)
  9130. d2 := &models.DownloadPlanDtl2{
  9131. PastureID: downloadplandtl2.PastureID,
  9132. Pid: data.ID,
  9133. Flpid: downloadplandtl2.Flpid,
  9134. Fbarid: downloadplandtl2.Fbarid,
  9135. FName: downloadplandtl2.FName,
  9136. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9137. LWeightHis: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9138. RemainLeftW: downloadplandtl2.RemainLeftW,
  9139. AllowRW: downloadplandtl2.AllowRW,
  9140. Sort: downloadplandtl2.Sort,
  9141. HaveButton: downloadplandtl2.HaveButton,
  9142. BeginTag: downloadplandtl2.BeginTag,
  9143. EndTag: downloadplandtl2.EndTag,
  9144. ButtonType: downloadplandtl2.ButtonType,
  9145. OptDevice: downloadplandtl2.OptDevice,
  9146. CowCount: downloadplandtl2.CowCount,
  9147. CowClassID: downloadplandtl2.CowClassID,
  9148. CowClassName: downloadplandtl2.CowClassName,
  9149. BigCowName: downloadplandtl2.BigCowName,
  9150. PWeight: downloadplandtl2.PWeight,
  9151. CCountRatio: downloadplandtl2.CCountRatio,
  9152. SumRTime: downloadplandtl2.SumRTime,
  9153. FeedTempletID: downloadplandtl2.FeedTempletID,
  9154. FeedTempletName: downloadplandtl2.FeedTempletName,
  9155. DryWeight: downloadplandtl2.DryWeight,
  9156. SumWeight: downloadplandtl2.SumWeight,
  9157. PriceWeight: downloadplandtl2.PriceWeight,
  9158. // ProcessTime :downloadplandtl2.ProcessTime ,
  9159. Fpid: downloadplandtl2.Fpid,
  9160. UseInBarType: downloadplandtl2.UseInBarType,
  9161. Date: downloadplandtl2.Date,
  9162. AllowRatio: downloadplandtl2.AllowRatio,
  9163. ErrRatio: downloadplandtl2.ErrRatio,
  9164. ButtonSucc: downloadplandtl2.ButtonSucc,
  9165. Type: downloadplandtl2.Type,
  9166. XxwTempletCode: downloadplandtl2.XxwTempletCode,
  9167. XxwBarCode: downloadplandtl2.XxwBarCode,
  9168. }
  9169. _, err := tx.Insert(d2)
  9170. fmt.Println(err)
  9171. }
  9172. for _, downloadplandtl2 := range downloadplandtl1ExecList {
  9173. d2 := &models.DownloadPlanDtl1Exec{
  9174. PastureID: downloadplandtl2.PastureID,
  9175. Pid: data.ID,
  9176. Flpid: downloadplandtl2.Flpid,
  9177. LWeight: (downloadedplan.LWeight - float64(i)*lweight) / downloadedplan.LWeight * downloadplandtl2.LWeight,
  9178. HaveButton: downloadplandtl2.HaveButton,
  9179. ButtonType: downloadplandtl2.ButtonType,
  9180. OptDevice: downloadplandtl2.OptDevice,
  9181. Sort: downloadplandtl2.Sort,
  9182. FName: downloadplandtl2.FName,
  9183. FCount: downloadplandtl2.FCount,
  9184. TmrLoadName: downloadplandtl2.TmrLoadName,
  9185. FeedAllowRatio: downloadplandtl2.FeedAllowRatio,
  9186. StirDelay: downloadplandtl2.StirDelay,
  9187. ButtonSucc: downloadplandtl2.ButtonSucc,
  9188. ErrRatio: downloadplandtl2.ErrRatio,
  9189. Date: downloadplandtl2.Date,
  9190. Type: downloadplandtl2.Type,
  9191. Deviation: downloadplandtl2.Deviation,
  9192. XxwFeedCode: downloadplandtl2.XxwFeedCode,
  9193. }
  9194. fmt.Println(d2)
  9195. _, err := tx.Insert(d2)
  9196. fmt.Println(err)
  9197. }
  9198. }
  9199. }
  9200. }
  9201. downloadedplanSortList := make([]*models.DownloadedPlan, 0)
  9202. tx.SQL(`SELECT * FROM downloadedplan WHERE mydate = ? ORDER BY projname`, data["startTime"]).Find(&downloadedplanSortList)
  9203. for i, d := range downloadedplanSortList {
  9204. tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, d.ID)
  9205. }
  9206. }
  9207. func EditPlanSort(c *gin.Context) {
  9208. appG := app.Gin{C: c}
  9209. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9210. fsions := gofasion.NewFasion(string(dataByte))
  9211. planIdStr := fsions.Get("planId").ValueStr()
  9212. mydate := fsions.Get("mydate").ValueStr()
  9213. sort := fsions.Get("sort").ValueStr()
  9214. tx := restful.Engine.NewSession()
  9215. defer tx.Close()
  9216. tx.Begin()
  9217. type downloadedplan struct {
  9218. Id int64 `xorm:"id"`
  9219. Sort int `xorm:"sort"`
  9220. Pid int64 `xorm:"pid"`
  9221. }
  9222. planInfo := new(downloadedplan)
  9223. err := tx.SQL(`select d.id,d.sort,d.pid from downloadedplan d where d.id = ? `, planIdStr).GetFirst(planInfo).Error
  9224. if err != nil {
  9225. logs.Error(err)
  9226. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9227. tx.Rollback()
  9228. return
  9229. }
  9230. sort1, _ := strconv.Atoi(sort)
  9231. if sort1 == planInfo.Sort {
  9232. appG.Response(http.StatusOK, e.ERROR, "计划顺序一致修改失败!")
  9233. tx.Rollback()
  9234. return
  9235. }
  9236. 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()
  9237. if err != nil {
  9238. logs.Error(err)
  9239. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9240. tx.Rollback()
  9241. return
  9242. }
  9243. if count1 == 0 {
  9244. tx.Rollback()
  9245. logs.Error(err)
  9246. appG.Response(http.StatusOK, e.ERROR, "您所排序的数值不存在!")
  9247. return
  9248. }
  9249. 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()
  9250. if err != nil {
  9251. logs.Error(err)
  9252. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9253. tx.Rollback()
  9254. return
  9255. }
  9256. if count > 0 {
  9257. tx.Rollback()
  9258. logs.Error(err)
  9259. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败,该计划已执行!")
  9260. return
  9261. }
  9262. if planInfo.Sort > sort1 {
  9263. 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()
  9264. if err != nil {
  9265. logs.Error(err)
  9266. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9267. tx.Rollback()
  9268. return
  9269. }
  9270. var minSort, pidCount int
  9271. for _, sort := range minSortList {
  9272. minSort, _ = strconv.Atoi(sort["sort"])
  9273. }
  9274. planList := make([]*downloadedplan, 0)
  9275. 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)
  9276. if err != nil {
  9277. logs.Error(err)
  9278. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9279. tx.Rollback()
  9280. return
  9281. }
  9282. planPid := planInfo.Pid
  9283. planList1 := make([]*downloadedplan, 0)
  9284. planList2 := make([]*downloadedplan, 0)
  9285. for _, plan := range planList {
  9286. if plan.Pid == planPid {
  9287. pidCount++
  9288. planList1 = append(planList1, plan)
  9289. } else {
  9290. planList2 = append(planList2, plan)
  9291. }
  9292. }
  9293. planList1 = append(planList1, planList2...)
  9294. for i, plan := range planList1 {
  9295. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, minSort+i, plan.Id)
  9296. if err != nil {
  9297. logs.Error(err)
  9298. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9299. tx.Rollback()
  9300. return
  9301. }
  9302. }
  9303. } else {
  9304. 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()
  9305. if err != nil {
  9306. logs.Error(err)
  9307. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9308. tx.Rollback()
  9309. return
  9310. }
  9311. var maxSort int
  9312. for _, sort := range maxSortList {
  9313. maxSort, _ = strconv.Atoi(sort["sort"])
  9314. }
  9315. planList := make([]*downloadedplan, 0)
  9316. 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)
  9317. if err != nil {
  9318. logs.Error(err)
  9319. appG.Response(http.StatusOK, e.ERROR, "调整计划顺序失败!"+err.Error())
  9320. tx.Rollback()
  9321. return
  9322. }
  9323. planPid := planInfo.Pid
  9324. planList1 := make([]*downloadedplan, 0)
  9325. planList2 := make([]*downloadedplan, 0)
  9326. for _, plan := range planList {
  9327. if plan.Pid == planPid {
  9328. // pidCount++
  9329. planList1 = append(planList1, plan)
  9330. } else {
  9331. planList2 = append(planList2, plan)
  9332. }
  9333. }
  9334. planList2 = append(planList2, planList1...)
  9335. for i, plan := range planList2 {
  9336. _, err := tx.Exec(` update downloadedplan set sort = ? where id = ? `, i+1, plan.Id)
  9337. if err != nil {
  9338. logs.Error(err)
  9339. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9340. tx.Rollback()
  9341. return
  9342. }
  9343. }
  9344. }
  9345. err = tx.Commit()
  9346. if err != nil {
  9347. logs.Error(err)
  9348. appG.Response(http.StatusOK, e.ERROR, "修改计划顺序失败!"+err.Error())
  9349. tx.Rollback()
  9350. return
  9351. }
  9352. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9353. }
  9354. func EditDownloadedplanArtificial(c *gin.Context) {
  9355. appG := app.Gin{C: c}
  9356. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9357. fsions := gofasion.NewFasion(string(dataByte))
  9358. planIdStr := fsions.Get("planId").ValueStr()
  9359. tx := restful.Engine.NewSession()
  9360. defer tx.Close()
  9361. tx.Begin()
  9362. planIdList := strings.Split(planIdStr, ",")
  9363. for _, planId := range planIdList {
  9364. _, err := tx.Exec(` update downloadedplan set artificial = 1 ,havebutton = 1,iscompleted = 1 where id = ? `, planId)
  9365. if err != nil {
  9366. logs.Error(err)
  9367. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9368. tx.Rollback()
  9369. return
  9370. }
  9371. }
  9372. err := tx.Commit()
  9373. if err != nil {
  9374. logs.Error(err)
  9375. appG.Response(http.StatusOK, e.ERROR, "修改计划状态失败!"+err.Error())
  9376. tx.Rollback()
  9377. return
  9378. }
  9379. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  9380. }
  9381. type PlanRFID struct {
  9382. RFID string `json:"RFID"`
  9383. Lweight string `json:"lweight"`
  9384. Gear string `json:"gear"`
  9385. Speed string `json:"speed"`
  9386. }
  9387. func GetPlanRFID(c *gin.Context) {
  9388. appG := app.Gin{C: c}
  9389. RFIDStr := c.Query("RFID")
  9390. planRFIDList := make([]*PlanRFID, 0)
  9391. planRFIDList = append(planRFIDList, &PlanRFID{
  9392. RFID: RFIDStr,
  9393. Lweight: "1411.1",
  9394. Gear: "1",
  9395. Speed: "10",
  9396. })
  9397. planRFIDList = append(planRFIDList, &PlanRFID{
  9398. RFID: RFIDStr,
  9399. Lweight: "1322.1",
  9400. Gear: "1",
  9401. Speed: "10",
  9402. })
  9403. planRFIDList = append(planRFIDList, &PlanRFID{
  9404. RFID: RFIDStr,
  9405. Lweight: "1904.1",
  9406. Gear: "1",
  9407. Speed: "10",
  9408. })
  9409. planRFIDList = append(planRFIDList, &PlanRFID{
  9410. RFID: RFIDStr,
  9411. Lweight: "1870.1",
  9412. Gear: "1",
  9413. Speed: "10",
  9414. })
  9415. planRFIDList = append(planRFIDList, &PlanRFID{
  9416. RFID: RFIDStr,
  9417. Lweight: "2041.1",
  9418. Gear: "1",
  9419. Speed: "10",
  9420. })
  9421. appG.Response(http.StatusOK, e.SUCCESS, planRFIDList)
  9422. }
  9423. type tmrEquipmentMuster struct {
  9424. A string
  9425. N string
  9426. }
  9427. func GetTmrEquipmentMuster(c *gin.Context) {
  9428. appG := app.Gin{C: c}
  9429. id := c.Query("id")
  9430. tx := restful.Engine.NewSession()
  9431. defer tx.Close()
  9432. dataList, err := tx.SQL(` select * from tmr_equipment_muster where pid = ? `, id).QueryString()
  9433. if err != nil {
  9434. logs.Error(err)
  9435. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9436. return
  9437. }
  9438. tmrEquipmentMusterList := make([]*tmrEquipmentMuster, 0)
  9439. for _, data := range dataList {
  9440. json.Unmarshal([]byte(data["gptjson"]), &tmrEquipmentMusterList)
  9441. for _, g := range tmrEquipmentMusterList {
  9442. a, _ := strconv.ParseFloat(g.A, 64)
  9443. n, _ := strconv.ParseFloat(g.N, 64)
  9444. a1, n1 := ddmmtoddd(a, n)
  9445. g.A = fmt.Sprintf("%f", n1)
  9446. g.N = fmt.Sprintf("%f", a1)
  9447. }
  9448. }
  9449. appG.Response(http.StatusOK, e.SUCCESS, tmrEquipmentMusterList)
  9450. }
  9451. func ddmmtoddd(lng, lat float64) (float64, float64) {
  9452. lngDegree := fmt.Sprintf("%f", lng/100)
  9453. lngDegreefloat, _ := strconv.ParseFloat(strings.Split(lngDegree, ".")[1], 64)
  9454. lngDegreeInt := int(lngDegreefloat * 1000000)
  9455. dd := lngDegreeInt / 100 * 100 / 60
  9456. fmt.Println(dd)
  9457. lngStr := strings.Split(lngDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", lngDegreeInt/100*100/60), ".", "", 0)
  9458. latDegree := fmt.Sprintf("%f", lat/100)
  9459. // latDegreeInt, _ := strconv.ParseInt(strings.Split(latDegree, ".")[1], 10, 64)
  9460. latDegreefloat, _ := strconv.ParseFloat(strings.Split(latDegree, ".")[1], 64)
  9461. latDegreeInt := int(latDegreefloat * 1000000)
  9462. latStr := strings.Split(latDegree, ".")[0] + "." + strings.Replace(fmt.Sprintf("%d", latDegreeInt/100*100/60), ".", "", 0)
  9463. a, _ := strconv.ParseFloat(lngStr, 64)
  9464. b, _ := strconv.ParseFloat(latStr, 64)
  9465. return coordtransform.WGS84toGCJ02(b, a)
  9466. }
  9467. func EditDownloadedplanExecWeight(c *gin.Context) {
  9468. appG := app.Gin{C: c}
  9469. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9470. fsions := gofasion.NewFasion(string(dataByte))
  9471. pid := fsions.Get("pid").ValueStr()
  9472. sort := fsions.Get("sort").ValueStr()
  9473. weight := fsions.Get("weight").ValueStr()
  9474. userId := fsions.Get("userId").ValueStr()
  9475. tx := restful.Engine.NewSession()
  9476. defer tx.Close()
  9477. tx.Begin()
  9478. _, err := tx.Exec(` insert into downloadplandtl1_update(pid,sort,lastweight,weight,userId,createdate)
  9479. values(?,?,(select actualweightminus from downloadplandtl1_exec where pid = ? and sort = ? ),?,?,now()) `,
  9480. pid, sort, pid, sort, weight, userId)
  9481. if err != nil {
  9482. logs.Error(err)
  9483. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9484. tx.Rollback()
  9485. return
  9486. }
  9487. _, err = tx.Exec(` update downloadplandtl1_exec set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9488. if err != nil {
  9489. logs.Error(err)
  9490. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9491. tx.Rollback()
  9492. return
  9493. }
  9494. _, 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)
  9495. if err != nil {
  9496. logs.Error(err)
  9497. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9498. tx.Rollback()
  9499. return
  9500. }
  9501. err = tx.Commit()
  9502. if err != nil {
  9503. logs.Error(err)
  9504. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9505. tx.Rollback()
  9506. return
  9507. }
  9508. appG.Response(http.StatusOK, e.SUCCESS, true)
  9509. }
  9510. func EditDownloadplandtl2Weight(c *gin.Context) {
  9511. appG := app.Gin{C: c}
  9512. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9513. fsions := gofasion.NewFasion(string(dataByte))
  9514. pid := fsions.Get("pid").ValueStr()
  9515. sort := fsions.Get("sort").ValueStr()
  9516. weight := fsions.Get("weight").ValueStr()
  9517. userId := fsions.Get("userId").ValueStr()
  9518. tx := restful.Engine.NewSession()
  9519. defer tx.Close()
  9520. tx.Begin()
  9521. _, err := tx.Exec(` insert into downloadplandtl2_update(pid,sort,lastweight,weight,userId,createdate)
  9522. values(?,?,(select actualweightminus from downloadplandtl2 where pid = ? and sort = ? ),?,?,now()) `,
  9523. pid, sort, pid, sort, weight, userId)
  9524. if err != nil {
  9525. logs.Error(err)
  9526. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9527. tx.Rollback()
  9528. return
  9529. }
  9530. _, err = tx.Exec(` update downloadplandtl2 set actualweightminus = ? where pid = ? and sort = ? `, weight, pid, sort)
  9531. if err != nil {
  9532. logs.Error(err)
  9533. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9534. tx.Rollback()
  9535. return
  9536. }
  9537. err = tx.Commit()
  9538. if err != nil {
  9539. logs.Error(err)
  9540. appG.Response(http.StatusOK, e.ERROR, "修改计划重量失败!"+err.Error())
  9541. tx.Rollback()
  9542. return
  9543. }
  9544. appG.Response(http.StatusOK, e.SUCCESS, true)
  9545. }
  9546. func FtdetailSurplus(fasion *gofasion.Fasion) error {
  9547. params := fasion.Get("parammaps")
  9548. surplus := params.Get("surplus").ValueStr()
  9549. surplusId := params.Get("surplusId").ValueStr()
  9550. tx := restful.Engine.NewSession()
  9551. defer tx.Close()
  9552. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, params.Get("id").ValueStr())
  9553. if surplusId != "0" {
  9554. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", params.Get("id").ValueStr()).QueryString()
  9555. if err != nil {
  9556. log.Println("PostDataByName-error-1: ", err)
  9557. return errors.New("配方修改失败!")
  9558. }
  9559. type ftdetail struct {
  9560. Id string
  9561. Fname string
  9562. Sort int64
  9563. }
  9564. ftList := make([]*ftdetail, 0)
  9565. for _, data := range dataList {
  9566. ft := new(ftdetail)
  9567. ft.Fname = data["fname"]
  9568. ft.Id = data["id"]
  9569. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9570. if err != nil {
  9571. log.Println("PostDataByName-error-2: ", err)
  9572. return err
  9573. }
  9574. ft.Sort = sort
  9575. ftList = append(ftList, ft)
  9576. }
  9577. if surplus == "日粮" {
  9578. for _, ft := range ftList {
  9579. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9580. }
  9581. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9582. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9583. params.Get("pastureid").ValueStr(), params.Get("id").ValueStr(), surplusId, surplusId, surplusId)
  9584. fmt.Println(err)
  9585. } else {
  9586. var sort int64
  9587. for _, ft := range ftList {
  9588. if ft.Fname == surplus {
  9589. sort = ft.Sort
  9590. break
  9591. }
  9592. }
  9593. if sort == 0 {
  9594. for _, ft := range ftList {
  9595. ft.Sort = ft.Sort + 1
  9596. }
  9597. } else {
  9598. for _, ft := range ftList {
  9599. if ft.Sort >= sort {
  9600. ft.Sort = ft.Sort + 1
  9601. }
  9602. }
  9603. }
  9604. for _, ft := range ftList {
  9605. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9606. }
  9607. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9608. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9609. params.Get("id").ValueStr(), surplusId, surplusId, sort, surplusId, params.Get("pastureid").ValueStr())
  9610. if err != nil {
  9611. log.Println("PostDataByName-error-1: ", err)
  9612. fmt.Println(err)
  9613. return errors.New("配方修改失败!")
  9614. }
  9615. }
  9616. }
  9617. return nil
  9618. }
  9619. func FeedSurplus(fasion *gofasion.Fasion) {
  9620. tx := restful.Engine.NewSession()
  9621. defer tx.Close()
  9622. params := fasion.Get("parammaps")
  9623. feedId := params.Get("id").ValueStr()
  9624. tx.Exec(` update surplus set surplus = (select fname from feed where id = ? ) where feedId = ? `, feedId, feedId)
  9625. tx.Exec(` update feed set fname = concat((select id from surplus where feedId = ? ) ,'_剩料') where backup3 = (select id from surplus where feedId = ? )`, feedId, feedId)
  9626. }
  9627. func FtdetailSurplusFt(surplus, surplusId, id, pastureId string) error {
  9628. // params := fasion.Get("parammaps")
  9629. // surplus := params.Get("surplus").ValueStr()
  9630. // surplusId := params.Get("surplusId").ValueStr()
  9631. tx := restful.Engine.NewSession()
  9632. defer tx.Close()
  9633. tx.Exec(` delete from ftdetail where ftid = ? and is_surplus = 1 `, id)
  9634. if surplusId != "0" {
  9635. dataList, err := tx.Table("ftdetail").Where("ftid = ? ", id).QueryString()
  9636. if err != nil {
  9637. log.Println("PostDataByName-error-1: ", err)
  9638. return errors.New("配方修改失败!")
  9639. }
  9640. type ftdetail struct {
  9641. Id string
  9642. Fname string
  9643. Sort int64
  9644. }
  9645. ftList := make([]*ftdetail, 0)
  9646. for _, data := range dataList {
  9647. ft := new(ftdetail)
  9648. ft.Fname = data["fname"]
  9649. ft.Id = data["id"]
  9650. sort, err := strconv.ParseInt(data["sort"], 10, 64)
  9651. if err != nil {
  9652. log.Println("PostDataByName-error-2: ", err)
  9653. return err
  9654. }
  9655. ft.Sort = sort
  9656. ftList = append(ftList, ft)
  9657. }
  9658. if surplus == "日粮" {
  9659. for _, ft := range ftList {
  9660. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort+1, ft.Id)
  9661. }
  9662. _, err = tx.Exec(` insert into ftdetail(pastureid,ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight)
  9663. values(?,?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),0,1,2,(select fname from feed where backup3 = ? ),0)`,
  9664. pastureId, id, surplusId, surplusId, surplusId)
  9665. fmt.Println(err)
  9666. } else {
  9667. var sort int64
  9668. for _, ft := range ftList {
  9669. if ft.Fname == surplus {
  9670. sort = ft.Sort
  9671. break
  9672. }
  9673. }
  9674. if sort == 0 {
  9675. for _, ft := range ftList {
  9676. ft.Sort = ft.Sort + 1
  9677. }
  9678. } else {
  9679. for _, ft := range ftList {
  9680. if ft.Sort >= sort {
  9681. ft.Sort = ft.Sort + 1
  9682. }
  9683. }
  9684. }
  9685. for _, ft := range ftList {
  9686. tx.Exec(` update ftdetail set sort = ? where id = ? `, ft.Sort, ft.Id)
  9687. }
  9688. _, err = tx.Exec(` insert into ftdetail(ftid,fid,fname,sort,is_surplus,is_show,feedgroup,fweight,pastureid)
  9689. values(?,(select id from feed where backup3 = ? ),(select fname from feed where backup3 = ? ),?,1,2,(select fname from feed where backup3 = ? ),0,?)`,
  9690. id, surplusId, surplusId, sort, surplusId, pastureId)
  9691. if err != nil {
  9692. log.Println("PostDataByName-error-1: ", err)
  9693. fmt.Println(err)
  9694. return errors.New("配方修改失败!")
  9695. }
  9696. }
  9697. }
  9698. return nil
  9699. }
  9700. func GetLanguageStatus() string {
  9701. tx := restful.Engine.NewSession()
  9702. defer tx.Close()
  9703. dataList, err := tx.SQL(`select inforvalue from sysopt where inforname = 'language' `).QueryString()
  9704. if err != nil {
  9705. log.Println(err)
  9706. return "0"
  9707. }
  9708. return dataList[0]["inforvalue"]
  9709. }
  9710. func EditLanguage(c *gin.Context) {
  9711. appG := app.Gin{C: c}
  9712. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  9713. fsions := gofasion.NewFasion(string(dataByte))
  9714. language := fsions.Get("language").ValueStr()
  9715. tx := restful.Engine.NewSession()
  9716. defer tx.Close()
  9717. _, err := tx.Exec(` update sysopt set inforvalue = ? where inforname = 'language' `, language)
  9718. if err != nil {
  9719. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9720. return
  9721. }
  9722. if language == "0" {
  9723. _, err := tx.Exec(`delete from dictlist `)
  9724. if err != nil {
  9725. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9726. return
  9727. }
  9728. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9729. select id,pid,pastureId,label,value,orderby,enable from dictlist_cn `)
  9730. if err != nil {
  9731. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9732. return
  9733. }
  9734. } else {
  9735. _, err := tx.Exec(`delete from dictlist `)
  9736. if err != nil {
  9737. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9738. return
  9739. }
  9740. _, err = tx.Exec(` insert into dictlist(id,pid,pastureId,label,value,orderby,enable)
  9741. select id,pid,pastureId,label,value,orderby,enable from dictlist_english `)
  9742. if err != nil {
  9743. appG.Response(http.StatusOK, e.ERROR, err.Error())
  9744. return
  9745. }
  9746. }
  9747. appG.Response(http.StatusOK, e.SUCCESS, true)
  9748. }
  9749. func FpdBatchEditGrfd(pastureid string, barList []map[string]string) {
  9750. tx := restful.Engine.NewSession()
  9751. defer tx.Close()
  9752. 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
  9753. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9754. if err != nil {
  9755. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  9756. return
  9757. }
  9758. for _, dataexcel := range barList {
  9759. // dataexcel := make(map[string]interface{}, 0)
  9760. // dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  9761. // dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  9762. // dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  9763. // dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  9764. // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  9765. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  9766. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  9767. // if err != nil {
  9768. // logs.Error(err)
  9769. // return
  9770. // }
  9771. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  9772. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  9773. // if err != nil {
  9774. // logs.Error(err)
  9775. // return
  9776. // }
  9777. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  9778. continue
  9779. }
  9780. // dataexcel["1"] = barFsions.Get("times1").ValueStr()
  9781. // dataexcel["2"] = barFsions.Get("times2").ValueStr()
  9782. // dataexcel["3"] = barFsions.Get("times3").ValueStr()
  9783. // dataexcel["4"] = barFsions.Get("times4").ValueStr()
  9784. // dataexcel["5"] = barFsions.Get("times5").ValueStr()
  9785. // dataexcel["6"] = barFsions.Get("times6").ValueStr()
  9786. // /*
  9787. tx.SQL(` update lpplandtl1 set lweight = 0 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. tx.SQL(` update fpdetail set ptuse = 0 where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9793. if err != nil {
  9794. logs.Error(err)
  9795. return
  9796. }
  9797. // */
  9798. exist, err := tx.SQL(` select id from feedp where barid = (select id from bar where bname = ? ) and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  9799. if err != nil {
  9800. logs.Error(err)
  9801. return
  9802. }
  9803. if !exist {
  9804. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  9805. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  9806. if err != nil {
  9807. logs.Error(err)
  9808. return
  9809. }
  9810. }
  9811. var feedpargs []interface{}
  9812. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  9813. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  9814. if _, ok := dataexcel["ftname"]; ok {
  9815. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  9816. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  9817. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  9818. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  9819. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9820. } else {
  9821. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  9822. }
  9823. if _, ok := dataexcel["ptsfname"]; ok {
  9824. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  9825. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  9826. upFeedpSql += `,supplyweight = ifnull((select sum(fweight) fweight from ftdetail
  9827. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)),0)`
  9828. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  9829. } else {
  9830. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  9831. }
  9832. upFeedpSql += " where barname = ? and pastureid = ? "
  9833. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  9834. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  9835. if err != nil {
  9836. logs.Error(err)
  9837. return
  9838. }
  9839. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  9840. if err != nil {
  9841. logs.Error(err)
  9842. return
  9843. }
  9844. if !exist1 {
  9845. _, 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) `,
  9846. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9847. if err != nil {
  9848. logs.Error(err)
  9849. return
  9850. }
  9851. }
  9852. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  9853. if err != nil {
  9854. logs.Error(err)
  9855. return
  9856. }
  9857. if !exist2 {
  9858. _, 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) `,
  9859. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9860. if err != nil {
  9861. logs.Error(err)
  9862. return
  9863. }
  9864. }
  9865. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  9866. if err != nil {
  9867. logs.Error(err)
  9868. return
  9869. }
  9870. if !exist3 {
  9871. _, 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) `,
  9872. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9873. if err != nil {
  9874. logs.Error(err)
  9875. return
  9876. }
  9877. }
  9878. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  9879. if err != nil {
  9880. logs.Error(err)
  9881. return
  9882. }
  9883. if !exist4 {
  9884. _, 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) `,
  9885. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9886. if err != nil {
  9887. logs.Error(err)
  9888. return
  9889. }
  9890. }
  9891. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  9892. if err != nil {
  9893. logs.Error(err)
  9894. return
  9895. }
  9896. if !exist5 {
  9897. _, 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) `,
  9898. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9899. if err != nil {
  9900. logs.Error(err)
  9901. return
  9902. }
  9903. }
  9904. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  9905. if err != nil {
  9906. logs.Error(err)
  9907. return
  9908. }
  9909. if !exist6 {
  9910. _, 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) `,
  9911. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  9912. if err != nil {
  9913. logs.Error(err)
  9914. return
  9915. }
  9916. }
  9917. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  9918. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  9919. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  9920. and pastureid = ? and times = ?`
  9921. var fpdargs1 []interface{}
  9922. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  9923. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9924. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  9925. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  9926. if err != nil {
  9927. fmt.Println(err)
  9928. return
  9929. }
  9930. var fpdargs2 []interface{}
  9931. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  9932. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9933. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  9934. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  9935. if err != nil {
  9936. fmt.Println(err)
  9937. return
  9938. }
  9939. var fpdargs3 []interface{}
  9940. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  9941. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9942. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  9943. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  9944. if err != nil {
  9945. fmt.Println(err)
  9946. return
  9947. }
  9948. var fpdargs4 []interface{}
  9949. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  9950. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9951. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  9952. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  9953. if err != nil {
  9954. fmt.Println(err)
  9955. return
  9956. }
  9957. var fpdargs5 []interface{}
  9958. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  9959. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9960. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  9961. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  9962. if err != nil {
  9963. fmt.Println(err)
  9964. return
  9965. }
  9966. var fpdargs6 []interface{}
  9967. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  9968. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  9969. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  9970. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  9971. if err != nil {
  9972. fmt.Println(err)
  9973. return
  9974. }
  9975. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  9976. 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()
  9977. if err != nil {
  9978. return
  9979. }
  9980. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  9981. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  9982. upFpdetailList := make([]*upFpdetail, 0)
  9983. for _, newfpd := range newList {
  9984. for _, oldfpd := range oldFpdList {
  9985. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  9986. var oldweight, newweight float64
  9987. if oldfpd["weight"] != nil {
  9988. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  9989. }
  9990. if newfpd["weight"] != nil {
  9991. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  9992. }
  9993. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  9994. upFpdetailList = append(upFpdetailList, &upFpdetail{
  9995. Old: oldweight,
  9996. New: newweight,
  9997. Times: newfpd["times"].(int64),
  9998. Ptid: newfpd["ptid"].(int64),
  9999. Fweight: fweight,
  10000. Id: oldfpd["id"].(int64),
  10001. })
  10002. break
  10003. }
  10004. }
  10005. }
  10006. updateFpdetailByBar(pastureid, dataexcel["barname"], upFpdetailList)
  10007. }
  10008. }
  10009. func AddXxwFtdetail(c *gin.Context) {
  10010. appG := app.Gin{C: c}
  10011. xxwFtdetailList := make([]*models.XXWFtdetail, 0)
  10012. c.Bind(&xxwFtdetailList)
  10013. tx := restful.Engine.NewSession()
  10014. defer tx.Close()
  10015. _, err := tx.Exec(` delete from xxw_feedtemplet `)
  10016. if err != nil {
  10017. logs.Error(err)
  10018. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10019. }
  10020. _, err = tx.Insert(xxwFtdetailList)
  10021. if err != nil {
  10022. logs.Error(err)
  10023. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10024. }
  10025. tx.Exec(` UPDATE notice SET status = 1 WHERE content = 'xxwFeedtemplet' `)
  10026. appG.Response(http.StatusOK, e.SUCCESS, true)
  10027. }
  10028. func AddXxwFeedtemplet(c *gin.Context) {
  10029. appG := app.Gin{C: c}
  10030. xxwFeedtempletList := make([]*models.XXWFeedTemplet, 0)
  10031. c.Bind(&xxwFeedtempletList)
  10032. tx := restful.Engine.NewSession()
  10033. defer tx.Close()
  10034. pastureinfo := new(udPastureInfo)
  10035. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  10036. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  10037. if err != nil {
  10038. logs.Error(err)
  10039. return
  10040. }
  10041. for _, ft := range xxwFeedtempletList {
  10042. ids, err := setting.SnowIds.NextId()
  10043. if err != nil {
  10044. ids = time.Now().UnixNano()
  10045. logging.Info("create SnowIds err", err)
  10046. }
  10047. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname)
  10048. values(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE classname = ?`, ids, pastureinfo.Pastureid, ft.RecipeobjName, ft.RecipeobjName, ids,
  10049. ft.RecipeobjName, ft.RecipeobjName)
  10050. if err != nil {
  10051. logs.Error(err)
  10052. return
  10053. }
  10054. count, _ := tx.SQL(`select count(1) from feedtemplet where pastureid = ? `, pastureinfo.Pastureid).Count()
  10055. _, 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')),
  10056. ?,?,(select ID from cowclass where classname=? and pastureId = ? limit 1),?,'丰顿下发','饲喂配方',1,'丰顿下发',?,?) ON DUPLICATE KEY UPDATE tname = ? `,
  10057. pastureinfo.Pastureid, ft.RecipeName, ft.RecipeId, ft.RecipeobjName, pastureinfo.Pastureid, ft.RecipeobjName, count, ft.RecipeId, ft.RecipeName)
  10058. if err != nil {
  10059. logs.Error(err)
  10060. return
  10061. }
  10062. }
  10063. appG.Response(http.StatusOK, e.SUCCESS, true)
  10064. }
  10065. func ProcessExcel(c *gin.Context) {
  10066. appG := app.Gin{C: c}
  10067. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10068. fasion := gofasion.NewFasion(string(dataByte))
  10069. params := fasion.Get("parammaps")
  10070. pastureid := params.Get("pastureid").ValueStr()
  10071. startTime := params.Get("startTime").ValueStr()
  10072. stopTime := params.Get("stopTime").ValueStr()
  10073. iscompleted := params.Get("iscompleted").ValueStr()
  10074. lpplantype := params.Get("lpplantype").ValueStr()
  10075. error := params.Get("error").ValueStr()
  10076. hlwc1 := params.Get("hlwc1").ValueStr()
  10077. hlwc2 := params.Get("hlwc2").ValueStr()
  10078. slwc1 := params.Get("slwc1").ValueStr()
  10079. slwc2 := params.Get("slwc2").ValueStr()
  10080. hlzq1 := params.Get("hlzq1").ValueStr()
  10081. hlzq2 := params.Get("hlzq2").ValueStr()
  10082. slzq1 := params.Get("slzq1").ValueStr()
  10083. slzq2 := params.Get("slzq2").ValueStr()
  10084. fclassid := params.Get("fclassid").ValueStr()
  10085. minproesstime := params.Get("minproesstime").ValueStr()
  10086. maxproesstime := params.Get("maxproesstime").ValueStr()
  10087. tx := restful.Engine.NewSession()
  10088. defer tx.Close()
  10089. planList, err := tx.SQL(`SELECT
  10090. 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
  10091. FROM downloadedplan d
  10092. join pasture p on p.pastureid = d.pastureid
  10093. WHERE d.pastureid= ? and d.intime IS NOT NULL
  10094. AND mydate >= ? AND mydate <= ?
  10095. AND (iscompleted=? or ?='')
  10096. AND (lpplantype = ? or ? = '')
  10097. and (if((select count(1) from downloadplandtl1 d1 where d1.pid = d.id
  10098. 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
  10099. and ABS(d1.lweight- d1.actualweightminus) > d1.allowratio and d1.allowratio != 0 ) >0,"有误差","无误差") = ? or ? = '')
  10100. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10101. and ABS(d1.lweight- d1.actualweightminus) between ? and ? ) > 0)
  10102. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10103. and ABS(d2.lweight- d2.actualweightminus) between ? and ? )> 0)
  10104. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl1_exec d1 where d1.pid = d.id
  10105. and if( d1.lweight >= d1.actualweightminus,d1.actualweightminus / d1.lweight *100 ,d1.lweight / d1.actualweightminus *100) between ? and ? )> 0)
  10106. and if(?='' and ? = '' ,1=1,(select count(1) from downloadplandtl2 d2 where d2.pid = d.id
  10107. and if( d2.lweight >= d2.actualweightminus,d2.actualweightminus / d2.lweight *100 ,d2.lweight / d2.actualweightminus *100) between ? and ? )> 0)
  10108. and if(? = '', 1=1,(select count(1) from downloadplandtl1 d1
  10109. 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,
  10110. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' 00:00:00'),
  10111. concat(DATE_FORMAT(intime,'%Y-%m-%d'),' ',TIMEDIFF(IFNULL((SELECT MAX(intime) FROM downloadplandtl2 d2
  10112. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id),
  10113. (SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10114. WHERE d.mydate=d2.date AND d.pastureid = d2.pastureid AND d2.pid=d.id)
  10115. ),(select intime from downloadplandtl1_exec de where de.pid = d.id order by de.sort limit 1 )) ) )/60,2) between ? and ?
  10116. or (?= '' and ? = '' ))
  10117. `, pastureid, startTime, stopTime, iscompleted, iscompleted, lpplantype, lpplantype,
  10118. error, error, error, hlwc1, hlwc2, hlwc1, hlwc2, slwc1, slwc2, slwc1, slwc2, hlzq1,
  10119. hlzq2, hlzq1, hlzq2, slzq1, slzq2, slzq1, slzq2, fclassid, fclassid, minproesstime,
  10120. maxproesstime, minproesstime, maxproesstime).QueryString()
  10121. if err != nil {
  10122. logs.Error(err)
  10123. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10124. return
  10125. }
  10126. planExecList, err := tx.SQL(`SELECT
  10127. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10128. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10129. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadedplan d2
  10130. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10131. ) proesstime,
  10132. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10133. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadedplan d2
  10134. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid))
  10135. sumproesstime, d1.pid,
  10136. d1.sort,
  10137. d1.fname,
  10138. d1.lweight,
  10139. d1.actualweightminus,
  10140. ifnull(ABS(d1.lweight- d1.actualweightminus),0) diff,
  10141. ifnull(if(ifnull(d1.feedallowratio,0) <=0 ,0, if(ABS(d1.lweight- ifnull(d1.actualweightminus,0)) >= ifnull(d1.feedallowratio,0),1,0)),0) abnormal,
  10142. round(ifnull(if((select inforvalue from sysopt where inforname = 'accuracy' and pastureid = d1.pastureid) = 1,
  10143. if(abs(d1.actualweightminus - d1.lweight) <=ifnull(d1.feedallowratio,0) , 100,
  10144. if(d1.actualweightminus > d1.lweight , 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.actualweightminus ,
  10145. 1-(abs(d1.actualweightminus - d1.lweight) - ifnull(d1.feedallowratio,0))/d1.lweight ) *100 ) ,
  10146. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight*100,2) ,ROUND(d1.lweight/d1.actualweightminus*100,2))),0),2) diffRate,
  10147. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10148. d1.begintime stoptime,
  10149. d1.lastactualweight,
  10150. d1.actualweight,
  10151. if( (select inforvalue from sysopt where inforname = 'language' and d1.pastureId =pastureId ) = 0 ,
  10152. case d1.buttontype
  10153. when 1 then '自动'
  10154. when 2 then '手动'
  10155. when 3 then '手动'
  10156. end,
  10157. case d1.buttontype
  10158. when 1 then 'Automatic'
  10159. when 2 then 'Manual'
  10160. when 3 then 'Manual'
  10161. end
  10162. ) buttontype
  10163. FROM
  10164. downloadplandtl1_exec d1
  10165. WHERE d1.date between ? and ?
  10166. ORDER BY sort
  10167. `, startTime, stopTime).QueryString()
  10168. if err != nil {
  10169. logs.Error(err)
  10170. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10171. return
  10172. }
  10173. planExec2, err := tx.SQL(`SELECT
  10174. IFNULL(TIMEDIFF (d1.intime,(SELECT MAX(intime) FROM downloadplandtl2 d2
  10175. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime))
  10176. , TIMEDIFF(intime,(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10177. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid))
  10178. ) proesstime,
  10179. TIMEDIFF((SELECT MAX(intime) FROM downloadplandtl2 d2
  10180. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid ),(SELECT MAX(intime) FROM downloadplandtl1_exec d2
  10181. WHERE d1.date=d2.date AND d1.pastureid = d2.pastureid AND d2.pid=d1.pid)) sumproesstime,
  10182. d1.sort,
  10183. d1.fname,
  10184. d1.lweight,
  10185. d1.actualweightminus,
  10186. if(d1.allowratio <=0 ,0, if(ABS(d1.lweight- d1.actualweightminus) >= d1.allowratio ,1,0)) abnormal,
  10187. ABS(d1.lweight- d1.actualweightminus) diff,
  10188. 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,
  10189. DATE_FORMAT(d1.intime, '%H:%i:%s') intime,
  10190. d1.begintime stoptime,
  10191. d1.lastactualweight,
  10192. d1.actualweight,d1.pid
  10193. FROM
  10194. downloadplandtl2 d1
  10195. WHERE d1.date between ? and ?
  10196. ORDER BY sort`, startTime, stopTime).QueryString()
  10197. if err != nil {
  10198. logs.Error(err)
  10199. appG.Response(http.StatusOK, e.ERROR, err.Error())
  10200. return
  10201. }
  10202. // 创建一个新的 Excel 文件
  10203. f := excelizexuri.NewFile()
  10204. // 创建工作表名称
  10205. sheetName := "Sheet1"
  10206. // border := []excelizexuri.Border{
  10207. // {Type: "left", Color: "000000", Style: 1},
  10208. // {Type: "right", Color: "000000", Style: 1},
  10209. // {Type: "top", Color: "000000", Style: 1},
  10210. // {Type: "bottom", Color: "000000", Style: 1},
  10211. // }
  10212. // 创建新的样式
  10213. style := &excelizexuri.Style{
  10214. // Border: border,
  10215. Alignment: &excelizexuri.Alignment{
  10216. Vertical: "center",
  10217. Horizontal: "center",
  10218. ShrinkToFit: true,
  10219. WrapText: true,
  10220. },
  10221. }
  10222. styleTitle := &excelizexuri.Style{
  10223. Fill: excelizexuri.Fill{
  10224. Color: []string{"FFFF0000"}, // 尝试使用完整的ARGB格式
  10225. },
  10226. // Border: border,
  10227. Font: &excelizexuri.Font{
  10228. Bold: true, // 加粗
  10229. Size: 24, // 字体大小
  10230. // Name: "宋体", // 字体名称
  10231. // WrapText :true,
  10232. Color: "000000", // 字体颜色(黑色)
  10233. },
  10234. Alignment: &excelizexuri.Alignment{
  10235. Vertical: "center", // 垂直居中
  10236. Horizontal: "center", // 水平居中
  10237. ShrinkToFit: true,
  10238. WrapText: true,
  10239. },
  10240. }
  10241. // 创建样式 ID
  10242. styleTitleId, err := f.NewStyle(styleTitle)
  10243. if err != nil {
  10244. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10245. return
  10246. }
  10247. // 创建样式 ID
  10248. styleID, err := f.NewStyle(style)
  10249. if err != nil {
  10250. c.String(http.StatusInternalServerError, "Failed to create style: "+err.Error())
  10251. return
  10252. }
  10253. // 合并单元格并设置内容
  10254. f.MergeCell(sheetName, "A1", "K1")
  10255. f.SetCellValue(sheetName, "A1", "TMR计划执行情况明细")
  10256. f.SetCellStyle(sheetName, "A1", "K1", styleTitleId)
  10257. // 添加表头 牧场名称 TMR 计划名称 制定日期 开始日期
  10258. planExecMap := make(map[string][]map[string]string, 0)
  10259. for _, planExec := range planExecList {
  10260. planExecMap[planExec["pid"]] = append(planExecMap[planExec["pid"]], planExec)
  10261. }
  10262. plan2Map := make(map[string][]map[string]string, 0)
  10263. for _, plan2 := range planExec2 {
  10264. plan2Map[plan2["pid"]] = append(plan2Map[plan2["pid"]], plan2)
  10265. }
  10266. num := 2
  10267. var notBorder []int
  10268. for _, plan := range planList {
  10269. headers := []string{"牧场名称", "TMR", "计划名称", "制定日期", "开始日期"}
  10270. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10271. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10272. for i, header := range headers {
  10273. // 从 A2 开始
  10274. if header == "开始日期" {
  10275. cell := "%" + fmt.Sprintf("c%d", num)
  10276. cell = fmt.Sprintf(cell, 'A'+i+1)
  10277. f.SetCellValue(sheetName, cell, header)
  10278. f.SetCellStyle(sheetName, cell, cell, styleID)
  10279. continue
  10280. }
  10281. cell := "%" + fmt.Sprintf("c%d", num)
  10282. cell = fmt.Sprintf(cell, 'A'+i)
  10283. f.SetCellValue(sheetName, cell, header)
  10284. f.SetCellStyle(sheetName, cell, cell, styleID)
  10285. }
  10286. num += 1
  10287. // cell := fmt.Sprintf("%c3", 'A'+0) // 从 A2 开始
  10288. cell := "%" + fmt.Sprintf("c%d", num)
  10289. cell = fmt.Sprintf(cell, 'A'+0)
  10290. f.SetCellValue(sheetName, cell, plan["pastureName"])
  10291. f.SetCellStyle(sheetName, cell, cell, styleID)
  10292. // cell = fmt.Sprintf("%c3", 'A'+1) // 从 A2 开始
  10293. cell = "%" + fmt.Sprintf("c%d", num)
  10294. cell = fmt.Sprintf(cell, 'A'+1)
  10295. f.SetCellValue(sheetName, cell, plan["tmrtname"])
  10296. f.SetCellStyle(sheetName, cell, cell, styleID)
  10297. // cell = fmt.Sprintf("%c3", 'A'+2) // 从 A2 开始
  10298. cell = "%" + fmt.Sprintf("c%d", num)
  10299. cell = fmt.Sprintf(cell, 'A'+2)
  10300. f.SetCellValue(sheetName, cell, plan["projname"])
  10301. f.SetCellStyle(sheetName, cell, cell, styleID)
  10302. cell = "%" + fmt.Sprintf("c%d", num)
  10303. cell = fmt.Sprintf(cell, 'A'+3)
  10304. f.MergeCell(sheetName, fmt.Sprintf("D%d", num), fmt.Sprintf("E%d", num))
  10305. f.SetCellValue(sheetName, cell, plan["mydate"])
  10306. f.SetCellStyle(sheetName, cell, cell, styleID)
  10307. cell = "%" + fmt.Sprintf("c%d", num)
  10308. cell = fmt.Sprintf(cell, 'A'+6)
  10309. f.MergeCell(sheetName, fmt.Sprintf("F%d", num), fmt.Sprintf("K%d", num))
  10310. f.SetCellValue(sheetName, cell, plan["intime"])
  10311. f.SetCellStyle(sheetName, cell, cell, styleID)
  10312. num += 1
  10313. headers1 := []string{"操作编号", "计划重量", "实际重量", "代表成分", "误差数", "准确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10314. for i, header := range headers1 {
  10315. cell = "%" + fmt.Sprintf("c%d", num)
  10316. cell = fmt.Sprintf(cell, 'C'+i)
  10317. f.SetCellValue(sheetName, cell, header)
  10318. f.SetCellStyle(sheetName, cell, cell, styleID)
  10319. // maxWidth := len(header)
  10320. // colName := string('C' + i)
  10321. // f.SetColWidth(sheetName, colName, colName, 20)
  10322. f.SetColWidth(sheetName, header, header, 40)
  10323. }
  10324. num += 1
  10325. // 在循环外部创建红色样式(只创建一次)
  10326. redStyle := &excelizexuri.Style{
  10327. Fill: excelizexuri.Fill{
  10328. Type: "pattern",
  10329. Color: []string{"FF0000"},
  10330. Pattern: 1,
  10331. },
  10332. // Font: &excelizexuri.Font{
  10333. // Bold: true, // 加粗
  10334. // Size: 24, // 字体大小
  10335. // // Name: "宋体", // 字体名称
  10336. // // WrapText :true,
  10337. // Color: "FFFF0000", // 字体颜色(黑色)
  10338. // },
  10339. Alignment: &excelizexuri.Alignment{
  10340. Vertical: "center",
  10341. Horizontal: "center",
  10342. ShrinkToFit: true,
  10343. WrapText: true,
  10344. },
  10345. }
  10346. redStyleID, err := f.NewStyle(redStyle)
  10347. if err != nil {
  10348. c.String(http.StatusInternalServerError, "Failed to create red style: "+err.Error())
  10349. return
  10350. }
  10351. // 在循环内部正确使用条件判断
  10352. for _, planExec := range planExecMap[plan["id"]] {
  10353. var currentStyleID int
  10354. if planExec["abnormal"] == "1" {
  10355. currentStyleID = redStyleID
  10356. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, planExec["abnormal"]) // 调试
  10357. } else {
  10358. currentStyleID = styleID
  10359. }
  10360. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10361. sort, _ := strconv.Atoi(planExec["sort"])
  10362. f.SetCellValue(sheetName, cell, sort)
  10363. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10364. cell = fmt.Sprintf("D%d", num)
  10365. lweight, _ := strconv.ParseFloat(planExec["lweight"], 64)
  10366. f.SetCellValue(sheetName, cell, lweight)
  10367. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10368. cell = fmt.Sprintf("E%d", num)
  10369. if _, ok := planExec["actualweightminus"]; ok {
  10370. actualweightminus, _ := strconv.ParseFloat(planExec["actualweightminus"], 64)
  10371. f.SetCellValue(sheetName, cell, actualweightminus)
  10372. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10373. } else {
  10374. f.SetCellValue(sheetName, cell, planExec["actualweightminus"])
  10375. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10376. }
  10377. cell = fmt.Sprintf("F%d", num)
  10378. f.SetCellValue(sheetName, cell, planExec["fname"])
  10379. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10380. cell = fmt.Sprintf("G%d", num)
  10381. if _, ok := planExec["diff"]; ok {
  10382. diff, _ := strconv.ParseFloat(planExec["diff"], 64)
  10383. f.SetCellValue(sheetName, cell, diff)
  10384. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10385. } else {
  10386. f.SetCellValue(sheetName, cell, planExec["diff"])
  10387. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10388. }
  10389. cell = fmt.Sprintf("H%d", num)
  10390. if _, ok := planExec["diffRate"]; ok {
  10391. diffRate, _ := strconv.ParseFloat(planExec["diffRate"], 64)
  10392. f.SetCellValue(sheetName, cell, diffRate)
  10393. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10394. } else {
  10395. f.SetCellValue(sheetName, cell, planExec["diffRate"])
  10396. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10397. }
  10398. cell = fmt.Sprintf("I%d", num)
  10399. f.SetCellValue(sheetName, cell, planExec["intime"])
  10400. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10401. cell = fmt.Sprintf("J%d", num)
  10402. if _, ok := planExec["lastactualweight"]; ok {
  10403. lastactualweight, _ := strconv.ParseFloat(planExec["lastactualweight"], 64)
  10404. f.SetCellValue(sheetName, cell, lastactualweight)
  10405. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10406. } else {
  10407. f.SetCellValue(sheetName, cell, planExec["lastactualweight"])
  10408. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10409. }
  10410. cell = fmt.Sprintf("K%d", num)
  10411. if _, ok := planExec["actualweight"]; ok {
  10412. actualweight, _ := strconv.ParseFloat(planExec["actualweight"], 64)
  10413. f.SetCellValue(sheetName, cell, actualweight)
  10414. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10415. } else {
  10416. f.SetCellValue(sheetName, cell, planExec["actualweight"])
  10417. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10418. }
  10419. num += 1
  10420. }
  10421. headers2 := []string{"操作编号", "投料位置", "计划重量", "实际重量", "误差数", "正确率(%)", "完成时间", "起始读数重量", "完成读数重量"}
  10422. for i, header := range headers2 {
  10423. cell := "%" + fmt.Sprintf("c%d", num)
  10424. cell = fmt.Sprintf(cell, 'C'+i)
  10425. f.SetCellValue(sheetName, cell, header)
  10426. f.SetCellStyle(sheetName, cell, cell, styleID)
  10427. maxWidth := len(header)
  10428. f.SetColWidth(sheetName, header, header, float64(maxWidth)*2.5)
  10429. }
  10430. num += 1
  10431. for _, plan2 := range plan2Map[plan["id"]] {
  10432. var currentStyleID int
  10433. if plan2["abnormal"] == "1" {
  10434. currentStyleID = redStyleID
  10435. fmt.Printf("行 %d 使用红色样式,abnormal: %s\n", num, plan2["abnormal"]) // 调试
  10436. } else {
  10437. currentStyleID = styleID
  10438. }
  10439. cell := fmt.Sprintf("C%d", num) // 从 A2 开始
  10440. sort, _ := strconv.Atoi(plan2["sort"])
  10441. f.SetCellValue(sheetName, cell, sort)
  10442. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10443. cell = fmt.Sprintf("D%d", num)
  10444. f.SetCellValue(sheetName, cell, plan2["fname"])
  10445. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10446. cell = fmt.Sprintf("E%d", num)
  10447. lweight, _ := strconv.ParseFloat(plan2["lweight"], 64)
  10448. f.SetCellValue(sheetName, cell, lweight)
  10449. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10450. cell = fmt.Sprintf("F%d", num)
  10451. if _, ok := plan2["actualweightminus"]; ok {
  10452. actualweightminus, _ := strconv.ParseFloat(plan2["actualweightminus"], 64)
  10453. f.SetCellValue(sheetName, cell, actualweightminus)
  10454. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10455. } else {
  10456. f.SetCellValue(sheetName, cell, plan2["actualweightminus"])
  10457. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10458. }
  10459. cell = fmt.Sprintf("G%d", num)
  10460. if _, ok := plan2["diff"]; ok {
  10461. diff, _ := strconv.ParseFloat(plan2["diff"], 64)
  10462. f.SetCellValue(sheetName, cell, diff)
  10463. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10464. } else {
  10465. f.SetCellValue(sheetName, cell, plan2["diff"])
  10466. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10467. }
  10468. cell = fmt.Sprintf("H%d", num)
  10469. if _, ok := plan2["diffRate"]; ok {
  10470. diffRate, _ := strconv.ParseFloat(plan2["diffRate"], 64)
  10471. f.SetCellValue(sheetName, cell, diffRate)
  10472. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10473. } else {
  10474. f.SetCellValue(sheetName, cell, plan2["diffRate"])
  10475. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10476. }
  10477. cell = fmt.Sprintf("I%d", num)
  10478. f.SetCellValue(sheetName, cell, plan2["intime"])
  10479. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10480. cell = fmt.Sprintf("J%d", num)
  10481. if _, ok := plan2["lastactualweight"]; ok {
  10482. lastactualweight, _ := strconv.ParseFloat(plan2["lastactualweight"], 64)
  10483. f.SetCellValue(sheetName, cell, lastactualweight)
  10484. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10485. } else {
  10486. f.SetCellValue(sheetName, cell, plan2["lastactualweight"])
  10487. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10488. }
  10489. cell = fmt.Sprintf("K%d", num)
  10490. if _, ok := plan2["lastactualweight"]; ok {
  10491. actualweight, _ := strconv.ParseFloat(plan2["actualweight"], 64)
  10492. f.SetCellValue(sheetName, cell, actualweight)
  10493. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10494. } else {
  10495. f.SetCellValue(sheetName, cell, plan2["actualweight"])
  10496. f.SetCellStyle(sheetName, cell, cell, currentStyleID)
  10497. }
  10498. num += 1
  10499. }
  10500. num += 1
  10501. notBorder = append(notBorder, num)
  10502. }
  10503. // for i := 2; i < num; i++ {
  10504. // exist := false
  10505. // for _, n := range notBorder {
  10506. // if i+1 == n {
  10507. // exist = true
  10508. // break
  10509. // }
  10510. // }
  10511. // if !exist {
  10512. // // 为 A-K 列设置边框
  10513. // for col := 'A'; col <= 'K'; col++ {
  10514. // cellName := fmt.Sprintf("%c%d", col, i)
  10515. // style, _ := f.NewStyle(&excelizexuri.Style{
  10516. // // Border: border,
  10517. // Alignment: &excelizexuri.Alignment{
  10518. // Vertical: "center",
  10519. // Horizontal: "center",
  10520. // ShrinkToFit: true,
  10521. // WrapText: true,
  10522. // },
  10523. // })
  10524. // f.SetCellStyle(sheetName, cellName, cellName, style)
  10525. // }
  10526. // }
  10527. // }
  10528. for col := 'A'; col <= 'K'; col++ {
  10529. colName := string(col)
  10530. switch colName {
  10531. case "A", "B": // 牧场名称、TMR列
  10532. f.SetColWidth(sheetName, colName, colName, 10)
  10533. case "C": // 操作编号列
  10534. f.SetColWidth(sheetName, colName, colName, 10)
  10535. case "D", "E": // 计划重量、实际重量列
  10536. f.SetColWidth(sheetName, colName, colName, 12)
  10537. case "F": // 代表成分/投料位置列
  10538. f.SetColWidth(sheetName, colName, colName, 20)
  10539. case "G", "H": // 误差数、准确率列
  10540. f.SetColWidth(sheetName, colName, colName, 12)
  10541. case "I": // 完成时间列
  10542. f.SetColWidth(sheetName, colName, colName, 15)
  10543. case "J", "K": // 起始读数重量、完成读数重量列
  10544. f.SetColWidth(sheetName, colName, colName, 15)
  10545. }
  10546. }
  10547. // 设置响应头
  10548. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  10549. c.Header("Content-Disposition", "attachment; filename=\"Workbook.xlsx\"")
  10550. c.Header("Content-Transfer-Encoding", "binary")
  10551. // 写入 Excel 文件到响应
  10552. if err := f.Write(c.Writer); err != nil {
  10553. c.String(http.StatusInternalServerError, "Failed to write Excel file: "+err.Error())
  10554. return
  10555. }
  10556. }
  10557. func RestartMqtt(c *gin.Context) {
  10558. appG := app.Gin{C: c}
  10559. // 发送 GET 请求到 MQTT 重启接口
  10560. resp, err := http.Get("http://host.docker.internal:8081/restartMqtt")
  10561. if err != nil {
  10562. logging.Error("RestartMqtt request failed:", err)
  10563. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10564. return
  10565. }
  10566. defer resp.Body.Close()
  10567. // 读取响应内容f
  10568. body, err := ioutil.ReadAll(resp.Body)
  10569. if err != nil {
  10570. logging.Error("RestartMqtt read response failed:", err)
  10571. appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
  10572. return
  10573. }
  10574. // 检查响应状态码
  10575. if resp.StatusCode != http.StatusOK {
  10576. logging.Error("RestartMqtt failed with status:", resp.StatusCode)
  10577. appG.Response(http.StatusInternalServerError, e.ERROR, string(body))
  10578. return
  10579. }
  10580. appG.Response(http.StatusOK, e.SUCCESS, string(body))
  10581. }
  10582. func FpdBatchEditByWeight(c *gin.Context) {
  10583. appG := app.Gin{C: c}
  10584. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  10585. fsions := gofasion.NewFasion(string(dataByte))
  10586. barList := fsions.Get("barList").Array()
  10587. pastureid := fsions.Get("pastureId").ValueStr()
  10588. tx := restful.Engine.NewSession()
  10589. defer tx.Close()
  10590. 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
  10591. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10592. if err != nil {
  10593. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10594. return
  10595. }
  10596. for _, barFsions := range barList {
  10597. dataexcel := make(map[string]interface{}, 0)
  10598. dataexcel["barname"] = barFsions.Get("barname").ValueStr()
  10599. dataexcel["ccount"] = barFsions.Get("ccount").ValueStr()
  10600. dataexcel["ratio"] = barFsions.Get("ratio").ValueStr()
  10601. dataexcel["ftname"] = barFsions.Get("ftname").ValueStr()
  10602. dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
  10603. if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
  10604. continue
  10605. }
  10606. // _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? )
  10607. // and find_in_set(barid,(select barid from feedp where barname = ? )) `, pastureid, pastureid, dataexcel["barname"]).Execute()
  10608. // if err != nil {
  10609. // logs.Error(err)
  10610. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10611. // return
  10612. // }
  10613. // _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  10614. // WHERE pastureid=? and find_in_set(barid,(select barid from feedp where barname = ? ) ) `, pastureid, dataexcel["barname"]).Execute()
  10615. // if err != nil {
  10616. // logs.Error(err)
  10617. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  10618. // return
  10619. // }
  10620. // weight := (barFsions.Get("times1").ValueDefaultFloat64(0) + barFsions.Get("times2").ValueDefaultFloat64(0) +
  10621. // barFsions.Get("times3").ValueDefaultFloat64(0) +
  10622. // barFsions.Get("times4").ValueDefaultFloat64(0) +
  10623. // barFsions.Get("times5").ValueDefaultFloat64(0) +
  10624. // barFsions.Get("times6").ValueDefaultFloat64(0))
  10625. // dataexcel["ratio1"] = (barFsions.Get("times1").ValueDefaultFloat64(0) / weight) * 100
  10626. // dataexcel["ratio2"] = (barFsions.Get("times2").ValueDefaultFloat64(0) / weight) * 100
  10627. // dataexcel["ratio3"] = (barFsions.Get("times3").ValueDefaultFloat64(0) / weight) * 100
  10628. // dataexcel["ratio4"] = (barFsions.Get("times4").ValueDefaultFloat64(0) / weight) * 100
  10629. // dataexcel["ratio5"] = (barFsions.Get("times5").ValueDefaultFloat64(0) / weight) * 100
  10630. // dataexcel["ratio6"] = (barFsions.Get("times6").ValueDefaultFloat64(0) / weight) * 100
  10631. dataexcel["1"] = barFsions.Get("times1").ValueStr()
  10632. dataexcel["2"] = barFsions.Get("times2").ValueStr()
  10633. dataexcel["3"] = barFsions.Get("times3").ValueStr()
  10634. dataexcel["4"] = barFsions.Get("times4").ValueStr()
  10635. dataexcel["5"] = barFsions.Get("times5").ValueStr()
  10636. dataexcel["6"] = barFsions.Get("times6").ValueStr()
  10637. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  10638. if err != nil {
  10639. logs.Error(err)
  10640. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10641. return
  10642. }
  10643. if !ftexist {
  10644. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  10645. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10646. if err != nil {
  10647. logs.Error(err)
  10648. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10649. return
  10650. }
  10651. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10652. if err != nil {
  10653. logs.Error(err)
  10654. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10655. return
  10656. }
  10657. }
  10658. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  10659. if err != nil {
  10660. logs.Error(err)
  10661. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10662. return
  10663. }
  10664. if !exist {
  10665. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  10666. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  10667. if err != nil {
  10668. logs.Error(err)
  10669. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10670. return
  10671. }
  10672. }
  10673. var feedpargs []interface{}
  10674. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  10675. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  10676. if _, ok := dataexcel["ftname"]; ok {
  10677. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  10678. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  10679. // upFeedpSql += `,ftweight = ? `
  10680. // feedpargs = append(feedpargs, weight)
  10681. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  10682. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  10683. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10684. } else {
  10685. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  10686. }
  10687. // if _, ok := dataexcel["ptsfname"]; ok {
  10688. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  10689. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  10690. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  10691. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  10692. // feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  10693. // } else {
  10694. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  10695. // }
  10696. upFeedpSql += " where barname = ? and pastureid = ? "
  10697. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  10698. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  10699. if err != nil {
  10700. logs.Error(err)
  10701. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10702. return
  10703. }
  10704. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  10705. if err != nil {
  10706. logs.Error(err)
  10707. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10708. return
  10709. }
  10710. if !exist1 {
  10711. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)v
  10712. alues(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  10713. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10714. if err != nil {
  10715. logs.Error(err)
  10716. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10717. return
  10718. }
  10719. }
  10720. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  10721. if err != nil {
  10722. logs.Error(err)
  10723. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10724. return
  10725. }
  10726. if !exist2 {
  10727. _, 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) `,
  10728. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10729. if err != nil {
  10730. logs.Error(err)
  10731. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10732. return
  10733. }
  10734. }
  10735. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  10736. if err != nil {
  10737. logs.Error(err)
  10738. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10739. return
  10740. }
  10741. if !exist3 {
  10742. _, 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) `,
  10743. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10744. if err != nil {
  10745. logs.Error(err)
  10746. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10747. return
  10748. }
  10749. }
  10750. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  10751. if err != nil {
  10752. logs.Error(err)
  10753. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10754. return
  10755. }
  10756. if !exist4 {
  10757. _, 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) `,
  10758. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10759. if err != nil {
  10760. logs.Error(err)
  10761. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10762. return
  10763. }
  10764. }
  10765. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  10766. if err != nil {
  10767. logs.Error(err)
  10768. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10769. return
  10770. }
  10771. if !exist5 {
  10772. _, 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) `,
  10773. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10774. if err != nil {
  10775. logs.Error(err)
  10776. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10777. return
  10778. }
  10779. }
  10780. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  10781. if err != nil {
  10782. logs.Error(err)
  10783. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10784. return
  10785. }
  10786. if !exist6 {
  10787. _, 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) `,
  10788. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  10789. if err != nil {
  10790. logs.Error(err)
  10791. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10792. return
  10793. }
  10794. }
  10795. upFpdSql := ` update fpdetail set tratio = ?/( select ftweight from feedp where barname = ? and pastureid = ? ) *100 ,weight = ?,cowcount = ? ,
  10796. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  10797. and pastureid = ? and times = ?`
  10798. var fpdargs1 []interface{}
  10799. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["barname"], pastureid, dataexcel["1"], dataexcel["ccount"],
  10800. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  10801. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  10802. if err != nil {
  10803. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10804. return
  10805. }
  10806. var fpdargs2 []interface{}
  10807. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["barname"], pastureid, dataexcel["2"], dataexcel["ccount"],
  10808. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  10809. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  10810. if err != nil {
  10811. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10812. return
  10813. }
  10814. var fpdargs3 []interface{}
  10815. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["barname"], pastureid, dataexcel["3"], dataexcel["ccount"],
  10816. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  10817. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  10818. if err != nil {
  10819. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10820. return
  10821. }
  10822. var fpdargs4 []interface{}
  10823. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["barname"], pastureid, dataexcel["4"], dataexcel["ccount"],
  10824. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  10825. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  10826. if err != nil {
  10827. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10828. return
  10829. }
  10830. var fpdargs5 []interface{}
  10831. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["barname"], pastureid, dataexcel["5"], dataexcel["ccount"],
  10832. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  10833. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  10834. if err != nil {
  10835. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10836. return
  10837. }
  10838. var fpdargs6 []interface{}
  10839. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["barname"], pastureid, dataexcel["6"], dataexcel["ccount"],
  10840. dataexcel["ratio"], dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  10841. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  10842. if err != nil {
  10843. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10844. return
  10845. }
  10846. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  10847. 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()
  10848. if err != nil {
  10849. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  10850. return
  10851. }
  10852. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  10853. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  10854. upFpdetailList := make([]*upFpdetail, 0)
  10855. for _, newfpd := range newList {
  10856. for _, oldfpd := range oldFpdList {
  10857. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  10858. var oldweight, newweight float64
  10859. if oldfpd["weight"] != nil {
  10860. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  10861. }
  10862. if newfpd["weight"] != nil {
  10863. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  10864. }
  10865. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  10866. upFpdetailList = append(upFpdetailList, &upFpdetail{
  10867. Old: oldweight,
  10868. New: newweight,
  10869. Times: newfpd["times"].(int64),
  10870. Ptid: newfpd["ptid"].(int64),
  10871. Fweight: fweight,
  10872. Id: oldfpd["id"].(int64),
  10873. })
  10874. break
  10875. }
  10876. }
  10877. }
  10878. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  10879. }
  10880. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  10881. }
  10882. func FtImportExcel(c *gin.Context) {
  10883. appG := app.Gin{C: c}
  10884. inputdata := ""
  10885. c.Request.ParseForm()
  10886. params := c.Request.Form
  10887. file, _, err := c.Request.FormFile("file")
  10888. if err != nil {
  10889. appG.Response(http.StatusOK, e.ERROR, err)
  10890. return
  10891. }
  10892. sqlnamestrs := params.Get("name")
  10893. sheetname := params.Get("sheetname")
  10894. pastureid := params.Get("pastureid")
  10895. //importParams := params.Get("importParams")
  10896. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  10897. // 必输项参数 (字符串格式 "field1,field2,field3")
  10898. requiredParams := params.Get("requiredParams")
  10899. // 日期参数
  10900. dateParams := params.Get("dateParams")
  10901. // 数字参数
  10902. numParams := params.Get("numParams")
  10903. //将字符串分割开
  10904. dateParamslist := strings.Split(dateParams, ",")
  10905. requiredParamslist := strings.Split(requiredParams, ",")
  10906. numParamslist := strings.Split(numParams, ",")
  10907. queryData := make([]interface{}, 0)
  10908. sqlslist := strings.Split(sqlnamestrs, ",")
  10909. xlsx1, err := excelize.OpenReader(file)
  10910. if err != nil {
  10911. fmt.Println(err)
  10912. return
  10913. }
  10914. ok := 0
  10915. error := 0
  10916. isdone := true
  10917. rows := xlsx1.GetRows(sheetname)
  10918. // 限制10000条,多余的截取掉
  10919. if len(rows) > 10000 {
  10920. rows = rows[:10000]
  10921. }
  10922. tx := restful.Engine.NewSession()
  10923. ftNameList := make(map[string]interface{})
  10924. var ftNames []interface{}
  10925. for i, row := range rows {
  10926. if i > 0 {
  10927. entry := make(map[string]interface{})
  10928. outentry := make(map[string]interface{})
  10929. for j, colCell := range rows[0] {
  10930. for k, colCell1 := range row {
  10931. if j == k {
  10932. outentry[colCell] = colCell1
  10933. entry[colCell] = colCell1
  10934. }
  10935. }
  10936. }
  10937. inputdata = ""
  10938. a := ""
  10939. fmt.Println(outentry, entry)
  10940. //校验日期格式
  10941. for _, v := range dateParamslist {
  10942. if v == "" {
  10943. continue
  10944. }
  10945. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  10946. dtime, err := TransfTime(d.(string))
  10947. if err != nil {
  10948. a = strings.Trim(v, " ")
  10949. break
  10950. }
  10951. outentry[strings.Trim(v, " ")] = dtime
  10952. }
  10953. }
  10954. if a != "" {
  10955. outentry["error_msg"] = a + " 格式错误"
  10956. error++
  10957. queryData = append(queryData, outentry)
  10958. continue
  10959. }
  10960. a = ""
  10961. //校验必填格式
  10962. for _, v := range requiredParamslist {
  10963. if v == "" {
  10964. continue
  10965. }
  10966. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  10967. a = strings.Trim(v, " ")
  10968. break
  10969. }
  10970. }
  10971. if a != "" {
  10972. outentry["error_msg"] = a + " 未填或格式错误"
  10973. error++
  10974. queryData = append(queryData, outentry)
  10975. continue
  10976. }
  10977. a = ""
  10978. //校验数字格式
  10979. for _, v := range numParamslist {
  10980. if v == "" {
  10981. continue
  10982. }
  10983. d, ok := outentry[strings.Trim(v, " ")]
  10984. if !ok || d == "" {
  10985. outentry[strings.Trim(v, " ")] = 0
  10986. } else {
  10987. var fl float64
  10988. switch d.(type) {
  10989. case string:
  10990. fl, err = strconv.ParseFloat(d.(string), 64)
  10991. }
  10992. if err != nil || fl < 0 {
  10993. a = strings.Trim(v, " ")
  10994. break
  10995. }
  10996. }
  10997. }
  10998. if a != "" {
  10999. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  11000. error++
  11001. queryData = append(queryData, outentry)
  11002. continue
  11003. }
  11004. err := tx.Begin()
  11005. if _, ok := ftNameList[outentry["配方名称"].(string)]; !ok {
  11006. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where tname = ? ) `, outentry["配方名称"])
  11007. ftNameList[outentry["配方名称"].(string)] = outentry["配方名称"].(string)
  11008. }
  11009. for _, sqlnamestr := range sqlslist {
  11010. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  11011. paramslist := strings.Split(paramslists, ",")
  11012. if len(paramslist) > 0 {
  11013. s_params := make([]interface{}, 0)
  11014. for _, value := range paramslist {
  11015. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  11016. if tempv, exists := c.Get("jwt_username"); exists {
  11017. s_params = append(s_params, tempv.(string))
  11018. } else {
  11019. s_params = append(s_params, "")
  11020. }
  11021. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  11022. s_params = append(s_params, pastureid)
  11023. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  11024. ids, err := setting.SnowIds.NextId()
  11025. if err != nil {
  11026. ids = time.Now().UnixNano()
  11027. logging.Info("create SnowIds err", err)
  11028. }
  11029. s_params = append(s_params, ids)
  11030. } else {
  11031. if outentry[strings.Trim(value, " ")] == nil {
  11032. s_params = append(s_params, "")
  11033. } else {
  11034. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  11035. }
  11036. }
  11037. }
  11038. outentry["input"] = inputdata
  11039. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  11040. if err != nil {
  11041. if tx != nil {
  11042. tx.Rollback()
  11043. }
  11044. if tx != nil {
  11045. tx.Close()
  11046. }
  11047. msg := geterrmsg(err.Error())
  11048. outentry["error_msg"] = msg
  11049. error++
  11050. queryData = append(queryData, outentry)
  11051. isdone = true
  11052. break
  11053. } else {
  11054. if len(returnmsgmap1) > 0 {
  11055. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  11056. if tx != nil {
  11057. tx.Rollback()
  11058. }
  11059. if tx != nil {
  11060. tx.Close()
  11061. }
  11062. msg := geterrmsg(va.(string))
  11063. outentry["error_msg"] = msg
  11064. error++
  11065. queryData = append(queryData, outentry)
  11066. isdone = true
  11067. break
  11068. }
  11069. }
  11070. isdone = false
  11071. }
  11072. }
  11073. }
  11074. ftNames = append(ftNames, outentry["配方名称"])
  11075. switch {
  11076. case err != nil:
  11077. if tx != nil {
  11078. tx.Rollback()
  11079. }
  11080. default:
  11081. if tx != nil {
  11082. err = tx.Commit()
  11083. }
  11084. }
  11085. if tx != nil {
  11086. tx.Close()
  11087. }
  11088. }
  11089. if !isdone {
  11090. ok++
  11091. isdone = true
  11092. }
  11093. }
  11094. go ftSync(ftNames, pastureid)
  11095. data := make(map[string]interface{})
  11096. data["result"] = queryData
  11097. data["success"] = ok
  11098. data["err_count"] = error
  11099. appG.Response(http.StatusOK, e.SUCCESS, data)
  11100. }
  11101. func ftSync(ftNameList []interface{}, pastureId string) {
  11102. tx := restful.Engine.NewSession()
  11103. defer tx.Close()
  11104. for _, ftName := range ftNameList {
  11105. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  11106. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  11107. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  11108. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  11109. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  11110. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  11111. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  11112. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  11113. join feedtemplet ft on ft.id = fp.ftid where ft.tname = ?`, ftName).QueryString()
  11114. FpdBatchEditGrfd(pastureId, values1)
  11115. }
  11116. }
  11117. func CopyFeedtemplet(c *gin.Context) {
  11118. appG := app.Gin{C: c}
  11119. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11120. fsion := gofasion.NewFasion(string(dataByte))
  11121. pastureid := fsion.Get("pastureid").ValueStr()
  11122. newName := fsion.Get("newName").ValueStr()
  11123. id := fsion.Get("id").ValueStr()
  11124. tx := restful.Engine.NewSession()
  11125. defer tx.Close()
  11126. count, err := tx.SQL(` select count(1) from feedtemplet where tname = ? `, newName).Count()
  11127. if err != nil {
  11128. appG.Response(http.StatusOK, e.ERROR, err)
  11129. return
  11130. }
  11131. if count > 0 {
  11132. appG.Response(http.StatusOK, e.ERROR, "配方名称重复!")
  11133. return
  11134. }
  11135. type ftCode struct {
  11136. Tcode string `xorm:"tcode"`
  11137. }
  11138. code := new(ftCode)
  11139. err = tx.SQL(`select if(left((select max(tcode) from feedtemplet where pastureid = ?),8) =
  11140. (select DATE_FORMAT(now(),"%Y%m%d")),(select max(tcode)+1 from feedtemplet where pastureid = ?),
  11141. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))) tcode`, pastureid, pastureid).GetFirst(code).Error
  11142. if err != nil {
  11143. appG.Response(http.StatusOK, e.ERROR, err)
  11144. return
  11145. }
  11146. if code.Tcode == "" {
  11147. appG.Response(http.StatusOK, e.ERROR, "配方编码生产失败!")
  11148. return
  11149. }
  11150. _, err = tx.Exec(`INSERT INTO feedtemplet(pastureid,tname,tcode,tcolor,ccid,ccname,fttype,fttypeid,source,
  11151. remark,enable,sort,volume,autozone)
  11152. select pastureid,?,?,tcolor,ccid,ccname,fttype,fttypeid,source,
  11153. remark,enable,sort,volume,autozone from feedtemplet where id = ? `, newName, code.Tcode, id)
  11154. if err != nil {
  11155. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11156. return
  11157. }
  11158. _, err = tx.Exec(`insert into ftdetail(pastureid,ftid,fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11159. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry)
  11160. select pastureid,(select id from feedtemplet where tcode = ? ),fid,fname,lweight,fweight, islockcount,isfg, sort,feedgroup,preftid, autosecond,
  11161. autosecondname,splitftpreid, deviation, is_modify, is_show, shutdown,is_surplus, dry
  11162. from ftdetail where ftid = ? `, code.Tcode, id)
  11163. if err != nil {
  11164. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("配方生成失败 %v", err))
  11165. return
  11166. }
  11167. appG.Response(http.StatusOK, e.SUCCESS, true)
  11168. }
  11169. func Test(c *gin.Context) {
  11170. appG := app.Gin{C: c}
  11171. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11172. appG.Response(http.StatusOK, e.SUCCESS, string(dataByte))
  11173. }
  11174. func GetPlanDry(c *gin.Context) {
  11175. appG := app.Gin{C: c}
  11176. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11177. fsion := gofasion.NewFasion(string(dataByte))
  11178. date := fsion.Get("date").ValueStr()
  11179. tx := restful.Engine.NewSession()
  11180. defer tx.Close()
  11181. dataList, err := tx.SQL(`SELECT
  11182. t.feedtempletName,
  11183. ifnull(t.feedtempletPrice,0)feedtempletPrice,
  11184. ifnull(t.feedtempletWeight,0)feedtempletWeight,
  11185. ifnull(t.feedtempletDryWeight,0)feedtempletDryWeight,
  11186. t.tmrno,
  11187. t.bname,
  11188. t.barid,
  11189. t.dry,
  11190. t.actualweightminus,
  11191. t.mydate,
  11192. t.pasturename,
  11193. t.endDate,
  11194. t.startDate,
  11195. t.times,
  11196. -- 计算startDate和endDate的中间时间
  11197. ifnull(DATE_FORMAT(
  11198. DATE_ADD(
  11199. t.startDate,
  11200. INTERVAL TIMESTAMPDIFF(SECOND, t.startDate, t.endDate)/2 SECOND
  11201. ),
  11202. '%Y-%m-%d %H:%i:%s'
  11203. ),'') AS midTime
  11204. FROM (
  11205. SELECT
  11206. (SELECT sort FROM downloadedplan WHERE pid = d.pid AND mydate = d.mydate AND lpplantype IN (0,1)) tmrno,
  11207. b.bname,
  11208. b.id barid,
  11209. 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
  11210. JOIN downloadplandtl1 dd1 ON dd.id = dd1.pid
  11211. JOIN feednur fn ON fn.fid = dd1.fid
  11212. WHERE dd.pid = d.pid AND dd.mydate = d.mydate AND lpplantype IN (0,1,4))/100),2) dry,
  11213. 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,
  11214. DATE_FORMAT(d.mydate,'%Y-%m-%d') mydate,
  11215. p.pasture_name pastureName,
  11216. DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endDate,
  11217. DATE_FORMAT(IFNULL(
  11218. (SELECT MAX(intime) FROM downloadplandtl2 d1
  11219. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d1.intime<d2.intime),
  11220. (SELECT MAX(intime) FROM downloadplandtl1_exec de
  11221. WHERE de.date=d2.date AND de.pastureid = d2.pastureid AND de.pid=d2.pid)
  11222. ), '%Y-%m-%d %H:%i:%s') startDate,
  11223. d.times ,
  11224. ( SELECT
  11225. round(SUM(
  11226. IF(ftd.preftid<>0,
  11227. ftd.fweight*IFNULL((SELECT SUM(ftd1.fweight*f1.dry/100)/SUM(ftd1.fweight) FROM ftdetaildate ftd1
  11228. JOIN feednur f1 ON f1.fid= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11229. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11230. ftd.fweight*f.dry/100)) ,2)
  11231. dryweight
  11232. FROM ftdetaildate ftd
  11233. LEFT JOIN feednur f ON f.fid= ftd.fid AND f.pastureid = ftd.pastureid
  11234. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletDryWeight,(
  11235. select
  11236. sum(ftd.fweight)
  11237. FROM ftdetaildate ftd
  11238. WHERE ftd.ftid = d.tempid and ftd.date = d2.date ) feedtempletWeight,
  11239. ( SELECT
  11240. round(SUM(
  11241. IF(ftd.preftid<>0,
  11242. IFNULL((SELECT SUM(ftd1.fweight*f1.uprice) FROM ftdetaildate ftd1
  11243. JOIN feed f1 ON f1.id= ftd1.fid AND f1.pastureid = ftd1.pastureid
  11244. WHERE ftd1.pastureid = ftd.pastureid AND ftd1.ftid = ftd.preftid and ftd1.date = d2.date ),0),
  11245. ftd.fweight*f.uprice)) ,2)
  11246. dryweight
  11247. FROM ftdetaildate ftd
  11248. LEFT JOIN feed f ON f.id= ftd.fid AND f.pastureid = ftd.pastureid
  11249. WHERE ftd.ftid = d.tempid and ftd.date = d2.date )
  11250. feedtempletPrice,d.templetname feedtempletName
  11251. FROM downloadedplan d
  11252. JOIN downloadplandtl2 d2 ON d.id=d2.PID
  11253. JOIN bar b ON b.id = d2.fbarid
  11254. JOIN pasture p ON p.pastureid = d.pastureid
  11255. WHERE d.mydate = DATE_FORMAT(?,'%Y-%m-%d')
  11256. AND d2.type = 0
  11257. AND d.havebutton = 1
  11258. ) t
  11259. WHERE 1=1 `, date).QueryString()
  11260. if err != nil {
  11261. logs.Error(err)
  11262. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11263. return
  11264. }
  11265. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11266. }
  11267. func GetBar(c *gin.Context) {
  11268. appG := app.Gin{C: c}
  11269. tx := restful.Engine.NewSession()
  11270. defer tx.Close()
  11271. pastureinfo := new(udPastureInfo)
  11272. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  11273. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  11274. if err != nil {
  11275. logs.Error(err)
  11276. return
  11277. }
  11278. dataList, err := tx.SQL(` select id,bname from bar where pastureid = ?`, pastureinfo.Pastureid).QueryString()
  11279. if err != nil {
  11280. logs.Error(err)
  11281. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11282. return
  11283. }
  11284. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11285. }
  11286. func GetHomepage(c *gin.Context) {
  11287. appG := app.Gin{C: c}
  11288. tx := restful.Engine.NewSession()
  11289. defer tx.Close()
  11290. dataList, err := tx.SQL(` SELECT
  11291. ifnull((SELECT CONCAT(ROUND(if(SUM(lweight) <= SUM(iweight),SUM(lweight)/SUM(iweight),SUM(iweight)/SUM(lweight))*100,2),'%') yesRateHL
  11292. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11293. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,1) ),'0.00%')yesRateHL, -- 昨日混料准确率
  11294. (SELECT CONCAT(ROUND(SUM(iweight)/SUM(lweight)*100,2),'%') yesRateHL
  11295. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11296. 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日混料准确率
  11297. ifnull((SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11298. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11299. AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d') and dt.lpplantype in(0,2) ),'0.00%')yesRateSL, -- 昨日撒料准确率
  11300. (SELECT CONCAT(ROUND(SUM(oweight)/SUM(lweight)*100,2),'%') yesRateSL
  11301. FROM downloadedplan dt WHERE dt.pastureid = d.pastureid
  11302. 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日撒料准确率
  11303. 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),'%') -- 正确率
  11304. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11305. WHERE dt.pastureid = d.pastureid AND dt.mydate=DATE_FORMAT(DATE_SUB(d.mydate,INTERVAL 1 DAY),'%Y-%m-%d')),'0.00%') yesRateSLR, -- 昨日正确率
  11306. (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),'%') -- 正确率
  11307. FROM downloadedplan dt JOIN downloadplandtl2 de ON dt.id=de.pid AND dt.pastureid = de.pastureid
  11308. WHERE dt.pastureid = d.pastureid
  11309. 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日正确率
  11310. (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,
  11311. (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,
  11312. 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,
  11313. 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,
  11314. ifnull(round(getSLtimeDiffSINGEL(d.pastureid,d.mydate),2),0.00) temtime,
  11315. ifnull(round(getSLtimeDiffMonth(d.pastureid) ,2),0.00) montime
  11316. FROM
  11317. (SELECT (select column_default as pastureid from information_schema.COLUMNS
  11318. 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()
  11319. if err != nil {
  11320. logs.Error(err)
  11321. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11322. return
  11323. }
  11324. dataList1, err := tx.SQL(`select
  11325. 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
  11326. LEFT JOIN ftdetail ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1'
  11327. join feed f on f.id = ifnull(ftd.fid,d1.fid) where d1.date = date_format(now(),'%Y-%m-%d') `).QueryString()
  11328. if err != nil {
  11329. logs.Error(err)
  11330. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11331. return
  11332. }
  11333. for _, data := range dataList {
  11334. for _, data1 := range dataList1 {
  11335. data["totalCost"] = data1["totalCost"]
  11336. data["cost"] = data1["cost"]
  11337. }
  11338. }
  11339. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11340. }
  11341. func GetFeedingManagement(c *gin.Context) {
  11342. appG := app.Gin{C: c}
  11343. typea := c.Query("typea") // 0 栏舍 1 日期
  11344. startDate := c.Query("startdate")
  11345. endDate := c.Query("enddate")
  11346. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11347. // fsion := gofasion.NewFasion(string(dataByte))
  11348. tx := restful.Engine.NewSession()
  11349. defer tx.Close()
  11350. if typea == "0" {
  11351. 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
  11352. SUM(
  11353. 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 ,
  11354. 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)*
  11355. 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 )),
  11356. 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)*
  11357. 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 ))
  11358. )
  11359. )actualweightminus ,
  11360. SUM(
  11361. 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 ,
  11362. 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)*
  11363. 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 )),
  11364. 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)*
  11365. 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 ))
  11366. ) * ifnull(fn.dry,0)
  11367. ) dryweight , SUM(
  11368. 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 ,
  11369. 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)*
  11370. 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 )),
  11371. 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)*
  11372. 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 ))
  11373. ) * ifnull(f.uprice,0)
  11374. ) priceweight
  11375. ,(select ccount from feedpdate where date = d1.date and barid = d2.fbarid) ccount,b.bname
  11376. FROM
  11377. downloadedplan d
  11378. JOIN downloadplandtl2 d2
  11379. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11380. JOIN downloadplandtl1 d1
  11381. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11382. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11383. 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
  11384. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11385. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11386. left join feednur fn on fn.fid = f.id
  11387. WHERE d.mydate BETWEEN ? AND ? GROUP BY d2.fbarid ) t `, startDate, endDate).QueryString()
  11388. if err != nil {
  11389. logs.Error(err)
  11390. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11391. return
  11392. }
  11393. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11394. } else {
  11395. 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
  11396. SUM(
  11397. 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 ,
  11398. 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)*
  11399. 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 )),
  11400. 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)*
  11401. 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 ))
  11402. )
  11403. )actualweightminus ,
  11404. SUM(
  11405. 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 ,
  11406. 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)*
  11407. 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 )),
  11408. 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)*
  11409. 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 ))
  11410. ) * ifnull(fn.dry,0)
  11411. ) dryweight , SUM(
  11412. 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 ,
  11413. 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)*
  11414. 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 )),
  11415. 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)*
  11416. 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 ))
  11417. ) * ifnull(f.uprice,0)
  11418. ) priceweight
  11419. ,(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
  11420. FROM
  11421. downloadedplan d
  11422. JOIN downloadplandtl2 d2
  11423. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  11424. JOIN downloadplandtl1 d1
  11425. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  11426. left join feedtempletdate ftd1 on d1.feedcode = '-1' and ftd1.date = d1.date and ftd1.id = d1.fid
  11427. 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
  11428. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  11429. join feed f on f.id = if(d1.feedcode = '-1' , ftd.fid,d1.fid)
  11430. left join feednur fn on fn.fid = f.id
  11431. WHERE d.mydate BETWEEN ? AND ?
  11432. GROUP BY d.mydate) t `, startDate, endDate).QueryString()
  11433. if err != nil {
  11434. logs.Error(err)
  11435. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11436. return
  11437. }
  11438. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  11439. }
  11440. }
  11441. func GetFpdetailFname(c *gin.Context) {
  11442. appG := app.Gin{C: c}
  11443. // id := c.Query("id")
  11444. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11445. fsion := gofasion.NewFasion(string(dataByte))
  11446. id := fsion.Get("id").ValueDefaultStr("")
  11447. tx := restful.Engine.NewSession()
  11448. defer tx.Close()
  11449. fpdetailFnameList := make([]*models.FpdetailFname, 0)
  11450. err := tx.SQL(` SELECT
  11451. TRIM(ftid)ftid,TRIM(fid)fid,
  11452. IFNULL((SELECT fname FROM feed WHERE pastureid =ftdetail.pastureid AND id = ftdetail.fid),ftdetail. fname) fname,
  11453. fweight,sort,
  11454. TRIM(ftdetail.id) id, fweight /(select sum(fweight) from ftdetail where ftid = (select ftid from feedp where barid = ? ) ) sumFweight
  11455. FROM
  11456. ftdetail
  11457. WHERE ( ftid=(select ftid from feedp where barid = ? )) AND is_show = 1
  11458. ORDER BY ftdetail.sort,ftdetail.id `, id, id).Find(&fpdetailFnameList)
  11459. if err != nil {
  11460. logs.Error(err)
  11461. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11462. return
  11463. }
  11464. fpdetailList := make([]*models.Fpdetail, 0)
  11465. err = tx.SQL(`select id,barid,barname,times,weight from fpdetail where barid = ?`, id).Find(&fpdetailList)
  11466. if err != nil {
  11467. logs.Error(err)
  11468. appG.Response(http.StatusOK, e.ERROR, "查询失败")
  11469. return
  11470. }
  11471. for _, f := range fpdetailFnameList {
  11472. f.FWeight = 0
  11473. for _, fpd := range fpdetailList {
  11474. value := f.SumFWeight * fpd.Weight
  11475. // 将其四舍五入到小数点后两位
  11476. roundedValue := math.Round(value*100) / 100
  11477. if fpd.Times == 1 {
  11478. f.TimesOne = roundedValue
  11479. } else if fpd.Times == 2 {
  11480. f.TimesTwo = roundedValue
  11481. } else if fpd.Times == 3 {
  11482. f.TimesThree = roundedValue
  11483. } else if fpd.Times == 4 {
  11484. f.TimesFour = roundedValue
  11485. } else if fpd.Times == 5 {
  11486. f.TimesFive = roundedValue
  11487. } else if fpd.Times == 6 {
  11488. f.TimesSix = roundedValue
  11489. }
  11490. f.FWeight += value
  11491. }
  11492. }
  11493. fpdetailFname := new(models.FpdetailFname)
  11494. fpdetailFname.FName = "合计"
  11495. for _, f := range fpdetailFnameList {
  11496. fpdetailFname.TimesOne += f.TimesOne
  11497. fpdetailFname.TimesTwo += f.TimesTwo
  11498. fpdetailFname.TimesThree += f.TimesThree
  11499. fpdetailFname.TimesFour += f.TimesFour
  11500. fpdetailFname.TimesFive += f.TimesFive
  11501. fpdetailFname.TimesSix += f.TimesSix
  11502. fpdetailFname.FWeight += f.FWeight
  11503. f.FWeight = RoundFloat(f.FWeight, 2)
  11504. }
  11505. // 在处理代码中
  11506. fpdetailFname.TimesOne = RoundFloat(fpdetailFname.TimesOne, 2)
  11507. fpdetailFname.TimesTwo = RoundFloat(fpdetailFname.TimesTwo, 2)
  11508. fpdetailFname.TimesThree = RoundFloat(fpdetailFname.TimesThree, 2)
  11509. fpdetailFname.TimesFour = RoundFloat(fpdetailFname.TimesFour, 2)
  11510. fpdetailFname.TimesFive = RoundFloat(fpdetailFname.TimesFive, 2)
  11511. fpdetailFname.TimesSix = RoundFloat(fpdetailFname.TimesSix, 2)
  11512. fpdetailFname.FWeight = RoundFloat(fpdetailFname.FWeight, 2)
  11513. fpdetailFnameList = append(fpdetailFnameList, fpdetailFname)
  11514. appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11515. }
  11516. func RoundFloat(x float64, prec int) float64 {
  11517. output := math.Pow(10, float64(prec))
  11518. return math.Round(x*output) / output
  11519. }
  11520. func GetLyUdData(c *gin.Context) {
  11521. appG := app.Gin{C: c}
  11522. // id := c.Query("id")
  11523. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  11524. fsion := gofasion.NewFasion(string(dataByte))
  11525. myDate := fsion.Get("myDate").ValueDefaultStr("")
  11526. times := fsion.Get("Times").ValueDefaultStr("")
  11527. name := fsion.Get("name").ValueDefaultStr("")
  11528. tx := restful.Engine.NewSession()
  11529. defer tx.Close()
  11530. if name == "dateplanlist" {
  11531. 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
  11532. join pasture p on dl.pastureId=p.pastureid JOIN downloadplandtl2 d2 on dl.id=d2.pid and dl.pastureId=d2.pastureId
  11533. where dl.Mydate = ? AND dl.lpplanType =0 and dl.Times= ? GROUP BY dl.id union all
  11534. 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
  11535. from downloadedplan dl join pasture p on dl.pastureId=p.pastureid
  11536. 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
  11537. where dl.Mydate = ? AND dl.lpplanType =2 and dl.Times= ?
  11538. GROUP BY dl.id order by ProjName `, myDate, times, myDate, times).Query().List()
  11539. fmt.Println(err)
  11540. appG.Response(http.StatusOK, e.SUCCESS, data)
  11541. return
  11542. } else if name == "getAddFeed" {
  11543. 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,
  11544. 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,
  11545. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM downloadedplan dd
  11546. JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11547. 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
  11548. join feedtemplet ftd on ftd.id = d.tempid and ftd.pastureId = d.pastureId
  11549. JOIN feed f ON f.id = d1.fid AND f.pastureId = d.pastureId
  11550. WHERE DATE_FORMAT(dd.Mydate ,'%Y-%m-%d' ) = ? and dd.Times =? and d1.type = 0
  11551. 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,
  11552. round(d1.LWEIGHT *(ftdd.fweight / (select sum(fweight) from ftdetaildate where date = ftdd.date and ftid = ftdd.ftid and pastureId = d.pastureId )),2) expWeight,
  11553. 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,
  11554. '' 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,
  11555. DATE_FORMAT(d1.InTime,'%Y-%m-%d %H:%i:%s') endTime FROM
  11556. downloadedplan dd JOIN downloadplandtl1 d1 ON d1.PID = dd.id and d1.pastureId = dd.pastureId
  11557. 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
  11558. join feedtemplet ftd on ftd.id = d1.fid and ftd.pastureId = d.pastureId
  11559. join ftdetaildate ftdd on ftdd.ftid = ftd.id and ftdd.date = d.Mydate and ftdd.pastureId = d.pastureId
  11560. join feed f on f.id = ftdd.fid and f.pastureId = d.pastureId
  11561. 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()
  11562. appG.Response(http.StatusOK, e.SUCCESS, data)
  11563. return
  11564. } else if name == "getDeleteFeed" {
  11565. 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,
  11566. 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 ,
  11567. (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
  11568. ,d2.xxwBarCode as penId,if(d.lpplanType=2,(select id from downloadedplan p where p.pid=d.pid and p.mydate=? and p.Times=?
  11569. and p.lpplanType=1 limit 1),d2.pid) Id from downloadedplan d LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID
  11570. and d.pastureId=d2.pastureId where d.mydate=? AND d.lpplanType in (0,2) and d.Times=?`, myDate, times, myDate, times).Query().List()
  11571. appG.Response(http.StatusOK, e.SUCCESS, data)
  11572. return
  11573. }
  11574. // appG.Response(http.StatusOK, e.SUCCESS, fpdetailFnameList)
  11575. }