db.go 262 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "path"
  12. "regexp"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. "../../pkg/app"
  19. "../../pkg/e"
  20. "../../pkg/logging"
  21. "../../pkg/setting"
  22. "../../routers/restful"
  23. "github.com/360EntSecGroup-Skylar/excelize"
  24. "github.com/Anderson-Lu/gofasion/gofasion"
  25. "github.com/astaxie/beego/logs"
  26. "github.com/gin-gonic/gin"
  27. "github.com/tealeg/xlsx"
  28. "github.com/xormplus/xorm"
  29. )
  30. // @Summary 根据SQL执行得到数据集
  31. // @Tags getData
  32. // @Accept json
  33. // @Produce json
  34. // @Param sql query string true "sql"
  35. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  36. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  37. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  38. // @Router /data/getdata [POST]
  39. func GetData(c *gin.Context) {
  40. appG := app.Gin{C: c}
  41. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  42. fsion := gofasion.NewFasion(string(dataByte))
  43. sqlstr := fsion.Get("sql").ValueStr()
  44. offset := fsion.Get("offset").ValueDefaultInt(0)
  45. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  46. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  47. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  48. if err != nil {
  49. appG.Response(http.StatusOK, e.ERROR, err.Error())
  50. } else {
  51. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  52. }
  53. }
  54. func Testpartitions(c *gin.Context) {
  55. appG := app.Gin{C: c}
  56. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  57. fsion := gofasion.NewFasion(string(dataByte))
  58. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  59. user := fsion.Get("user").ValueStr() //获取新数据库用户
  60. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  61. host := fsion.Get("host").ValueStr() //获取新数据库名称
  62. port := fsion.Get("port").ValueStr() //获取新数据库名称
  63. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  64. if sqls == nil || err1 != nil {
  65. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  66. }
  67. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  68. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  69. mydb, err := sql.Open("mysql", connecting) //连接新连接
  70. if err != nil {
  71. println("err1", err.Error())
  72. }
  73. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  74. if err != nil {
  75. println("err2", err.Error())
  76. }
  77. mydb.Close()
  78. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  79. mydb, err = sql.Open("mysql", connecting)
  80. if err != nil {
  81. println("err3", err.Error())
  82. }
  83. defer mydb.Close()
  84. if err == nil {
  85. mydb.SetMaxOpenConns(10)
  86. mydb.SetMaxIdleConns(10)
  87. }
  88. errmsg := ""
  89. if err == nil {
  90. //tx ,_ :=mydb.Begin()
  91. for _, sqlstr := range sqlstrs {
  92. //println("sqlstr---",sqlstr)
  93. if sqlstr == "" {
  94. continue
  95. }
  96. _, err = mydb.Exec(sqlstr)
  97. if err != nil {
  98. println("err4", err.Error())
  99. errmsg = err.Error()
  100. //err1 :=tx.Rollback()
  101. }
  102. }
  103. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  104. //err =tx.Commit()
  105. }
  106. if errmsg == "" {
  107. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  108. } else {
  109. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  110. }
  111. }
  112. func TestData(c *gin.Context) {
  113. appG := app.Gin{C: c}
  114. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  115. fsion := gofasion.NewFasion(string(dataByte))
  116. sqlstr := fsion.Get("sql").ValueStr()
  117. token := ""
  118. if tempv, exists := c.Get("jwt_username"); exists {
  119. token = tempv.(string)
  120. }
  121. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  122. }
  123. // @Summary 根据APISQL表中SQL执行得到数据集
  124. // @Tags GetDataByName
  125. // @Accept json
  126. // @Produce json
  127. // @Param sqlname body string true "sqlname"
  128. // @Param offset body int true "offset"
  129. // @Param pagecount body int true "pagecount"
  130. // @Param returntype body string true "returntype"
  131. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  132. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  133. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  134. // @Router /data/GetDataByName [POST]
  135. func GetDataByName(c *gin.Context) {
  136. appG := app.Gin{C: c}
  137. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  138. fsion := gofasion.NewFasion(string(dataByte))
  139. sqlnamestr := fsion.Get("name").ValueStr()
  140. offset := fsion.Get("offset").ValueDefaultInt(0)
  141. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  142. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  143. tx := restful.Engine.NewSession()
  144. err := tx.Begin()
  145. defer func() {
  146. switch {
  147. case err != nil:
  148. logging.Error("tx.Begin 事务启动失败__error:", err)
  149. if tx != nil {
  150. tx.Rollback()
  151. }
  152. default:
  153. if tx != nil {
  154. err = tx.Commit()
  155. }
  156. }
  157. if tx != nil {
  158. tx.Close()
  159. }
  160. }()
  161. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  162. if sql != "" {
  163. s_params := make([]interface{}, 0)
  164. if fsion.HasKey("parammaps") {
  165. parammaps := fsion.Get("parammaps")
  166. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  167. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  168. }
  169. paramslist := strings.Split(p, ",")
  170. if len(paramslist) > 0 && p != "" {
  171. for _, value := range paramslist {
  172. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  173. if tempv, exists := c.Get("jwt_username"); exists {
  174. s_params = append(s_params, tempv.(string))
  175. } else {
  176. s_params = append(s_params, "")
  177. }
  178. } else {
  179. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  180. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  181. // tmrNameList := []string{}
  182. // for _, tmr := range tmrArray {
  183. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  184. // }
  185. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  186. // } else {
  187. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  188. // }
  189. }
  190. }
  191. }
  192. } else if fsion.HasKey("params") {
  193. params := fsion.Get("params").Array()
  194. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  195. for _, v_params := range params {
  196. s_params = append(s_params, v_params.ValueStr())
  197. }
  198. }
  199. if returntype == "xlsx" {
  200. var xlsxfile *xlsx.File
  201. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  202. //c.File("c:/dd.xlsx")
  203. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  204. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  205. c.Header("Content-Transfer-Encoding", "binary")
  206. _ = xlsxfile.Write(c.Writer)
  207. } else {
  208. if sqlnamestr == "getHomepageStr" {
  209. parammaps := fsion.Get("parammaps")
  210. pastureid := parammaps.Get("pastureid").ValueStr()
  211. var montimeList []float64
  212. var montime float64
  213. var wg sync.WaitGroup
  214. now := time.Now()
  215. for i := 0; i < 30; i++ {
  216. wg.Add(1)
  217. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  218. go func(nowstr string) {
  219. defer wg.Done()
  220. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  221. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  222. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  223. montimeList = append(montimeList, m)
  224. }(nowstr)
  225. }
  226. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  227. if err != nil {
  228. logging.Error("GetDataByName err: ", err)
  229. msg := geterrmsg(err.Error())
  230. appG.Response(http.StatusOK, e.ERROR, msg)
  231. }
  232. wg.Wait()
  233. for _, m := range montimeList {
  234. montime += m
  235. }
  236. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  237. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  238. return
  239. }
  240. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  241. if err != nil {
  242. logging.Error("GetDataByName err: ", err)
  243. msg := geterrmsg(err.Error())
  244. appG.Response(http.StatusOK, e.ERROR, msg)
  245. } else {
  246. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  247. }
  248. }
  249. } else {
  250. appG.Response(http.StatusOK, e.SUCCESS, nil)
  251. }
  252. }
  253. // @Summary 根据APISQL表中SQL执行得到数据集
  254. // @Tags GetDataByName
  255. // @Accept json
  256. // @Produce json
  257. // @Param sqlname body string true "sqlname"
  258. // @Param offset body int true "offset"
  259. // @Param pagecount body int true "pagecount"
  260. // @Param returntype body string true "returntype"
  261. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  262. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  263. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  264. // @Router /data/GetDataByName [POST]
  265. func GetDataBySqlIN(c *gin.Context) {
  266. appG := app.Gin{C: c}
  267. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  268. fsion := gofasion.NewFasion(string(dataByte))
  269. sqlnamestr := fsion.Get("name").ValueStr()
  270. offset := fsion.Get("offset").ValueDefaultInt(0)
  271. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  272. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  273. tx := restful.Engine.NewSession()
  274. err := tx.Begin()
  275. defer func() {
  276. switch {
  277. case err != nil:
  278. logging.Error("tx.Begin 事务启动失败__error:", err)
  279. if tx != nil {
  280. tx.Rollback()
  281. }
  282. default:
  283. if tx != nil {
  284. err = tx.Commit()
  285. }
  286. }
  287. if tx != nil {
  288. tx.Close()
  289. }
  290. }()
  291. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  292. if sql != "" {
  293. s_params := make([]interface{}, 0)
  294. if fsion.HasKey("parammaps") {
  295. parammaps := fsion.Get("parammaps")
  296. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  297. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  298. }
  299. paramslist := strings.Split(p, ",")
  300. if len(paramslist) > 0 && p != "" {
  301. for _, value := range paramslist {
  302. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  303. if tempv, exists := c.Get("jwt_username"); exists {
  304. s_params = append(s_params, tempv.(string))
  305. } else {
  306. s_params = append(s_params, "")
  307. }
  308. } else {
  309. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  310. }
  311. }
  312. }
  313. } else if fsion.HasKey("params") {
  314. params := fsion.Get("params").Array()
  315. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  316. for _, v_params := range params {
  317. s_params = append(s_params, v_params.ValueStr())
  318. }
  319. }
  320. if returntype == "xlsx" {
  321. var xlsxfile *xlsx.File
  322. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  323. //c.File("c:/dd.xlsx")
  324. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  325. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  326. c.Header("Content-Transfer-Encoding", "binary")
  327. _ = xlsxfile.Write(c.Writer)
  328. } else {
  329. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  330. if err != nil {
  331. logging.Error("GetDataByName err: ", err)
  332. msg := geterrmsg(err.Error())
  333. appG.Response(http.StatusOK, e.ERROR, msg)
  334. } else {
  335. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  336. }
  337. }
  338. } else {
  339. appG.Response(http.StatusOK, e.SUCCESS, nil)
  340. }
  341. }
  342. // 错误处理
  343. // 将报错信息处理成汉字
  344. func geterrmsg(errstr string) (msgstr string) {
  345. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  346. rs := []rune(errstr)
  347. if hzRegexp.MatchString(string(rs[0])) {
  348. msgstr = errstr
  349. return
  350. }
  351. if strings.Contains(errstr, "Duplicate entry") {
  352. strs := strings.Split(errstr, ` key '`)
  353. if len(strs) > 1 {
  354. if len(strs[len(strs)-1]) > 1 {
  355. errstr = "Duplicate entry :" + strs[len(strs)-1]
  356. }
  357. }
  358. }
  359. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  360. if err != nil {
  361. msgstr = errstr
  362. return
  363. }
  364. if msg == nil || len(msg) == 0 {
  365. var param []interface{}
  366. param = append(param, errstr, errstr)
  367. go func() {
  368. tx := restful.Engine.NewSession()
  369. err := tx.Begin()
  370. defer func() {
  371. switch {
  372. case err != nil:
  373. logging.Error("tx.Begin 事务启动失败__error:", err)
  374. if tx != nil {
  375. tx.Rollback()
  376. }
  377. default:
  378. if tx != nil {
  379. err = tx.Commit()
  380. }
  381. }
  382. if tx != nil {
  383. tx.Close()
  384. }
  385. }()
  386. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  387. if err != nil {
  388. logging.Error("insert into err_msg(err,msg) err", err)
  389. }
  390. }()
  391. msgstr = errstr
  392. } else {
  393. msgstr = msg[0]["msg"]
  394. }
  395. return
  396. }
  397. // @Summary 根据APISQL表中SQL执行得到数据集
  398. // @Tags GetDataByNameForm
  399. // @Accept json
  400. // @Produce json
  401. // @Param sqlname body json true "sqlname"
  402. // @Param offset query int true "offset"
  403. // @Param pagecount query int true "pagecount"
  404. // @Param returntype query string true "returntype"
  405. // @Param s formData json true "ss"
  406. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  407. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  408. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  409. // @Router /data/GetDataByNameForm [POST]
  410. func GetDataByNameForm(c *gin.Context) {
  411. appG := app.Gin{C: c}
  412. //sqlnamestr := c.PostForm("measureNumber")
  413. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  414. //fsion := gofasion.NewFasion(string(dataByte))
  415. //sqlnamestr := fsion.Get("name").ValueStr()
  416. //offset := fsion.Get("offset").ValueInt()
  417. //pagecount := fsion.Get("pagecount").ValueInt()
  418. //returntype := fsion.Get("returntype").ValueStr()
  419. //params := fsion.Get("params").Array()
  420. c.Request.ParseForm()
  421. params := c.Request.Form
  422. offset := 0
  423. pageSize_ := 0
  424. returntype := params.Get("page")
  425. if returntype == "" {
  426. returntype = "0"
  427. }
  428. if tempv, exists := c.Get("jwt_username"); exists {
  429. params.Set("JwtUserName", tempv.(string))
  430. } else {
  431. params.Set("JwtUserName", "")
  432. }
  433. sqlnamestr := params.Get("name")
  434. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  435. s_params := make([]interface{}, 0)
  436. if returntype == "1" {
  437. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  438. if error != nil {
  439. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  440. }
  441. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  442. if error != nil {
  443. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  444. }
  445. pageSize_ = pageSize
  446. offset = pageNum
  447. }
  448. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  449. paramslist := strings.Split(p, ",")
  450. if len(paramslist) > 0 && p != "" {
  451. for _, value := range paramslist {
  452. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  453. }
  454. }
  455. if sql != "" {
  456. if returntype == "xlsx" {
  457. var xlsxfile *xlsx.File
  458. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  459. c.Header("Content-Type", "application/octet-stream")
  460. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  461. c.Header("Content-Transfer-Encoding", "binary")
  462. _ = xlsxfile.Write(c.Writer)
  463. } else {
  464. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  465. if err != nil {
  466. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  467. } else {
  468. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  469. }
  470. }
  471. } else {
  472. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  473. }
  474. }
  475. // @Summary 递归获取所有
  476. // @Tags menu
  477. // @Accept json
  478. // @Produce json
  479. // @Param Ton query string true "Ton"
  480. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  481. // @Router /authdata/GetRoleMenus [GET]
  482. func GetRecuDataByName(c *gin.Context) {
  483. appG := app.Gin{C: c}
  484. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  485. fsion := gofasion.NewFasion(string(dataByte))
  486. sqlnamestr := fsion.Get("name").ValueStr()
  487. parentidname := fsion.Get("idname").ValueStr()
  488. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  489. params := make(map[string]interface{})
  490. s_params := make([]interface{}, 0)
  491. if fsion.HasKey("params") {
  492. for _, v_params := range fsion.Get("params").Array() {
  493. s_params = append(s_params, v_params.ValueStr())
  494. }
  495. params["params"] = s_params
  496. } else {
  497. jparams := fsion.Get("parammaps")
  498. paramslist := strings.Split(p, ",")
  499. if len(paramslist) > 0 && p != "" {
  500. for _, value := range paramslist {
  501. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  502. if tempv, exists := c.Get("jwt_username"); exists {
  503. params[value] = tempv.(string)
  504. } else {
  505. params[value] = ""
  506. }
  507. } else {
  508. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  509. }
  510. }
  511. }
  512. }
  513. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  514. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  515. if err != nil {
  516. appG.Response(http.StatusOK, e.ERROR, err.Error())
  517. }
  518. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  519. }
  520. // @Summary 根据APISQL表中SQL执行得到数据集
  521. // @Tags GetDataByNames
  522. // @Accept json
  523. // @Produce json
  524. // @RequestBody sqlname query string true "sqlname"
  525. // @Param offset query int true "offset"
  526. // @Param pagecount query int true "pagecount"
  527. // @Param returntype query string true "returntype"
  528. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  529. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  530. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  531. // @Router /data/GetDataByNames [POST]
  532. func GetDataByNames(c *gin.Context) {
  533. appG := app.Gin{C: c}
  534. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  535. fsion := gofasion.NewFasion(string(dataByte))
  536. sqlParams := fsion.Array()
  537. queryData := make(map[string]interface{})
  538. for _, v := range sqlParams {
  539. fsion2 := gofasion.NewFasion(v.Json())
  540. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  541. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  542. if sql == "" {
  543. errorm := make(map[string]interface{})
  544. errorm["code"] = e.ERROR
  545. errorm["message"] = "sql没找到"
  546. queryData[fsion2.Get("name").ValueStr()] = errorm
  547. continue
  548. } else if sql != "" {
  549. offset := fsion2.Get("offset").ValueInt()
  550. pagecount := fsion2.Get("pagecount").ValueInt()
  551. returntype := fsion2.Get("returntype").ValueStr()
  552. s_params := make([]interface{}, 0)
  553. if fsion2.HasKey("parammaps") {
  554. parammaps := fsion2.Get("parammaps")
  555. paramslist := strings.Split(p, ",")
  556. if len(paramslist) > 0 && p != "" {
  557. for _, value := range paramslist {
  558. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  559. if tempv, exists := c.Get("jwt_username"); exists {
  560. s_params = append(s_params, tempv.(string))
  561. } else {
  562. s_params = append(s_params, "")
  563. }
  564. } else {
  565. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  566. }
  567. }
  568. }
  569. } else if fsion2.HasKey("params") {
  570. params := fsion2.Get("params").Array()
  571. for _, v_params := range params {
  572. s_params = append(s_params, v_params.ValueStr())
  573. }
  574. }
  575. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  576. if err != nil {
  577. errorm := make(map[string]interface{})
  578. errorm["code"] = e.ERROR
  579. errorm["message"] = err.Error()
  580. queryData[fsion2.Get("name").ValueStr()] = errorm
  581. logging.Error("GetDataByNames err: ", err)
  582. continue
  583. } else {
  584. queryData[fsion2.Get("name").ValueStr()] = queryData1
  585. }
  586. }
  587. }
  588. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  589. }
  590. // @Summary 根据APISQL表中SQL执行得到数据集
  591. // @Tags PostDataByNameForm
  592. // @Accept json
  593. // @Produce json
  594. // @Param sqlname query string true "sqlname"
  595. // @Param offset query int true "offset"
  596. // @Param pagecount query int true "pagecount"
  597. // @Param returntype query string true "returntype"
  598. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  599. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  600. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  601. // @Router /data/PostDataByNameForm [POST]
  602. func PostDataByNameForm(c *gin.Context) {
  603. appG := app.Gin{C: c}
  604. c.Request.ParseForm()
  605. params := c.Request.Form
  606. sqlnamestr := params.Get("name")
  607. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  608. s_params := make([]interface{}, 0)
  609. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  610. paramslist := strings.Split(p, ",")
  611. if len(paramslist) > 0 {
  612. for _, value := range paramslist {
  613. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  614. }
  615. }
  616. if sql != "" {
  617. queryData, err := execDataBySql(sql, s_params)
  618. if err != nil {
  619. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  620. } else {
  621. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  622. }
  623. } else {
  624. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  625. }
  626. }
  627. // @Summary 将数据集转换格式
  628. // @Tags PostDataByNameForm
  629. // @Accept json
  630. // @Produce json
  631. // @Param sqlname query string true "sqlname"
  632. // @Param offset query int true "offset"
  633. // @Param pagecount query int true "pagecount"
  634. // @Param returntype query string true "returntype"
  635. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  636. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  637. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  638. func GetReportform(c *gin.Context) {
  639. appG := app.Gin{C: c}
  640. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  641. fsion := gofasion.NewFasion(string(dataByte))
  642. sqlnamestr := fsion.Get("name").ValueStr()
  643. checked := fsion.Get("checked").ValueStr()
  644. offset := fsion.Get("offset").ValueDefaultInt(0)
  645. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  646. parammaps := fsion.Get("parammaps")
  647. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  648. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  649. tx := restful.Engine.NewSession()
  650. err := tx.Begin()
  651. defer func() {
  652. switch {
  653. case err != nil:
  654. if tx != nil {
  655. tx.Rollback()
  656. }
  657. default:
  658. if tx != nil {
  659. err = tx.Commit()
  660. }
  661. }
  662. if tx != nil {
  663. tx.Close()
  664. }
  665. }()
  666. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea)
  667. if err != nil {
  668. appG.Response(http.StatusOK, e.ERROR, err.Error())
  669. } else {
  670. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  671. }
  672. }
  673. //保养计划
  674. func GetUpkeepPlan(c *gin.Context) {
  675. appG := app.Gin{C: c}
  676. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  677. fsion := gofasion.NewFasion(string(dataByte))
  678. sqlnamestr := fsion.Get("name").ValueStr()
  679. offset := fsion.Get("offset").ValueDefaultInt(0)
  680. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  681. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  682. month := fsion.Get("month").ValueDefaultStr("map")
  683. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  684. tx := restful.Engine.NewSession()
  685. err := tx.Begin()
  686. defer func() {
  687. switch {
  688. case err != nil:
  689. if tx != nil {
  690. tx.Rollback()
  691. }
  692. default:
  693. if tx != nil {
  694. err = tx.Commit()
  695. }
  696. }
  697. if tx != nil {
  698. tx.Close()
  699. }
  700. }()
  701. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  702. if sql != "" {
  703. s_params := make([]interface{}, 0)
  704. if fsion.HasKey("parammaps") {
  705. parammaps := fsion.Get("parammaps")
  706. paramslist := strings.Split(p, ",")
  707. if len(paramslist) > 0 && p != "" {
  708. for _, value := range paramslist {
  709. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  710. if tempv, exists := c.Get("jwt_username"); exists {
  711. s_params = append(s_params, tempv.(string))
  712. } else {
  713. s_params = append(s_params, "")
  714. }
  715. } else {
  716. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  717. }
  718. }
  719. }
  720. } else if fsion.HasKey("params") {
  721. params := fsion.Get("params").Array()
  722. for _, v_params := range params {
  723. s_params = append(s_params, v_params.ValueStr())
  724. }
  725. }
  726. if returntype == "xlsx" {
  727. var xlsxfile *xlsx.File
  728. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  729. //c.File("c:/dd.xlsx")
  730. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  731. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  732. c.Header("Content-Transfer-Encoding", "binary")
  733. _ = xlsxfile.Write(c.Writer)
  734. } else {
  735. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  736. if err != nil {
  737. appG.Response(http.StatusOK, e.ERROR, err.Error())
  738. } else {
  739. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  740. if v, ok := value["id"]; ok {
  741. //month = "2020-03"
  742. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  743. if seviceplans != nil {
  744. for _, va := range seviceplans { //根据保养计划获取保养单
  745. //day,_ :=strconv.Atoi(va["day"])
  746. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  747. //buk := make(map[string]map[string]string)
  748. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  749. jstr := ""
  750. if bu["plantime"][8:9] == "0" {
  751. jstr = "m" + bu["plantime"][9:]
  752. } else {
  753. jstr = "m" + bu["plantime"][8:]
  754. }
  755. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  756. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  757. } else {
  758. if bu["flowCompeleted"] >= "2" {
  759. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  760. } else {
  761. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  762. }
  763. }
  764. }
  765. }
  766. }
  767. }
  768. }
  769. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  770. }
  771. }
  772. } else {
  773. appG.Response(http.StatusOK, e.SUCCESS, nil)
  774. }
  775. }
  776. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  777. // todo 优化性能 children统一查询
  778. // @Tags PostDataByNameForm
  779. // @Accept json
  780. // @Produce json
  781. // @Param sqlname query string true "sqlname"
  782. // @Param offset query int true "offset"
  783. // @Param pagecount query int true "pagecount"
  784. // @Param returntype query string true "returntype"
  785. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  786. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  787. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  788. func GetArrList(c *gin.Context) {
  789. appG := app.Gin{C: c}
  790. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  791. fsion := gofasion.NewFasion(string(dataByte))
  792. sqlnamestr := fsion.Get("name").ValueStr()
  793. sqlnamestr1 := fsion.Get("name1").ValueStr()
  794. offset := fsion.Get("offset").ValueDefaultInt(0)
  795. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  796. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  797. month := fsion.Get("month").ValueDefaultStr("map")
  798. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  799. tx := restful.Engine.NewSession()
  800. err := tx.Begin()
  801. defer func() {
  802. switch {
  803. case err != nil:
  804. if tx != nil {
  805. tx.Rollback()
  806. }
  807. default:
  808. if tx != nil {
  809. err = tx.Commit()
  810. }
  811. }
  812. if tx != nil {
  813. tx.Close()
  814. }
  815. }()
  816. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  817. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  818. if sql != "" {
  819. s_params := make([]interface{}, 0)
  820. if fsion.HasKey("parammaps") {
  821. parammaps := fsion.Get("parammaps")
  822. paramslist := strings.Split(p, ",")
  823. if len(paramslist) > 0 && p != "" {
  824. for _, value := range paramslist {
  825. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  826. if tempv, exists := c.Get("jwt_username"); exists {
  827. s_params = append(s_params, tempv.(string))
  828. } else {
  829. s_params = append(s_params, "")
  830. }
  831. } else {
  832. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  833. }
  834. }
  835. }
  836. }
  837. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  838. if err != nil {
  839. appG.Response(http.StatusOK, e.ERROR, err.Error())
  840. } else {
  841. paramslist1 := strings.Split(p1, ",")
  842. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  843. s_params1 := make([]interface{}, 0)
  844. if len(paramslist1) > 0 && p1 != "" {
  845. for _, v := range paramslist1 {
  846. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  847. }
  848. }
  849. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  850. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  851. }
  852. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  853. }
  854. } else {
  855. appG.Response(http.StatusOK, e.SUCCESS, nil)
  856. }
  857. }
  858. func GetAccount(c *gin.Context) {
  859. appG := app.Gin{C: c}
  860. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  861. fsion := gofasion.NewFasion(string(dataByte))
  862. sqlnamestr := fsion.Get("name").ValueStr()
  863. offset := fsion.Get("offset").ValueDefaultInt(0)
  864. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  865. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  866. tx := restful.Engine.NewSession()
  867. err := tx.Begin()
  868. defer func() {
  869. switch {
  870. case err != nil:
  871. logging.Error("tx.Begin 事务启动失败__error:", err)
  872. if tx != nil {
  873. tx.Rollback()
  874. }
  875. default:
  876. if tx != nil {
  877. err = tx.Commit()
  878. }
  879. }
  880. if tx != nil {
  881. tx.Close()
  882. }
  883. }()
  884. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  885. if sql != "" {
  886. s_params := make([]interface{}, 0)
  887. if fsion.HasKey("parammaps") {
  888. parammaps := fsion.Get("parammaps")
  889. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  890. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  891. }
  892. paramslist := strings.Split(p, ",")
  893. if len(paramslist) > 0 && p != "" {
  894. for _, value := range paramslist {
  895. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  896. if tempv, exists := c.Get("jwt_username"); exists {
  897. s_params = append(s_params, tempv.(string))
  898. } else {
  899. s_params = append(s_params, "")
  900. }
  901. } else {
  902. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  903. }
  904. }
  905. }
  906. } else if fsion.HasKey("params") {
  907. params := fsion.Get("params").Array()
  908. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  909. for _, v_params := range params {
  910. s_params = append(s_params, v_params.ValueStr())
  911. }
  912. }
  913. if returntype == "xlsx" {
  914. var xlsxfile *xlsx.File
  915. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  916. //c.File("c:/dd.xlsx")
  917. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  918. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  919. c.Header("Content-Transfer-Encoding", "binary")
  920. _ = xlsxfile.Write(c.Writer)
  921. } else {
  922. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  923. if err != nil {
  924. logging.Error("GetDataByName err: ", err)
  925. msg := geterrmsg(err.Error())
  926. appG.Response(http.StatusOK, e.ERROR, msg)
  927. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  928. } else {
  929. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  930. }
  931. }
  932. } else {
  933. appG.Response(http.StatusOK, e.SUCCESS, nil)
  934. }
  935. }
  936. // @Summary 根据APISQL表中SQL执行得到数据集
  937. // @Tags PostDataByName
  938. // @Accept json
  939. // @Produce json
  940. // @Param sqlname query string true "sqlname"
  941. // @Param offset query int true "offset"
  942. // @Param pagecount query int true "pagecount"
  943. // @Param returntype query string true "returntype"
  944. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  945. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  946. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  947. // @Router /data/PostDataByName [POST]
  948. func PostDataByName(c *gin.Context) {
  949. appG := app.Gin{C: c}
  950. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  951. fsion := gofasion.NewFasion(string(dataByte))
  952. sqlnamestr := fsion.Get("name").ValueStr()
  953. s_params := make([]interface{}, 0)
  954. tx := restful.Engine.NewSession()
  955. err := tx.Begin()
  956. defer func() {
  957. switch {
  958. case err != nil:
  959. if tx != nil {
  960. tx.Rollback()
  961. }
  962. default:
  963. if tx != nil {
  964. err = tx.Commit()
  965. }
  966. }
  967. if tx != nil {
  968. tx.Close()
  969. }
  970. }()
  971. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  972. if sql != "" {
  973. if fsion.HasKey("parammaps") {
  974. parammaps := fsion.Get("parammaps")
  975. logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  976. paramslist := strings.Split(p, ",")
  977. if len(paramslist) > 0 && p != "" {
  978. for _, value := range paramslist {
  979. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  980. if tempv, exists := c.Get("jwt_username"); exists {
  981. s_params = append(s_params, tempv.(string))
  982. } else {
  983. s_params = append(s_params, "")
  984. }
  985. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  986. ids, err := setting.SnowIds.NextId()
  987. if err != nil {
  988. ids = time.Now().UnixNano()
  989. logging.Info("create SnowIds err", err)
  990. }
  991. s_params = append(s_params, ids)
  992. } else {
  993. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  994. }
  995. }
  996. }
  997. } else if fsion.HasKey("params") {
  998. params := fsion.Get("params").Array()
  999. logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  1000. //ids,err := setting.SnowIds.NextId()
  1001. //if err !=nil{
  1002. // ids = time.Now().UnixNano()
  1003. // logging.Info("create SnowIds err",err)
  1004. //}
  1005. //s_params = append(s_params, ids)
  1006. for _, v_params := range params {
  1007. s_params = append(s_params, v_params.ValueStr())
  1008. }
  1009. }
  1010. queryData, err := execDataBySqlT(sql, s_params, tx)
  1011. if err != nil {
  1012. logging.Error("PostDataByName err: ", err)
  1013. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1014. if (sqlnamestr == "copybarfeedremain" || sqlnamestr == "copyFtdry" || sqlnamestr == "copyPennsieve") &&
  1015. strings.Contains(err.Error(), "Duplicate entry") {
  1016. appG.Response(http.StatusOK, e.ERROR, "同一栏舍,同一班次不可重复录入")
  1017. } else if (sqlnamestr == "copybarmilk" || sqlnamestr == "copyBodyscore" || sqlnamestr == "copyDungsieve" || sqlnamestr == "copyDungscore") &&
  1018. strings.Contains(err.Error(), "Duplicate entry") {
  1019. appG.Response(http.StatusOK, e.ERROR, "同一栏舍不可重复录入")
  1020. } else {
  1021. msg := geterrmsg(err.Error())
  1022. appG.Response(http.StatusOK, e.ERROR, msg)
  1023. }
  1024. } else {
  1025. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1026. }
  1027. } else {
  1028. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1029. }
  1030. }
  1031. //人脸识别/格润富德接口
  1032. func GetRJSBData(c *gin.Context) {
  1033. appG := app.Gin{C: c}
  1034. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1035. fsion := gofasion.NewFasion(string(dataByte))
  1036. sqlnamestr := fsion.Get("name").ValueStr()
  1037. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1038. offset := fsion.Get("offset").ValueDefaultInt(0)
  1039. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1040. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1041. month := fsion.Get("month").ValueDefaultStr("map")
  1042. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1043. tx := restful.Engine.NewSession()
  1044. err := tx.Begin()
  1045. defer func() {
  1046. switch {
  1047. case err != nil:
  1048. if tx != nil {
  1049. tx.Rollback()
  1050. }
  1051. default:
  1052. if tx != nil {
  1053. err = tx.Commit()
  1054. }
  1055. }
  1056. if tx != nil {
  1057. tx.Close()
  1058. }
  1059. }()
  1060. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1061. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1062. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1063. if sql != "" {
  1064. s_params := make([]interface{}, 0)
  1065. if fsion.HasKey("parammaps") {
  1066. parammaps := fsion.Get("parammaps")
  1067. paramslist := strings.Split(p, ",")
  1068. if len(paramslist) > 0 && p != "" {
  1069. for _, value := range paramslist {
  1070. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1071. if tempv, exists := c.Get("jwt_username"); exists {
  1072. s_params = append(s_params, tempv.(string))
  1073. } else {
  1074. s_params = append(s_params, "")
  1075. }
  1076. } else {
  1077. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1078. }
  1079. }
  1080. }
  1081. }
  1082. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1083. if err != nil {
  1084. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1085. } else {
  1086. paramslist1 := strings.Split(p1, ",")
  1087. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1088. s_params1 := make([]interface{}, 0)
  1089. if len(paramslist1) > 0 && p1 != "" {
  1090. for _, v := range paramslist1 {
  1091. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1092. }
  1093. }
  1094. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1095. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1096. }
  1097. // var wg sync.WaitGroup
  1098. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1099. // wg.Add(1)
  1100. // go func(value map[string]interface{}) {
  1101. // defer wg.Done()
  1102. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1103. // }(value)
  1104. // }
  1105. // wg.Wait()
  1106. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1107. }
  1108. } else {
  1109. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1110. }
  1111. }
  1112. func PostRJSBData(c *gin.Context) {
  1113. appG := app.Gin{C: c}
  1114. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1115. fsion := gofasion.NewFasion(string(dataByte))
  1116. logging.Info("PostRJSBData err: ", string(dataByte))
  1117. s_params := make([]interface{}, 0)
  1118. tx := restful.Engine.NewSession()
  1119. err := tx.Begin()
  1120. defer func() {
  1121. switch {
  1122. case err != nil:
  1123. if tx != nil {
  1124. tx.Rollback()
  1125. }
  1126. default:
  1127. if tx != nil {
  1128. err = tx.Commit()
  1129. }
  1130. }
  1131. if tx != nil {
  1132. tx.Close()
  1133. }
  1134. }()
  1135. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1136. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1137. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1138. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1139. if !fsion.HasKey("parammaps") {
  1140. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1141. return
  1142. }
  1143. parammaps := fsion.Get("parammaps")
  1144. paramslist := strings.Split(p, ",")
  1145. if len(paramslist) > 0 && p != "" {
  1146. for _, value := range paramslist {
  1147. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1148. }
  1149. }
  1150. _, err = tx.SQL(sql, s_params...).Execute()
  1151. if err != nil {
  1152. logging.Error("PostRJSBData err: ", err)
  1153. msg := geterrmsg(err.Error())
  1154. appG.Response(http.StatusOK, e.ERROR, msg)
  1155. return
  1156. }
  1157. s_params = make([]interface{}, 0)
  1158. paramslist = strings.Split(p1, ",")
  1159. if len(paramslist) > 0 && p1 != "" {
  1160. for _, value := range paramslist {
  1161. // if value == "ID" {
  1162. // id := parammaps.Get("ID").ValueStr()
  1163. // pastureid := parammaps.Get("pastureid").ValueStr()
  1164. // 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
  1165. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1166. // if err != nil {
  1167. // logging.Error("PostRJSBData err: ", err)
  1168. // msg := geterrmsg(err.Error())
  1169. // appG.Response(http.StatusOK, e.ERROR, msg)
  1170. // return
  1171. // }
  1172. // for _, item := range datalist {
  1173. // id = item["id"]
  1174. // }
  1175. // s_params = append(s_params, id)
  1176. // } else {
  1177. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1178. // }
  1179. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1180. }
  1181. }
  1182. _, err = tx.SQL(sql1, s_params...).Execute()
  1183. if err != nil {
  1184. logging.Error("PostRJSBData1 err: ", err)
  1185. msg := geterrmsg(err.Error())
  1186. appG.Response(http.StatusOK, e.ERROR, msg)
  1187. return
  1188. }
  1189. s_params = make([]interface{}, 0)
  1190. paramslist = strings.Split(p2, ",")
  1191. if len(paramslist) > 0 && p2 != "" {
  1192. for _, value := range paramslist {
  1193. if value == "ID" {
  1194. id := parammaps.Get("ID").ValueStr()
  1195. pastureid := parammaps.Get("pastureid").ValueStr()
  1196. 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
  1197. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1198. if err != nil {
  1199. logging.Error("PostRJSBData err: ", err)
  1200. msg := geterrmsg(err.Error())
  1201. appG.Response(http.StatusOK, e.ERROR, msg)
  1202. return
  1203. }
  1204. for _, item := range datalist {
  1205. id = item["id"]
  1206. }
  1207. s_params = append(s_params, id)
  1208. } else {
  1209. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1210. }
  1211. }
  1212. }
  1213. _, err = tx.SQL(sql2, s_params...).Execute()
  1214. if err != nil {
  1215. logging.Error("PostRJSBData2 err: ", err)
  1216. msg := geterrmsg(err.Error())
  1217. appG.Response(http.StatusOK, e.ERROR, msg)
  1218. return
  1219. }
  1220. s_params = make([]interface{}, 0)
  1221. paramslist = strings.Split(p3, ",")
  1222. if len(paramslist) > 0 && p3 != "" {
  1223. for _, value := range paramslist {
  1224. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1225. }
  1226. }
  1227. _, err = tx.SQL(sql3, s_params...).Execute()
  1228. if err != nil {
  1229. logging.Error("PostRJSBData3 err: ", err)
  1230. msg := geterrmsg(err.Error())
  1231. appG.Response(http.StatusOK, e.ERROR, msg)
  1232. return
  1233. }
  1234. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1235. }
  1236. func PostRJSBDatas(c *gin.Context) {
  1237. appG := app.Gin{C: c}
  1238. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1239. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1240. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1241. tx := restful.Engine.NewSession()
  1242. err := tx.Begin()
  1243. defer func() {
  1244. switch {
  1245. case err != nil:
  1246. if tx != nil {
  1247. tx.Rollback()
  1248. }
  1249. default:
  1250. if tx != nil {
  1251. err = tx.Commit()
  1252. }
  1253. }
  1254. if tx != nil {
  1255. tx.Close()
  1256. }
  1257. }()
  1258. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1259. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1260. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1261. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1262. for _, fsion := range fsions {
  1263. if !fsion.HasKey("parammaps") {
  1264. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1265. return
  1266. }
  1267. parammaps := fsion.Get("parammaps")
  1268. s_params := make([]interface{}, 0)
  1269. paramslist := strings.Split(p, ",")
  1270. if len(paramslist) > 0 && p != "" {
  1271. for _, value := range paramslist {
  1272. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1273. }
  1274. }
  1275. _, err = tx.SQL(sql, s_params...).Execute()
  1276. if err != nil {
  1277. logging.Error("PostRJSBData err: ", err)
  1278. msg := geterrmsg(err.Error())
  1279. appG.Response(http.StatusOK, e.ERROR, msg)
  1280. return
  1281. }
  1282. s_params = make([]interface{}, 0)
  1283. paramslist = strings.Split(p1, ",")
  1284. if len(paramslist) > 0 && p1 != "" {
  1285. for _, value := range paramslist {
  1286. // if value == "ID" {
  1287. // id := parammaps.Get("ID").ValueStr()
  1288. // pastureid := parammaps.Get("pastureid").ValueStr()
  1289. // datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  1290. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1291. // if err != nil {
  1292. // logging.Error("PostRJSBData err: ", err)
  1293. // msg := geterrmsg(err.Error())
  1294. // appG.Response(http.StatusOK, e.ERROR, msg)
  1295. // return
  1296. // }
  1297. // for _, item := range datalist {
  1298. // id = item["id"]
  1299. // }
  1300. // s_params = append(s_params, id)
  1301. // } else {
  1302. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1303. // }
  1304. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1305. }
  1306. }
  1307. _, err = tx.SQL(sql1, s_params...).Execute()
  1308. if err != nil {
  1309. logging.Error("PostRJSBData1 err: ", err)
  1310. msg := geterrmsg(err.Error())
  1311. appG.Response(http.StatusOK, e.ERROR, msg)
  1312. return
  1313. }
  1314. s_params = make([]interface{}, 0)
  1315. paramslist = strings.Split(p2, ",")
  1316. if len(paramslist) > 0 && p2 != "" {
  1317. for _, value := range paramslist {
  1318. if value == "ID" {
  1319. id := parammaps.Get("ID").ValueStr()
  1320. pastureid := parammaps.Get("pastureid").ValueStr()
  1321. 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
  1322. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1323. if err != nil {
  1324. logging.Error("PostRJSBData err: ", err)
  1325. msg := geterrmsg(err.Error())
  1326. appG.Response(http.StatusOK, e.ERROR, msg)
  1327. return
  1328. }
  1329. for _, item := range datalist {
  1330. id = item["id"]
  1331. }
  1332. s_params = append(s_params, id)
  1333. } else {
  1334. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1335. }
  1336. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1337. }
  1338. }
  1339. _, err = tx.SQL(sql2, s_params...).Execute()
  1340. if err != nil {
  1341. logging.Error("PostRJSBData2 err: ", err)
  1342. msg := geterrmsg(err.Error())
  1343. appG.Response(http.StatusOK, e.ERROR, msg)
  1344. return
  1345. }
  1346. s_params = make([]interface{}, 0)
  1347. paramslist = strings.Split(p3, ",")
  1348. if len(paramslist) > 0 && p3 != "" {
  1349. for _, value := range paramslist {
  1350. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1351. }
  1352. }
  1353. _, err = tx.SQL(sql3, s_params...).Execute()
  1354. if err != nil {
  1355. logging.Error("PostRJSBData3 err: ", err)
  1356. msg := geterrmsg(err.Error())
  1357. appG.Response(http.StatusOK, e.ERROR, msg)
  1358. return
  1359. }
  1360. }
  1361. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1362. }
  1363. // @Summary 根据APISQL表中SQL执行得到数据集
  1364. // @Tags ExecDataByConfig
  1365. // @Accept json
  1366. // @Produce json
  1367. // @Param sqlname query string true "sqlname"
  1368. // @Param offset query int true "offset"
  1369. // @Param pagecount query int true "pagecount"
  1370. // @Param returntype query string true "returntype"
  1371. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1372. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1373. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1374. // @Router /data/PostDataByName [POST]
  1375. func ExecDataByConfig(c *gin.Context) {
  1376. appG := app.Gin{C: c}
  1377. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1378. tempval_ := make(map[string]interface{})
  1379. tempCommon := make(map[string]interface{})
  1380. tempval := make([]map[string]interface{}, 0)
  1381. err := json.Unmarshal(dataByte, &tempval_)
  1382. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1383. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1384. if err != nil {
  1385. } else {
  1386. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1387. tempCommon = v
  1388. }
  1389. if v, ok := tempval_["data"].([]interface{}); ok {
  1390. for _, Tvalue := range v {
  1391. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1392. tempval = append(tempval, v1)
  1393. }
  1394. }
  1395. }
  1396. tx := restful.Engine.NewSession()
  1397. err := tx.Begin()
  1398. if err != nil {
  1399. logging.Error("tx.Begin 事务启动失败__error:", err)
  1400. }
  1401. defer func() {
  1402. switch {
  1403. case err != nil:
  1404. if tx != nil {
  1405. tx.Rollback()
  1406. }
  1407. default:
  1408. if tx != nil {
  1409. err = tx.Commit()
  1410. }
  1411. }
  1412. if tx != nil {
  1413. tx.Close()
  1414. }
  1415. }()
  1416. if err == nil {
  1417. if tempv, exists := c.Get("jwt_username"); exists {
  1418. tempCommon["jwt_username"] = tempv.(string)
  1419. }
  1420. for _, paramvalue := range tempval {
  1421. fmt.Println(paramvalue["name"])
  1422. if paramvalue["name"].(string) == "updateBigFP" {
  1423. err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
  1424. if err != nil {
  1425. msg := geterrmsg(err.Error())
  1426. appG.Response(http.StatusOK, e.ERROR, msg)
  1427. return
  1428. }
  1429. }
  1430. }
  1431. for _, paramvalue := range tempval {
  1432. if _, ok := paramvalue["resultname"]; !ok {
  1433. paramvalue["resultname"] = paramvalue["name"]
  1434. }
  1435. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1436. if err != nil {
  1437. logging.Error("ExecDataParam error:", err)
  1438. break
  1439. }
  1440. }
  1441. if err == nil {
  1442. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1443. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1444. } else {
  1445. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1446. }
  1447. } else {
  1448. msg := geterrmsg(err.Error())
  1449. appG.Response(http.StatusOK, e.ERROR, msg)
  1450. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1451. }
  1452. }
  1453. }
  1454. if err != nil {
  1455. msg := geterrmsg(err.Error())
  1456. appG.Response(http.StatusOK, e.ERROR, msg)
  1457. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1458. }
  1459. }
  1460. func interfacetostring(val interface{}) string {
  1461. switch val.(type) {
  1462. case string:
  1463. ss := val.(string)
  1464. return ss
  1465. break
  1466. case int:
  1467. ss := val.(int)
  1468. return strconv.Itoa(ss)
  1469. break
  1470. case int64:
  1471. ss := val.(int64)
  1472. return strconv.FormatInt(ss, 10)
  1473. break
  1474. case float64:
  1475. ss := val.(float64)
  1476. return strconv.FormatFloat(ss, 'E', -1, 32)
  1477. break
  1478. }
  1479. return ""
  1480. }
  1481. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1482. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1483. tempstrb := strings.IndexAny(valuestring, "@")
  1484. tempstre := strings.IndexAny(valuestring, ".")
  1485. if tempstrb > -1 && tempstre > -1 {
  1486. for _, ParamMapList := range ParamMap {
  1487. if v, ok := ParamMapList["resultname"]; ok {
  1488. if v == valuestring[tempstrb+1:tempstre] {
  1489. if v1, ok := ParamMapList["resultmaps"]; ok {
  1490. if newA, ok := v1.([]map[string]interface{}); ok {
  1491. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1492. } else if newA, ok := v1.(map[string]interface{}); ok {
  1493. return interfacetostring(newA[valuestring[tempstre+1:]])
  1494. }
  1495. }
  1496. }
  1497. }
  1498. }
  1499. } else {
  1500. return valuestring
  1501. }
  1502. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1503. return strconv.FormatInt(int64(valuestring), 10)
  1504. }
  1505. return ""
  1506. }
  1507. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1508. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1509. tempstrb := strings.IndexAny(valuestring, "@")
  1510. tempstre := strings.IndexAny(valuestring, ".")
  1511. if tempstrb > -1 && tempstre > -1 {
  1512. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1513. if s, ok := v.(string); ok {
  1514. return s
  1515. } else if s, ok := v.(float64); ok {
  1516. return strconv.FormatFloat(s, 'f', -1, 64)
  1517. // return strconv.FormatInt(int64(s), 10)
  1518. }
  1519. }
  1520. }
  1521. }
  1522. return ""
  1523. }
  1524. 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) {
  1525. sqlname := fasion["name"].(string)
  1526. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1527. if v, ok := fasion["type"]; ok {
  1528. sqltype = v.(string)
  1529. }
  1530. sql := ""
  1531. p := ""
  1532. s_params := make([]interface{}, 0)
  1533. if sqltype != "" {
  1534. sql, p = restful.GetSqlByName(sqlname, tx)
  1535. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1536. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1537. paramslist := strings.Split(p, ",")
  1538. if len(paramslist) > 0 && p != "" {
  1539. for _, value := range paramslist {
  1540. ss := ""
  1541. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1542. ids, err := setting.SnowIds.NextId()
  1543. if err != nil {
  1544. ids = time.Now().UnixNano()
  1545. logging.Info("create SnowIds err", err)
  1546. }
  1547. s_params = append(s_params, ids)
  1548. } else {
  1549. if ss == "" && CommonParamMap != nil {
  1550. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1551. ss = valuestring
  1552. tempstrb := strings.IndexAny(valuestring, "@")
  1553. tempstre := strings.IndexAny(valuestring, ".")
  1554. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1555. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1556. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1557. }
  1558. } else {
  1559. ss = ""
  1560. }
  1561. }
  1562. }
  1563. if ss == "" && ParentParamMap != nil {
  1564. ss = getParamValue_(v, value, ParentParamMap)
  1565. }
  1566. if ss == "" && sameParamMap != nil {
  1567. ss = getParamValue(v, value, sameParamMap)
  1568. }
  1569. if ss == "" && ParamMap != nil {
  1570. ss = getParamValue(v, value, ParamMap)
  1571. }
  1572. s_params = append(s_params, ss)
  1573. }
  1574. }
  1575. }
  1576. }
  1577. }
  1578. if sql == "" {
  1579. sqltype = ""
  1580. }
  1581. if sqltype == "s1" {
  1582. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1583. if v, ok := tempValParam.(map[string]interface{}); ok {
  1584. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1585. }
  1586. if err != nil {
  1587. return nil, err
  1588. }
  1589. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1590. if err != nil {
  1591. return nil, err
  1592. }
  1593. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1594. } else if sqltype == "sm" {
  1595. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1596. if v, ok := tempValParam.(map[string]interface{}); ok {
  1597. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1598. } else {
  1599. }
  1600. if err != nil {
  1601. return nil, err
  1602. }
  1603. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1604. if err != nil {
  1605. return nil, err
  1606. }
  1607. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1608. } else if sqltype == "v" {
  1609. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1610. if v, ok := tempValParam.(map[string]interface{}); ok {
  1611. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1612. } else {
  1613. }
  1614. if err != nil {
  1615. return nil, err
  1616. }
  1617. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1618. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1619. }
  1620. } else if sqltype == "e" {
  1621. tempVal_arrary := make([]map[string]interface{}, 0)
  1622. tempVal_map := make(map[string]interface{})
  1623. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1624. if err == nil {
  1625. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1626. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1627. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1628. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1629. return tempVal_arrary, err
  1630. }
  1631. return nil, err
  1632. } else {
  1633. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1634. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1635. if err != nil {
  1636. return nil, err
  1637. }
  1638. return nil, err
  1639. }
  1640. }
  1641. return nil, nil
  1642. }
  1643. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1644. var err error
  1645. subarray, ok := fasion["children"]
  1646. if ok {
  1647. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1648. tempVal_arrary := make([]map[string]interface{}, 0)
  1649. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1650. tempVal_ := make(map[string]interface{})
  1651. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1652. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1653. } else {
  1654. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1655. }
  1656. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1657. if err != nil {
  1658. return err
  1659. }
  1660. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1661. }
  1662. v.(map[string]interface{})["children"] = tempVal_arrary
  1663. }
  1664. }
  1665. return nil
  1666. }
  1667. // @Summary 删除图片
  1668. // @Tags RemovePicByName
  1669. // @Accept json
  1670. // @Produce json
  1671. // @Param sqlname query string true "sqlname"
  1672. // @Param offset query int true "offset"
  1673. // @Param pagecount query int true "pagecount"
  1674. // @Param returntype query string true "returntype"
  1675. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1676. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1677. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1678. // @Router /data/PostDataByName [POST]
  1679. func RemovePicByName(c *gin.Context) {
  1680. logging.Info("RemovePicByName ", c.Keys)
  1681. appG := app.Gin{C: c}
  1682. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1683. fsion := gofasion.NewFasion(string(dataByte))
  1684. sqlnamestr := fsion.Get("name").ValueStr()
  1685. picname := fsion.Get("picname").ValueStr()
  1686. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1687. params := fsion.Get("params").Array()
  1688. s_params := make([]interface{}, 0)
  1689. for _, v_params := range params {
  1690. s_params = append(s_params, v_params.ValueStr())
  1691. }
  1692. if sql != "" {
  1693. queryData, err := execDataBySql(sql, s_params)
  1694. if picname != "" {
  1695. // Destination
  1696. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1697. err := os.Remove(distPath) //删除文件test.txt
  1698. if err != nil {
  1699. //如果删除失败则输出 file remove Error!
  1700. fmt.Println("file remove Error!")
  1701. //输出错误详细信息
  1702. fmt.Printf("%s", err)
  1703. } else {
  1704. //如果删除成功则输出 file remove OK!
  1705. fmt.Print("file remove OK!")
  1706. }
  1707. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1708. err = os.Remove(distPath) //删除文件test.txt
  1709. if err != nil {
  1710. //如果删除失败则输出 file remove Error!
  1711. fmt.Println("file remove Error!")
  1712. //输出错误详细信息
  1713. fmt.Printf("%s", err)
  1714. } else {
  1715. //如果删除成功则输出 file remove OK!
  1716. fmt.Print("file remove OK!")
  1717. }
  1718. }
  1719. if err != nil {
  1720. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1721. } else {
  1722. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1723. }
  1724. } else {
  1725. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1726. }
  1727. }
  1728. // @Summary 删除文件
  1729. // @Tags RemoveFileByName
  1730. // @Accept json
  1731. // @Produce json
  1732. // @Param sqlname query string true "sqlname"
  1733. // @Param offset query int true "offset"
  1734. // @Param pagecount query int true "pagecount"
  1735. // @Param returntype query string true "returntype"
  1736. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1737. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1738. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1739. // @Router /data/PostDataByName [POST]
  1740. func RemoveFileByName(c *gin.Context) {
  1741. appG := app.Gin{C: c}
  1742. id := c.Param("id")
  1743. logging.Info("DownloadFile ", c.Keys, id)
  1744. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1745. if eqdoc == nil {
  1746. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1747. return
  1748. }
  1749. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1750. err = os.Remove(distPath) //删除文件test.txt
  1751. if err != nil {
  1752. //如果删除失败则输出 file remove Error!
  1753. fmt.Println("file remove Error!")
  1754. //输出错误详细信息
  1755. fmt.Printf("%s", err)
  1756. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1757. return
  1758. }
  1759. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1760. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1761. }
  1762. // @Summary 根据APISQL表中SQL执行得到数据集
  1763. // @Tags PostDataByName
  1764. // @Accept json
  1765. // @Produce json
  1766. // @Param sqlname query string true "sqlname"
  1767. // @Param offset query int true "offset"
  1768. // @Param pagecount query int true "pagecount"
  1769. // @Param returntype query string true "returntype"
  1770. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1771. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1772. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1773. // @Router /data/PostDataByName [POST]
  1774. func UpdateDataRelation(c *gin.Context) {
  1775. appG := app.Gin{C: c}
  1776. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1777. fsion := gofasion.NewFasion(string(dataByte))
  1778. tablename := fsion.Get("name").ValueStr()
  1779. dataname := fsion.Get("dataname").ValueStr()
  1780. datavalue := fsion.Get("datavalue").ValueStr()
  1781. valuename := fsion.Get("valuename").ValueStr()
  1782. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1783. values := fsion.Get("values").Array()
  1784. tx := restful.Engine.NewSession()
  1785. err := tx.Begin()
  1786. defer func() {
  1787. switch {
  1788. case err != nil:
  1789. if tx != nil {
  1790. tx.Rollback()
  1791. }
  1792. default:
  1793. if tx != nil {
  1794. err = tx.Commit()
  1795. }
  1796. }
  1797. if tx != nil {
  1798. tx.Close()
  1799. }
  1800. }()
  1801. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1802. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1803. d_params := make([]interface{}, 4)
  1804. d_params[0] = datavalue
  1805. s_params := ""
  1806. for _, v_values := range values {
  1807. d_params[1] = v_values.ValueStr()
  1808. if s_params == "" {
  1809. s_params = v_values.ValueStr()
  1810. } else {
  1811. s_params = s_params + "," + v_values.ValueStr()
  1812. }
  1813. d_params[2] = d_params[1]
  1814. d_params[3] = d_params[0]
  1815. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1816. if err != nil {
  1817. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1818. break
  1819. }
  1820. }
  1821. if s_params != "" {
  1822. deleteSqlstr := "delete from " + tablename + " " +
  1823. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1824. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1825. if err != nil {
  1826. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1827. } else if err == nil {
  1828. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1829. }
  1830. } else {
  1831. deleteSqlstr := "delete from " + tablename + " " +
  1832. " where " + dataname + " = " + datavalue
  1833. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1834. if err != nil {
  1835. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1836. } else if err == nil {
  1837. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1838. }
  1839. }
  1840. }
  1841. // @Summary 根据APISQL表中SQL执行得到数据集
  1842. // @Tags PostDatasByName
  1843. // @Accept json
  1844. // @Produce json
  1845. // @Param sqlname query string true "sqlname"
  1846. // @Param offset query int true "offset"
  1847. // @Param pagecount query int true "pagecount"
  1848. // @Param returntype query string true "returntype"
  1849. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1850. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1851. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1852. // @Router /data/PostDatasByName [POST]
  1853. func PostDataByNames(c *gin.Context) {
  1854. appG := app.Gin{C: c}
  1855. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1856. fsion := gofasion.NewFasion(string(dataByte))
  1857. sqlParams := fsion.Get("array").Array()
  1858. queryData := make(map[string]interface{})
  1859. for _, v := range sqlParams {
  1860. fsion2 := gofasion.NewFasion(v.Json())
  1861. ss := fsion2.Get("name")
  1862. aa := fsion2.Get("params")
  1863. fmt.Println(ss, aa)
  1864. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1865. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1866. if sql == "" {
  1867. errorm := make(map[string]interface{})
  1868. errorm["code"] = e.ERROR
  1869. errorm["message"] = "sql没有找到"
  1870. errorm["param"] = ""
  1871. queryData[fsion2.Get("name").ValueStr()] = errorm
  1872. continue
  1873. } else if sql != "" {
  1874. s_params := make([]interface{}, 0)
  1875. if fsion2.HasKey("parammaps") {
  1876. parammaps := fsion2.Get("parammaps")
  1877. paramslist := strings.Split(p, ",")
  1878. if len(paramslist) > 0 && p != "" {
  1879. for _, value := range paramslist {
  1880. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1881. if tempv, exists := c.Get("jwt_username"); exists {
  1882. s_params = append(s_params, tempv.(string))
  1883. } else {
  1884. s_params = append(s_params, "")
  1885. }
  1886. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1887. ids, err := setting.SnowIds.NextId()
  1888. if err != nil {
  1889. ids = time.Now().UnixNano()
  1890. logging.Info("create SnowIds err", err)
  1891. }
  1892. s_params = append(s_params, ids)
  1893. } else {
  1894. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1895. }
  1896. }
  1897. }
  1898. } else if fsion2.HasKey("params") {
  1899. params := fsion2.Get("params").Array()
  1900. //ids,err := setting.SnowIds.NextId()
  1901. //if err !=nil{
  1902. // ids = time.Now().UnixNano()
  1903. // logging.Info("create SnowIds err",err)
  1904. //}
  1905. //s_params = append(s_params, ids)
  1906. for _, v_params := range params {
  1907. s_params = append(s_params, v_params.ValueStr())
  1908. }
  1909. }
  1910. _, err := execDataBySql(sql, s_params)
  1911. if err != nil {
  1912. logging.Error("PostDataByName err: ", err)
  1913. errorm := make(map[string]interface{})
  1914. errorm["code"] = e.ERROR
  1915. errorm["message"] = err.Error()
  1916. errorm["param"] = s_params
  1917. queryData[fsion2.Get("name").ValueStr()] = errorm
  1918. continue
  1919. } else {
  1920. errorm := make(map[string]interface{})
  1921. errorm["code"] = e.SUCCESS
  1922. errorm["message"] = "success"
  1923. queryData[fsion2.Get("name").ValueStr()] = errorm
  1924. continue
  1925. }
  1926. } else {
  1927. errorm := make(map[string]interface{})
  1928. errorm["code"] = e.ERROR
  1929. errorm["message"] = "NO SQL"
  1930. errorm["param"] = ""
  1931. queryData[fsion2.Get("name").ValueStr()] = errorm
  1932. }
  1933. }
  1934. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1935. }
  1936. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1937. if offset > 0 {
  1938. offset = offset - 1
  1939. }
  1940. //if pagecount == 0 {
  1941. // pagecount = setting.AppSetting.PageSize
  1942. //}else if pagecount>setting.AppSetting.PageSize{
  1943. // pagecount = setting.AppSetting.PageSize
  1944. //}
  1945. if returntype == "list" {
  1946. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1947. return queryData, err
  1948. } else if returntype == "listlist" {
  1949. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1950. return queryData, err
  1951. } else {
  1952. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1953. return queryData, err
  1954. }
  1955. }
  1956. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1957. if offset > 0 {
  1958. offset = offset - 1
  1959. }
  1960. //if pagecount == 0 {
  1961. // pagecount = setting.AppSetting.PageSize
  1962. //}else if pagecount>setting.AppSetting.PageSize{
  1963. // pagecount = setting.AppSetting.PageSize
  1964. //}
  1965. if returntype == "list" {
  1966. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1967. return queryData, err
  1968. } else if returntype == "listlist" {
  1969. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1970. return queryData, err
  1971. } else {
  1972. fmt.Println(params)
  1973. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1974. return queryData, err
  1975. }
  1976. }
  1977. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1978. paramslist := strings.Split(Params, ",")
  1979. s_params := make([]interface{}, 0)
  1980. if isList {
  1981. for _, v_params := range thisParams["params"].([]interface{}) {
  1982. s_params = append(s_params, v_params)
  1983. }
  1984. } else {
  1985. paramslist := strings.Split(Params, ",")
  1986. if len(paramslist) > 0 && Params != "" {
  1987. for _, value := range paramslist {
  1988. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1989. }
  1990. }
  1991. }
  1992. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  1993. for _, queryData_ := range queryData {
  1994. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  1995. if isList {
  1996. if queryData_[idname] != nil {
  1997. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  1998. }
  1999. } else {
  2000. if queryData_[idname] != nil {
  2001. thisParams[idname] = queryData_[idname].(interface{})
  2002. }
  2003. if len(paramslist) > 0 && Params != "" {
  2004. s_params = make([]interface{}, 0)
  2005. for _, value := range paramslist {
  2006. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  2007. }
  2008. }
  2009. }
  2010. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  2011. } else {
  2012. }
  2013. }
  2014. return queryData, err
  2015. }
  2016. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2017. queryData, err := restful.ExecQuery(sqlstr, params)
  2018. return queryData, err
  2019. }
  2020. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2021. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2022. return queryData, err
  2023. }
  2024. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2025. queryData, err := restful.ExecQuery(sqlstr, params)
  2026. return queryData, err
  2027. }
  2028. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2029. // @Tags ImportExcel
  2030. // @Accept json
  2031. // @Produce json
  2032. // @Param file query string true "文件名"
  2033. // @Param name header string true "执行sql的名字"
  2034. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2035. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2036. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2037. // @Router /data/ImportExcel [POST]
  2038. func ImportExcel(c *gin.Context) {
  2039. appG := app.Gin{C: c}
  2040. inputdata := ""
  2041. c.Request.ParseForm()
  2042. params := c.Request.Form
  2043. file, _, err := c.Request.FormFile("file")
  2044. if err != nil {
  2045. appG.Response(http.StatusOK, e.ERROR, err)
  2046. return
  2047. }
  2048. sqlnamestrs := params.Get("name")
  2049. sheetname := params.Get("sheetname")
  2050. pastureid := params.Get("pastureid")
  2051. //importParams := params.Get("importParams")
  2052. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2053. // 必输项参数 (字符串格式 "field1,field2,field3")
  2054. requiredParams := params.Get("requiredParams")
  2055. // 日期参数
  2056. dateParams := params.Get("dateParams")
  2057. // 数字参数
  2058. numParams := params.Get("numParams")
  2059. //将字符串分割开
  2060. dateParamslist := strings.Split(dateParams, ",")
  2061. requiredParamslist := strings.Split(requiredParams, ",")
  2062. numParamslist := strings.Split(numParams, ",")
  2063. queryData := make([]interface{}, 0)
  2064. sqlslist := strings.Split(sqlnamestrs, ",")
  2065. xlsx1, err := excelize.OpenReader(file)
  2066. if err != nil {
  2067. fmt.Println(err)
  2068. return
  2069. }
  2070. ok := 0
  2071. error := 0
  2072. isdone := true
  2073. rows, _ := xlsx1.GetRows(sheetname)
  2074. // 限制10000条,多余的截取掉
  2075. if len(rows) > 10000 {
  2076. rows = rows[:10000]
  2077. }
  2078. for i, row := range rows {
  2079. if i > 0 {
  2080. entry := make(map[string]interface{})
  2081. outentry := make(map[string]interface{})
  2082. for j, colCell := range rows[0] {
  2083. for k, colCell1 := range row {
  2084. if j == k {
  2085. outentry[colCell] = colCell1
  2086. entry[colCell] = colCell1
  2087. }
  2088. }
  2089. }
  2090. inputdata = ""
  2091. a := ""
  2092. fmt.Println(outentry, entry)
  2093. //校验日期格式
  2094. for _, v := range dateParamslist {
  2095. if v == "" {
  2096. continue
  2097. }
  2098. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2099. dtime, err := TransfTime(d.(string))
  2100. if err != nil {
  2101. a = strings.Trim(v, " ")
  2102. break
  2103. }
  2104. outentry[strings.Trim(v, " ")] = dtime
  2105. }
  2106. }
  2107. if a != "" {
  2108. outentry["error_msg"] = a + " 格式错误"
  2109. error++
  2110. queryData = append(queryData, outentry)
  2111. continue
  2112. }
  2113. a = ""
  2114. //校验必填格式
  2115. for _, v := range requiredParamslist {
  2116. if v == "" {
  2117. continue
  2118. }
  2119. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2120. a = strings.Trim(v, " ")
  2121. break
  2122. }
  2123. }
  2124. if a != "" {
  2125. outentry["error_msg"] = a + " 未填或格式错误"
  2126. error++
  2127. queryData = append(queryData, outentry)
  2128. continue
  2129. }
  2130. a = ""
  2131. //校验数字格式
  2132. for _, v := range numParamslist {
  2133. if v == "" {
  2134. continue
  2135. }
  2136. d, ok := outentry[strings.Trim(v, " ")]
  2137. if !ok || d == "" {
  2138. outentry[strings.Trim(v, " ")] = 0
  2139. } else {
  2140. var fl float64
  2141. switch d.(type) {
  2142. case string:
  2143. fl, err = strconv.ParseFloat(d.(string), 64)
  2144. }
  2145. if err != nil || fl < 0 {
  2146. a = strings.Trim(v, " ")
  2147. break
  2148. }
  2149. }
  2150. }
  2151. if a != "" {
  2152. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2153. error++
  2154. queryData = append(queryData, outentry)
  2155. continue
  2156. }
  2157. tx := restful.Engine.NewSession()
  2158. err := tx.Begin()
  2159. for _, sqlnamestr := range sqlslist {
  2160. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2161. paramslist := strings.Split(paramslists, ",")
  2162. if len(paramslist) > 0 {
  2163. s_params := make([]interface{}, 0)
  2164. for _, value := range paramslist {
  2165. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2166. if tempv, exists := c.Get("jwt_username"); exists {
  2167. s_params = append(s_params, tempv.(string))
  2168. } else {
  2169. s_params = append(s_params, "")
  2170. }
  2171. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2172. s_params = append(s_params, pastureid)
  2173. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2174. ids, err := setting.SnowIds.NextId()
  2175. if err != nil {
  2176. ids = time.Now().UnixNano()
  2177. logging.Info("create SnowIds err", err)
  2178. }
  2179. s_params = append(s_params, ids)
  2180. } else {
  2181. if outentry[strings.Trim(value, " ")] == nil {
  2182. s_params = append(s_params, "")
  2183. } else {
  2184. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2185. }
  2186. }
  2187. }
  2188. outentry["input"] = inputdata
  2189. fmt.Println(sql, s_params)
  2190. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2191. if err != nil {
  2192. if tx != nil {
  2193. tx.Rollback()
  2194. }
  2195. if tx != nil {
  2196. tx.Close()
  2197. }
  2198. msg := geterrmsg(err.Error())
  2199. outentry["error_msg"] = msg
  2200. error++
  2201. queryData = append(queryData, outentry)
  2202. isdone = true
  2203. break
  2204. } else {
  2205. if len(returnmsgmap1) > 0 {
  2206. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2207. if tx != nil {
  2208. tx.Rollback()
  2209. }
  2210. if tx != nil {
  2211. tx.Close()
  2212. }
  2213. msg := geterrmsg(va.(string))
  2214. outentry["error_msg"] = msg
  2215. error++
  2216. queryData = append(queryData, outentry)
  2217. isdone = true
  2218. break
  2219. }
  2220. }
  2221. isdone = false
  2222. }
  2223. }
  2224. }
  2225. switch {
  2226. case err != nil:
  2227. if tx != nil {
  2228. tx.Rollback()
  2229. }
  2230. default:
  2231. if tx != nil {
  2232. err = tx.Commit()
  2233. }
  2234. }
  2235. if tx != nil {
  2236. tx.Close()
  2237. }
  2238. }
  2239. if !isdone {
  2240. ok++
  2241. isdone = true
  2242. }
  2243. }
  2244. data := make(map[string]interface{})
  2245. data["result"] = queryData
  2246. data["success"] = ok
  2247. data["err_count"] = error
  2248. appG.Response(http.StatusOK, e.SUCCESS, data)
  2249. }
  2250. func TransfTime(timestr string) (string, error) {
  2251. if timestr == "" {
  2252. return time.Now().Format("2006-01-02"), nil
  2253. }
  2254. days, err := strconv.Atoi(timestr)
  2255. if err != nil {
  2256. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2257. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2258. }
  2259. _, err := time.Parse("2006-01-02", timestr)
  2260. if err != nil {
  2261. t, err := time.Parse("2006/01/02", timestr)
  2262. if err != nil {
  2263. t, err := time.Parse("2006.01.02", timestr)
  2264. if err != nil {
  2265. return "", err
  2266. } else {
  2267. return t.Format("2006-01-02"), nil
  2268. }
  2269. } else {
  2270. return t.Format("2006-01-02"), nil
  2271. }
  2272. } else {
  2273. return timestr, nil
  2274. }
  2275. }
  2276. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2277. times = times.AddDate(0, 0, days)
  2278. return times.Format("2006-01-02"), nil
  2279. }
  2280. func Createchart(c *gin.Context) {
  2281. appG := app.Gin{C: c}
  2282. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2283. fsion := gofasion.NewFasion(string(dataByte))
  2284. chart_name := fsion.Get("chart_name").ValueStr()
  2285. desc := fsion.Get("desc").ValueStr()
  2286. pastureid := fsion.Get("pastureid").ValueStr()
  2287. source_id := fsion.Get("source_id").ValueStr()
  2288. emp := fsion.Get("emp").ValueStr()
  2289. content := fsion.Get("content").Json()
  2290. var mapResult map[string]interface{}
  2291. err1 := json.Unmarshal([]byte(content), &mapResult)
  2292. if err1 != nil {
  2293. fmt.Println("JsonToMapDemo err: ", err1)
  2294. }
  2295. tx := restful.Engine.NewSession()
  2296. err := tx.Begin()
  2297. defer func() {
  2298. switch {
  2299. case err != nil:
  2300. logging.Error("tx.Begin 事务启动失败__error:", err)
  2301. if tx != nil {
  2302. tx.Rollback()
  2303. }
  2304. default:
  2305. if tx != nil {
  2306. err = tx.Commit()
  2307. }
  2308. }
  2309. if tx != nil {
  2310. tx.Close()
  2311. }
  2312. }()
  2313. ids, err := setting.SnowIds.NextId()
  2314. if err != nil {
  2315. ids = time.Now().UnixNano()
  2316. logging.Info("create SnowIds err", err)
  2317. }
  2318. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2319. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2320. if err != nil {
  2321. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2322. } else {
  2323. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2324. }
  2325. }
  2326. func Updatedashboard(c *gin.Context) {
  2327. appG := app.Gin{C: c}
  2328. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2329. fsion := gofasion.NewFasion(string(dataByte))
  2330. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2331. pastureid := fsion.Get("pastureid").ValueStr()
  2332. content := fsion.Get("content").Json()
  2333. var mapResult map[string]interface{}
  2334. err1 := json.Unmarshal([]byte(content), &mapResult)
  2335. if err1 != nil {
  2336. fmt.Println("JsonToMapDemo err: ", err1)
  2337. }
  2338. layout := mapResult["layout"]
  2339. tx := restful.Engine.NewSession()
  2340. err := tx.Begin()
  2341. defer func() {
  2342. switch {
  2343. case err != nil:
  2344. logging.Error("tx.Begin 事务启动失败__error:", err)
  2345. if tx != nil {
  2346. tx.Rollback()
  2347. }
  2348. default:
  2349. if tx != nil {
  2350. err = tx.Commit()
  2351. }
  2352. }
  2353. if tx != nil {
  2354. tx.Close()
  2355. }
  2356. }()
  2357. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2358. if err != nil {
  2359. println("2", err.Error())
  2360. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2361. } else {
  2362. if exec != nil {
  2363. if exec[0]["content"] == nil {
  2364. mapR := make(map[string]interface{})
  2365. mapR["layout"] = layout
  2366. mjson, _ := json.Marshal(mapR)
  2367. mString := string(mjson)
  2368. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2369. if err3 != nil {
  2370. println("3", err3.Error())
  2371. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2372. } else {
  2373. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2374. }
  2375. } else {
  2376. var mapR map[string]interface{}
  2377. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2378. if err1 != nil {
  2379. fmt.Println("JsonToMapDemo err: ", err2)
  2380. }
  2381. mapR["layout"] = layout
  2382. mjson, _ := json.Marshal(mapR)
  2383. mString := string(mjson)
  2384. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2385. if err3 != nil {
  2386. println("3", err3.Error())
  2387. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2388. } else {
  2389. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2390. }
  2391. }
  2392. } else {
  2393. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2394. }
  2395. }
  2396. }
  2397. func ExecSQL(c *gin.Context) {
  2398. appG := app.Gin{C: c}
  2399. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2400. fsion := gofasion.NewFasion(string(dataByte))
  2401. content := fsion.Get("content").Json()
  2402. pastureid := fsion.Get("pastureid").ValueStr()
  2403. var mapResult map[string]interface{}
  2404. err1 := json.Unmarshal([]byte(content), &mapResult)
  2405. if err1 != nil {
  2406. fmt.Println("JsonToMapDemo err: ", err1)
  2407. }
  2408. sqlstr := "select "
  2409. groupstr := " GROUP BY "
  2410. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2411. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2412. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2413. }
  2414. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2415. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2416. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2417. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2418. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2419. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2420. sqlstr = sqlstr + tem + ","
  2421. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2422. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2423. sqlstr = sqlstr + tem + ","
  2424. } else {
  2425. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2426. sqlstr = sqlstr + tem + ","
  2427. }
  2428. }
  2429. if _, ok := mapResult["selectedCalcul2"]; ok {
  2430. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2431. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2432. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2433. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2434. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2435. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2436. sqlstr = sqlstr + tem + ","
  2437. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2438. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2439. sqlstr = sqlstr + tem + ","
  2440. } else {
  2441. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2442. sqlstr = sqlstr + tem + ","
  2443. }
  2444. }
  2445. }
  2446. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2447. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2448. sqlstr = sqlstr + " where pastureid=" + pastureid
  2449. if len(mapResult["filters"].([]interface{})) > 0 {
  2450. sqlstr = sqlstr + " and "
  2451. }
  2452. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2453. for _, value := range mapResult["filters"].([]interface{}) {
  2454. switch value.(map[string]interface{})["filterOperator"].(string) {
  2455. case ">", "=", "<", ">=", "<=", "!=", "like":
  2456. 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 "
  2457. case "IN":
  2458. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2459. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2460. sqlstr = sqlstr + value1.(string) + ","
  2461. }
  2462. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2463. sqlstr = sqlstr + ")" + " AND "
  2464. case "BETWEEN":
  2465. 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 "
  2466. }
  2467. }
  2468. if len(mapResult["filters"].([]interface{})) > 0 {
  2469. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2470. }
  2471. //
  2472. groupstr = groupstr[0 : len(groupstr)-1]
  2473. sqlstr = sqlstr + groupstr + " "
  2474. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2475. sqlstr = sqlstr + " order by "
  2476. }
  2477. //
  2478. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2479. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2480. sqlstr = sqlstr + value.(string) + " "
  2481. } else {
  2482. sqlstr = sqlstr + value.(string) + ","
  2483. }
  2484. }
  2485. //
  2486. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2487. tx := restful.Engine.NewSession()
  2488. err := tx.Begin()
  2489. defer func() {
  2490. switch {
  2491. case err != nil:
  2492. logging.Error("tx.Begin 事务启动失败__error:", err)
  2493. if tx != nil {
  2494. tx.Rollback()
  2495. }
  2496. default:
  2497. if tx != nil {
  2498. err = tx.Commit()
  2499. }
  2500. }
  2501. if tx != nil {
  2502. tx.Close()
  2503. }
  2504. }()
  2505. exec, err := tx.SQL(sqlstr).Query().List()
  2506. if err != nil {
  2507. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2508. } else {
  2509. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2510. }
  2511. }
  2512. func Dashboards(c *gin.Context) {
  2513. appG := app.Gin{C: c}
  2514. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2515. fsion := gofasion.NewFasion(string(dataByte))
  2516. sqlnamestr := fsion.Get("name").ValueStr()
  2517. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2518. offset := fsion.Get("offset").ValueDefaultInt(0)
  2519. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2520. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2521. month := fsion.Get("month").ValueDefaultStr("map")
  2522. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2523. tx := restful.Engine.NewSession()
  2524. err := tx.Begin()
  2525. defer func() {
  2526. switch {
  2527. case err != nil:
  2528. if tx != nil {
  2529. tx.Rollback()
  2530. }
  2531. default:
  2532. if tx != nil {
  2533. err = tx.Commit()
  2534. }
  2535. }
  2536. if tx != nil {
  2537. tx.Close()
  2538. }
  2539. }()
  2540. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2541. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2542. if sql != "" {
  2543. s_params := make([]interface{}, 0)
  2544. if fsion.HasKey("parammaps") {
  2545. parammaps := fsion.Get("parammaps")
  2546. paramslist := strings.Split(p, ",")
  2547. if len(paramslist) > 0 && p != "" {
  2548. for _, value := range paramslist {
  2549. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2550. if tempv, exists := c.Get("jwt_username"); exists {
  2551. s_params = append(s_params, tempv.(string))
  2552. } else {
  2553. s_params = append(s_params, "")
  2554. }
  2555. } else {
  2556. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2557. }
  2558. }
  2559. }
  2560. }
  2561. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2562. if err != nil {
  2563. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2564. } else {
  2565. //paramslist1 := strings.Split(p1, ",")
  2566. dids := make([]interface{}, 0)
  2567. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2568. var mapResult map[string]interface{}
  2569. dids = append(dids, value["dashboard_id"])
  2570. if value["content"] != nil {
  2571. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2572. if err1 != nil {
  2573. println("JsonToMapDemo1 err: ", err1)
  2574. }
  2575. temap := make(map[string]interface{})
  2576. tem := mapResult["layout"].([]interface{})
  2577. if v, ok := value["chartids"]; ok {
  2578. chartids := strings.Split(v.(string), ",")
  2579. for _, va := range chartids {
  2580. a := false
  2581. for _, v2 := range tem {
  2582. if v2.(map[string]interface{})["id"].(string) == va {
  2583. a = true
  2584. //println("va1======",va)
  2585. }
  2586. }
  2587. if !a {
  2588. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2589. va + "\",\"id\":\"" + va +
  2590. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2591. var mapTem map[string]interface{}
  2592. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2593. if err1 != nil {
  2594. println("JsonToMapDemo err: ", err1)
  2595. }
  2596. tem = append(tem, mapTem)
  2597. }
  2598. }
  2599. temap["layout"] = tem
  2600. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2601. }
  2602. } else {
  2603. temap := make(map[string]interface{})
  2604. tem := make([]interface{}, 0)
  2605. if v, ok := value["chartids"]; ok {
  2606. chartids := strings.Split(v.(string), ",")
  2607. for _, va := range chartids {
  2608. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2609. va + "\",\"id\":\"" + va +
  2610. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2611. var mapTem map[string]interface{}
  2612. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2613. if err1 != nil {
  2614. println("JsonToMapDemo err: ", err1)
  2615. }
  2616. tem = append(tem, mapTem)
  2617. }
  2618. temap["layout"] = tem
  2619. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2620. }
  2621. }
  2622. }
  2623. queryData.(map[string]interface{})["order"] = dids
  2624. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2625. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2626. }
  2627. } else {
  2628. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2629. }
  2630. }
  2631. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2632. fsion := gofasion.NewFasion(parammaps)
  2633. sqlnamestr := fsion.Get("name").ValueStr()
  2634. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2635. offset := fsion.Get("offset").ValueDefaultInt(0)
  2636. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2637. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2638. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2639. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2640. body := []byte("")
  2641. if sql != "" {
  2642. s_params := make([]interface{}, 0)
  2643. if fsion.HasKey("parammaps") {
  2644. parammaps := fsion.Get("parammaps")
  2645. paramslist := strings.Split(p, ",")
  2646. if len(paramslist) > 0 && p != "" {
  2647. for _, value := range paramslist {
  2648. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2649. }
  2650. }
  2651. }
  2652. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2653. if err != nil {
  2654. } else {
  2655. paramslist1 := strings.Split(p1, ",")
  2656. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2657. s_params1 := make([]interface{}, 0)
  2658. if len(paramslist1) > 0 && p1 != "" {
  2659. for _, v := range paramslist1 {
  2660. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2661. }
  2662. }
  2663. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2664. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2665. body, _ = json.Marshal(queryData)
  2666. }
  2667. }
  2668. }
  2669. bs := bytes.NewBuffer(body)
  2670. client := &http.Client{}
  2671. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2672. req, err := http.NewRequest(RequestMethod,
  2673. url,
  2674. bs,
  2675. )
  2676. if err != nil {
  2677. }
  2678. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2679. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2680. if err != nil {
  2681. // handle error
  2682. }
  2683. resp, err := client.Do(req)
  2684. if err != nil {
  2685. return ""
  2686. }
  2687. defer resp.Body.Close()
  2688. result_body, err := ioutil.ReadAll(resp.Body)
  2689. if err != nil {
  2690. return ""
  2691. }
  2692. fmt.Println(string(result_body))
  2693. return ""
  2694. }
  2695. func GetSummary(c *gin.Context) {
  2696. appG := app.Gin{C: c}
  2697. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2698. fsion := gofasion.NewFasion(string(dataByte))
  2699. offset := fsion.Get("offset").ValueDefaultInt(0)
  2700. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2701. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2702. parammaps := fsion.Get("parammaps")
  2703. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2704. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2705. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2706. tx := restful.Engine.NewSession()
  2707. defer tx.Close()
  2708. sqlnamestr := ""
  2709. if genre == "0" {
  2710. if status == "0" {
  2711. sqlnamestr = "getAccuracyJSY"
  2712. } else if status == "1" {
  2713. sqlnamestr = "getAccuracyHFT"
  2714. } else if status == "2" {
  2715. sqlnamestr = "getAccuracyHNS"
  2716. } else if status == "3" {
  2717. sqlnamestr = "getAccuracyHSC"
  2718. } else if status == "4" {
  2719. sqlnamestr = "getAccuracyHCC"
  2720. } else if status == "5" {
  2721. sqlnamestr = "getAccuracyMC"
  2722. } else if status == "6" {
  2723. sqlnamestr = "getAccuracyFeedHL"
  2724. } else if status == "7" {
  2725. sqlnamestr = "getAccuracyRT"
  2726. }
  2727. } else {
  2728. if status == "0" {
  2729. sqlnamestr = "getAccuracySCCJSY"
  2730. } else if status == "1" {
  2731. sqlnamestr = "getAccuracySFT"
  2732. } else if status == "2" {
  2733. sqlnamestr = "getAccuracySNS"
  2734. } else if status == "3" {
  2735. sqlnamestr = "getAccuracySSC"
  2736. } else if status == "4" {
  2737. sqlnamestr = "getAccuracySCC"
  2738. } else if status == "5" {
  2739. sqlnamestr = "getAccuracySLCL"
  2740. } else if status == "7" {
  2741. sqlnamestr = "getAccuracySCCRT"
  2742. }
  2743. }
  2744. if isDate == "1" {
  2745. sqlnamestr += "Date"
  2746. }
  2747. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2748. // fmt.Println(sqlnamestr, sql)
  2749. if sql != "" {
  2750. s_params := make([]interface{}, 0)
  2751. // if fsion.HasKey("parammaps") {
  2752. fmt.Println(s_params, "222", p)
  2753. paramslist := strings.Split(p, ",")
  2754. if len(paramslist) > 0 && p != "" {
  2755. for _, value := range paramslist {
  2756. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2757. if tempv, exists := c.Get("jwt_username"); exists {
  2758. s_params = append(s_params, tempv.(string))
  2759. } else {
  2760. s_params = append(s_params, "")
  2761. }
  2762. } else {
  2763. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2764. }
  2765. }
  2766. }
  2767. if returntype == "xlsx" {
  2768. var xlsxfile *xlsx.File
  2769. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2770. //c.File("c:/dd.xlsx")
  2771. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2772. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2773. c.Header("Content-Transfer-Encoding", "binary")
  2774. _ = xlsxfile.Write(c.Writer)
  2775. } else {
  2776. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2777. if err != nil {
  2778. logging.Error("GetDataByName err: ", err)
  2779. msg := geterrmsg(err.Error())
  2780. appG.Response(http.StatusOK, e.ERROR, msg)
  2781. } else {
  2782. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2783. }
  2784. }
  2785. } else {
  2786. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2787. }
  2788. }
  2789. // type lpplanStruct struct {
  2790. // Id int64 `xorm:"id"`
  2791. // Tmrname string `xorm:"tmrname"`
  2792. // Tmrid int64 `xorm:"tmrid"`
  2793. // Sort int64 `xorm:"sort"`
  2794. // Sel int64 `xorm:"sel"`
  2795. // Times int64 `xorm:"times"`
  2796. // Ftname string `xorm:"ftname"`
  2797. // Ftid int64 `xorm:"ftid"`
  2798. // Maxweight float64 `xorm:"maxweight"`
  2799. // Sumweight float64 `xorm:"sumweight"`
  2800. // Sumcowcount int64 `xorm:"sumcowcount"`
  2801. // Pastureid string `xorm:"pastureid"`
  2802. // Display string `xorm:"display"`
  2803. // Issplit int64 `xorm:"issplit"`
  2804. // BeginTime string `xorm:"begintime"`
  2805. // }
  2806. func UpdateFTdetail(c *gin.Context) {
  2807. appG := app.Gin{C: c}
  2808. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2809. tempval_ := make(map[string]interface{})
  2810. tempCommon := make(map[string]interface{})
  2811. tempval := make([]map[string]interface{}, 0)
  2812. fTChange := make(map[string]interface{}, 0)
  2813. fpdOldDataList := make([]map[string]interface{}, 0)
  2814. fpdDataList := make([]map[string]interface{}, 0)
  2815. fsion := gofasion.NewFasion(string(dataByte))
  2816. // parammaps := fsion.Get("parammaps")
  2817. createdate := time.Now().Format("2006-01-02 15:04:05")
  2818. err := json.Unmarshal(dataByte, &tempval_)
  2819. if err != nil {
  2820. appG.Response(http.StatusOK, e.ERROR, false)
  2821. return
  2822. }
  2823. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2824. tx := restful.Engine.NewSession()
  2825. if v, ok := tempval_["data"].([]interface{}); ok {
  2826. for _, Tvalue := range v {
  2827. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2828. if v1["name"] == "updateFPbyFTChange" {
  2829. fTChange = v1
  2830. continue
  2831. }
  2832. tempval = append(tempval, v1)
  2833. }
  2834. }
  2835. }
  2836. parammaps := fTChange["parammaps"].(map[string]interface{})
  2837. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2838. // if err != nil {
  2839. // logs.Error(err)
  2840. // appG.Response(http.StatusOK, e.ERROR, false)
  2841. // return
  2842. // }
  2843. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2844. // if err != nil {
  2845. // logs.Error(err)
  2846. // appG.Response(http.StatusOK, e.ERROR, false)
  2847. // return
  2848. // }
  2849. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2850. // if err != nil {
  2851. // logs.Error(err)
  2852. // appG.Response(http.StatusOK, e.ERROR, false)
  2853. // return
  2854. // }
  2855. err = tx.Begin()
  2856. if err != nil {
  2857. logging.Error("tx.Begin 事务启动失败__error:", err)
  2858. }
  2859. defer func() {
  2860. if err != nil {
  2861. if tx != nil {
  2862. tx.Rollback()
  2863. }
  2864. }
  2865. if tx != nil {
  2866. tx.Close()
  2867. }
  2868. }()
  2869. if err != nil {
  2870. } else {
  2871. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2872. tempCommon = v
  2873. }
  2874. 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 ,
  2875. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2876. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2877. UNION
  2878. 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 ,
  2879. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2880. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2881. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2882. if err == nil {
  2883. if tempv, exists := c.Get("jwt_username"); exists {
  2884. tempCommon["jwt_username"] = tempv.(string)
  2885. }
  2886. for _, paramvalue := range tempval {
  2887. if _, ok := paramvalue["resultname"]; !ok {
  2888. paramvalue["resultname"] = paramvalue["name"]
  2889. }
  2890. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2891. if err != nil {
  2892. logging.Error("ExecDataParam error:", err)
  2893. break
  2894. }
  2895. }
  2896. if err != nil {
  2897. msg := geterrmsg(err.Error())
  2898. appG.Response(http.StatusOK, e.ERROR, msg)
  2899. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2900. }
  2901. }
  2902. }
  2903. tx.Commit()
  2904. // go func() {
  2905. if fTChange != nil {
  2906. parammaps := fTChange["parammaps"].(map[string]interface{})
  2907. if parammaps["type"].(float64) == 1 {
  2908. _, err = tx.SQL(`UPDATE feedp fp
  2909. set
  2910. fp.ftweight= IFNULL(IF(
  2911. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2912. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2913. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2914. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2915. ),0),fp.feedweight = IFNULL(IF(
  2916. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2917. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2918. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2919. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2920. ),0) +ifnull(fp.supplyweight,0)
  2921. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2922. _, err = tx.SQL(`UPDATE fpdetail fpd
  2923. INNER JOIN feedp fp
  2924. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2925. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2926. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2927. } else {
  2928. _, err = tx.SQL(`UPDATE feedp fp
  2929. SET
  2930. fp.supplyweight= IFNULL(IF(
  2931. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2932. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2933. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2934. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2935. ),0),fp.feedweight = IFNULL(IF(
  2936. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2937. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2938. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2939. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2940. ),0) +ifnull(fp.supplyweight,0)
  2941. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2942. _, err = tx.SQL(`UPDATE fpdetail fpd
  2943. INNER JOIN feedp fp
  2944. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2945. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2946. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2947. }
  2948. 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(ptid) ptid,TRIM(ptsid ) ptsid ,
  2949. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2950. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2951. UNION
  2952. 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 ,
  2953. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2954. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2955. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2956. lpplanList := make([]*lpplanStruct, 0)
  2957. err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2958. if err != nil {
  2959. logs.Error(err, 1)
  2960. return
  2961. }
  2962. lppidlist := []string{}
  2963. for _, lpp := range lpplanList {
  2964. lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2965. }
  2966. if len(lppidlist) <= 0 {
  2967. appG.Response(http.StatusOK, e.SUCCESS, true)
  2968. return
  2969. }
  2970. lpplandtl1AllList := make([]*lpplandtl1, 0)
  2971. err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  2972. order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  2973. if err != nil {
  2974. // tx.Rollback()
  2975. logs.Error(err, 2, parammaps["pastureid"])
  2976. return
  2977. }
  2978. var wg sync.WaitGroup
  2979. for _, old := range fpdOldDataList {
  2980. for _, fpd := range fpdDataList {
  2981. wg.Add(1)
  2982. go func(old, fpd map[string]interface{}) {
  2983. updateLppandList := make([]*lpplandtl1, 0)
  2984. defer wg.Done()
  2985. if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  2986. fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  2987. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  2988. oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  2989. if weight > oldweight {
  2990. return
  2991. }
  2992. var w float64
  2993. var status int
  2994. if weight < oldweight {
  2995. if weight >= 0 {
  2996. return
  2997. }
  2998. w = weight
  2999. status = 0
  3000. } else {
  3001. if oldweight > 0 {
  3002. return
  3003. }
  3004. w = weight
  3005. status = 1
  3006. }
  3007. // fweight = w
  3008. for _, lpp := range lpplanList {
  3009. var fweight float64
  3010. var lweight float64
  3011. lpplandtl1List := make([]*lpplandtl1, 0)
  3012. fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  3013. for _, lppland := range lpplandtl1AllList {
  3014. if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  3015. lpplandtl1List = append(lpplandtl1List, lppland)
  3016. }
  3017. }
  3018. if len(lpplandtl1List) == 0 {
  3019. continue
  3020. }
  3021. for _, lppland := range lpplandtl1List {
  3022. lweight += lppland.Lweight
  3023. }
  3024. if status == 0 {
  3025. if lweight <= 0 {
  3026. continue
  3027. }
  3028. } else {
  3029. if lpp.Maxweight <= lweight {
  3030. continue
  3031. }
  3032. }
  3033. for _, lppland := range lpplandtl1List {
  3034. if fpdid == lppland.Fpdid {
  3035. if status == 1 {
  3036. // if w <= lppland.Lweight {
  3037. if lpp.Maxweight <= lweight {
  3038. continue
  3039. }
  3040. if w+lweight <= lpp.Maxweight {
  3041. lppland.Lweight += w
  3042. lweight += w
  3043. fweight += w
  3044. w = 0
  3045. } else {
  3046. w = w - (lpp.Maxweight - lweight)
  3047. n := (lpp.Maxweight - lweight)
  3048. lppland.Lweight = lppland.Lweight + n
  3049. lweight += n
  3050. fweight += n
  3051. }
  3052. } else {
  3053. if lppland.Lweight == 0 {
  3054. continue
  3055. }
  3056. if w+lppland.Lweight >= 0 {
  3057. lppland.Lweight = lppland.Lweight + w
  3058. lweight = lweight + w
  3059. fweight = fweight + w
  3060. w = 0
  3061. } else {
  3062. w = w + lppland.Lweight
  3063. lweight = lweight - lppland.Lweight
  3064. fweight = fweight - lppland.Lweight
  3065. lppland.Lweight = 0
  3066. }
  3067. }
  3068. updateLppandList = append(updateLppandList, lppland)
  3069. break
  3070. }
  3071. }
  3072. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3073. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3074. WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3075. if err != nil {
  3076. // tx.Rollback()
  3077. logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3078. return
  3079. }
  3080. for _, lppland := range updateLppandList {
  3081. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3082. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3083. if err != nil {
  3084. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3085. // tx.Rollback()
  3086. logs.Error(err, 3)
  3087. return
  3088. }
  3089. // defer wg.Done()
  3090. }
  3091. updateLppandList = []*lpplandtl1{}
  3092. if w == 0 {
  3093. break
  3094. }
  3095. }
  3096. }
  3097. }(old, fpd)
  3098. }
  3099. }
  3100. wg.Wait()
  3101. }
  3102. newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3103. if err != nil {
  3104. logs.Error(err)
  3105. appG.Response(http.StatusOK, e.ERROR, false)
  3106. return
  3107. }
  3108. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3109. if err != nil {
  3110. logs.Error(err)
  3111. appG.Response(http.StatusOK, e.ERROR, false)
  3112. return
  3113. }
  3114. newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3115. if err != nil {
  3116. logs.Error(err)
  3117. appG.Response(http.StatusOK, e.ERROR, false)
  3118. return
  3119. }
  3120. now := createdate
  3121. // for _, oldFpd := range oldFpdDataList {
  3122. for _, newFpd := range newFpdDataList {
  3123. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3124. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3125. // go func() {
  3126. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
  3127. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3128. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3129. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
  3130. if err != nil {
  3131. logs.Error(err)
  3132. appG.Response(http.StatusOK, e.ERROR, false)
  3133. return
  3134. }
  3135. // }()
  3136. }
  3137. // break
  3138. // }
  3139. // }
  3140. // }
  3141. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3142. for _, newLpplandtl1 := range newLpplandtl1List {
  3143. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3144. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3145. // go func() {
  3146. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3147. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3148. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3149. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3150. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3151. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3152. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3153. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3154. if err != nil {
  3155. logs.Error(err)
  3156. appG.Response(http.StatusOK, e.ERROR, false)
  3157. return
  3158. }
  3159. // }()
  3160. // }
  3161. // break
  3162. // }
  3163. // }
  3164. }
  3165. // for _, oldFeedp := range oldFeedpList {
  3166. for _, newFeedp := range newFeedpList {
  3167. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3168. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3169. // go func() {
  3170. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3171. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
  3172. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3173. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3174. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3175. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3176. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3177. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
  3178. if err != nil {
  3179. logs.Error(err)
  3180. appG.Response(http.StatusOK, e.ERROR, false)
  3181. return
  3182. }
  3183. // }()
  3184. // }
  3185. // }
  3186. }
  3187. appG.Response(http.StatusOK, e.SUCCESS, true)
  3188. }
  3189. type lpplandtlInfo struct {
  3190. Id int64 `xorm:"id"`
  3191. Pastureid int64 `xorm:"pastureid"`
  3192. Lppid int64 `xorm:"lppid"`
  3193. Barid int64 `xorm:"barid"`
  3194. Barname string `xorm:"barname"`
  3195. Fpdid int64 `xorm:"fpdid"`
  3196. Fttype int64 `xorm:"fttype"`
  3197. Lweight float64 `xorm:"lweight"`
  3198. Sort int64 `xorm:"sort"`
  3199. Tmrid int64 `xorm:"tmrid"`
  3200. Tmrname string `xorm:"tmrname"`
  3201. Cowcount int64 `xorm:"cowcount"`
  3202. Ccountradio float64 `xorm:"ccountradio"`
  3203. Background string `xorm:"background"`
  3204. Lweighthis float64 `xorm:"lweighthis"`
  3205. Maxweight float64 `xorm:"maxweight"`
  3206. }
  3207. func UpdateFpdetailBar(c *gin.Context) {
  3208. appG := app.Gin{C: c}
  3209. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3210. fsion := gofasion.NewFasion(string(dataByte))
  3211. pastureid := fsion.Get("pastureid").ValueStr()
  3212. id := fsion.Get("id").ValueStr()
  3213. tx := restful.Engine.NewSession()
  3214. tx.Begin()
  3215. 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 `,
  3216. pastureid, id).Query().List()
  3217. if err != nil {
  3218. logs.Error(err)
  3219. }
  3220. for _, fpd := range fpdList {
  3221. lpplandList, err := tx.SQL(` select lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  3222. where lppland.pastureid = ? and lppland.fpdid = ? order by lpp.sort desc `,
  3223. pastureid, fpd["id"]).Query().List()
  3224. if err != nil {
  3225. tx.Rollback()
  3226. logs.Error(err)
  3227. appG.Response(http.StatusOK, e.ERROR, false)
  3228. return
  3229. }
  3230. var lweight float64
  3231. for _, lppland := range lpplandList {
  3232. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3233. lweight += lweight1
  3234. }
  3235. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3236. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  3237. if fpdweight >= ptuse && lweight == ptuse {
  3238. continue
  3239. } else {
  3240. if lweight <= fpdweight {
  3241. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  3242. if err != nil {
  3243. tx.Rollback()
  3244. logs.Error(err)
  3245. appG.Response(http.StatusOK, e.ERROR, false)
  3246. return
  3247. }
  3248. } else {
  3249. weight := fpdweight - lweight
  3250. for _, lppland := range lpplandList {
  3251. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  3252. if weight >= lpplandlweight {
  3253. weight = weight - lpplandlweight
  3254. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  3255. if err != nil {
  3256. tx.Rollback()
  3257. logs.Error(err)
  3258. appG.Response(http.StatusOK, e.ERROR, false)
  3259. return
  3260. }
  3261. } else {
  3262. // _, err := tx.SQL(` update lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
  3263. // _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  3264. // if err != nil {
  3265. // tx.Rollback()
  3266. // logs.Error(err)
  3267. // appG.Response(http.StatusOK, e.ERROR, false)
  3268. // return
  3269. // }
  3270. weight = 0
  3271. break
  3272. }
  3273. }
  3274. }
  3275. }
  3276. }
  3277. for _, list := range fsion.Get("data").Array() {
  3278. ftmap := make(map[string]interface{})
  3279. ftmap["old"] = list.Get("old").ValueFloat64()
  3280. ftmap["new"] = list.Get("new").ValueFloat64()
  3281. ftmap["times"] = list.Get("times").ValueInt64()
  3282. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3283. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3284. // fmt.Println(ftmap)
  3285. fpdDataList, err := tx.SQL(`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(-1 ) ptsid ,
  3286. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  3287. WHERE fpdetail.pastureid = ? and barid =(select barid from feedp where id = ? ) and times = ?
  3288. UNION
  3289. 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 ,
  3290. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3291. WHERE fpdetail.pastureid = ? and barid = (select barid from feedp where id = ? ) and times = ? ) t
  3292. order by t.barname,t.times`, pastureid, id, ftmap["times"], pastureid, id, ftmap["times"]).Query().List()
  3293. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3294. if err != nil {
  3295. tx.Rollback()
  3296. logs.Error(err)
  3297. }
  3298. for _, fpd := range fpdDataList {
  3299. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  3300. fttype := -1
  3301. if ftmap["ptid"].(string) != "-1" {
  3302. fttype = 1
  3303. }
  3304. var fweight float64
  3305. var lweight float64
  3306. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3307. err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  3308. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  3309. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3310. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3311. if err != nil {
  3312. tx.Rollback()
  3313. logs.Error(err)
  3314. }
  3315. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3316. var w float64
  3317. var status int
  3318. fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
  3319. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  3320. if weight >= 0 {
  3321. continue
  3322. }
  3323. w = weight
  3324. status = 0
  3325. } else {
  3326. // continue
  3327. if weight <= 0 {
  3328. continue
  3329. }
  3330. w = weight
  3331. status = 1
  3332. }
  3333. for _, lppland := range lpplandtl1List {
  3334. lweight += lppland.Lweight
  3335. }
  3336. for _, lppland := range lpplandtl1List {
  3337. if status == 1 {
  3338. // if w <= lppland.Lweight {
  3339. if lppland.Maxweight <= lweight {
  3340. continue
  3341. }
  3342. if w+lweight <= lppland.Maxweight {
  3343. lppland.Lweight += w
  3344. lweight += w
  3345. fweight += w
  3346. w = 0
  3347. } else {
  3348. w = w - (lppland.Maxweight - lweight)
  3349. n := (lppland.Maxweight - lweight)
  3350. lppland.Lweight = lppland.Lweight + n
  3351. lweight += n
  3352. fweight += n
  3353. }
  3354. } else {
  3355. if lppland.Lweight == 0 {
  3356. continue
  3357. }
  3358. if w+lppland.Lweight >= 0 {
  3359. lppland.Lweight = lppland.Lweight + w
  3360. lweight = lweight + w
  3361. fweight = fweight + w
  3362. w = 0
  3363. } else {
  3364. w = w + lppland.Lweight
  3365. lweight = lweight - lppland.Lweight
  3366. fweight = fweight - lppland.Lweight
  3367. lppland.Lweight = 0
  3368. }
  3369. }
  3370. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3371. if err != nil {
  3372. tx.Rollback()
  3373. logs.Error(err)
  3374. return
  3375. }
  3376. break
  3377. }
  3378. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3379. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3380. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3381. if err != nil {
  3382. tx.Rollback()
  3383. logs.Error(err)
  3384. }
  3385. if w == 0 {
  3386. break
  3387. }
  3388. }
  3389. }
  3390. }
  3391. tx.Commit()
  3392. now := time.Now()
  3393. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3394. if err != nil {
  3395. logs.Error(err)
  3396. appG.Response(http.StatusOK, e.ERROR, false)
  3397. return
  3398. }
  3399. // newFpdDataList, err := tx.SQL(` select * from fpdetail where barid = ? and pastureid = ? `, id, pastureid).Query().List()
  3400. // if err != nil {
  3401. // logs.Error(err)
  3402. // appG.Response(http.StatusOK, e.ERROR, false)
  3403. // return
  3404. // }
  3405. // newFeedpList, err := tx.SQL(` select * from feedp where barid = ? and pastureid = ?`, id, pastureid).Query().List()
  3406. // if err != nil {
  3407. // logs.Error(err)
  3408. // appG.Response(http.StatusOK, e.ERROR, false)
  3409. // return
  3410. // }
  3411. for _, newLpplandtl1 := range newLpplandtl1List {
  3412. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3413. background,cowcount,ccountradio,lweighthis,createdate,userId)
  3414. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3415. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3416. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3417. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3418. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3419. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
  3420. if err != nil {
  3421. logs.Error(err)
  3422. appG.Response(http.StatusOK, e.ERROR, false)
  3423. return
  3424. }
  3425. }
  3426. appG.Response(http.StatusOK, e.SUCCESS, true)
  3427. }
  3428. func GetProcessAnalysis(c *gin.Context) {
  3429. appG := app.Gin{C: c}
  3430. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3431. fsion := gofasion.NewFasion(string(dataByte))
  3432. sqlnamestr := fsion.Get("name").ValueStr()
  3433. offset := fsion.Get("offset").ValueDefaultInt(0)
  3434. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3435. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3436. parammaps := fsion.Get("parammaps")
  3437. tx := restful.Engine.NewSession()
  3438. err := tx.Begin()
  3439. defer func() {
  3440. switch {
  3441. case err != nil:
  3442. logging.Error("tx.Begin 事务启动失败__error:", err)
  3443. if tx != nil {
  3444. tx.Rollback()
  3445. }
  3446. default:
  3447. if tx != nil {
  3448. err = tx.Commit()
  3449. }
  3450. }
  3451. if tx != nil {
  3452. tx.Close()
  3453. }
  3454. }()
  3455. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3456. s_params := make([]interface{}, 0)
  3457. paramslist := strings.Split(p, ",")
  3458. if len(paramslist) > 0 && p != "" {
  3459. for _, value := range paramslist {
  3460. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3461. if tempv, exists := c.Get("jwt_username"); exists {
  3462. s_params = append(s_params, tempv.(string))
  3463. } else {
  3464. s_params = append(s_params, "")
  3465. }
  3466. } else {
  3467. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3468. }
  3469. }
  3470. }
  3471. tmrtnameStr := ""
  3472. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3473. if len(tmrtnameStr) == 0 {
  3474. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3475. } else {
  3476. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3477. }
  3478. }
  3479. if len(tmrtnameStr) > 0 {
  3480. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3481. }
  3482. sql += " ORDER BY d.intime"
  3483. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3484. if err != nil {
  3485. logging.Error("GetDataByName err: ", err)
  3486. msg := geterrmsg(err.Error())
  3487. appG.Response(http.StatusOK, e.ERROR, msg)
  3488. } else {
  3489. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3490. }
  3491. }
  3492. func UpdateFeedtempletStatus(c *gin.Context) {
  3493. appG := app.Gin{C: c}
  3494. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3495. fsion := gofasion.NewFasion(string(dataByte))
  3496. parammaps := fsion.Get("parammaps")
  3497. tx := restful.Engine.NewSession()
  3498. tx.Begin()
  3499. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3500. if err != nil {
  3501. tx.Rollback()
  3502. logs.Error(err)
  3503. appG.Response(http.StatusOK, e.ERROR, err)
  3504. return
  3505. }
  3506. tx.Commit()
  3507. appG.Response(http.StatusOK, e.SUCCESS, true)
  3508. }
  3509. func AddFtdry(c *gin.Context) {
  3510. appG := app.Gin{C: c}
  3511. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3512. fsion := gofasion.NewFasion(string(dataByte))
  3513. sqlnamestr := fsion.Get("name").ValueStr()
  3514. s_params := make([]interface{}, 0)
  3515. tx := restful.Engine.NewSession()
  3516. err := tx.Begin()
  3517. defer func() {
  3518. switch {
  3519. case err != nil:
  3520. if tx != nil {
  3521. tx.Rollback()
  3522. }
  3523. default:
  3524. if tx != nil {
  3525. err = tx.Commit()
  3526. }
  3527. }
  3528. if tx != nil {
  3529. tx.Close()
  3530. }
  3531. }()
  3532. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3533. if sql != "" {
  3534. parammaps := fsion.Get("parammaps")
  3535. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3536. paramslist := strings.Split(p, ",")
  3537. if len(paramslist) > 0 && p != "" {
  3538. for _, value := range paramslist {
  3539. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3540. if tempv, exists := c.Get("jwt_username"); exists {
  3541. s_params = append(s_params, tempv.(string))
  3542. } else {
  3543. s_params = append(s_params, "")
  3544. }
  3545. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3546. ids, err := setting.SnowIds.NextId()
  3547. if err != nil {
  3548. ids = time.Now().UnixNano()
  3549. logging.Info("create SnowIds err", err)
  3550. }
  3551. s_params = append(s_params, ids)
  3552. } else {
  3553. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3554. }
  3555. }
  3556. }
  3557. var actweight float64
  3558. actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight from ftdry
  3559. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3560. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3561. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3562. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3563. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3564. 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()
  3565. if err != nil {
  3566. logging.Error("AddFtdry err: ", err)
  3567. msg := geterrmsg(err.Error())
  3568. appG.Response(http.StatusOK, e.ERROR, msg)
  3569. }
  3570. if len(actweightList) > 0 {
  3571. for _, item := range actweightList {
  3572. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3573. if err != nil {
  3574. logging.Error("AddFtdry err: ", err)
  3575. msg := geterrmsg(err.Error())
  3576. appG.Response(http.StatusOK, e.ERROR, msg)
  3577. }
  3578. actweight = fl
  3579. }
  3580. } else {
  3581. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3582. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3583. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3584. if err != nil {
  3585. logging.Error("AddFtdry err: ", err)
  3586. msg := geterrmsg(err.Error())
  3587. appG.Response(http.StatusOK, e.ERROR, msg)
  3588. }
  3589. for _, item := range dryList {
  3590. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3591. if err != nil {
  3592. logging.Error("AddFtdry err: ", err)
  3593. msg := geterrmsg(err.Error())
  3594. appG.Response(http.StatusOK, e.ERROR, msg)
  3595. }
  3596. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3597. }
  3598. }
  3599. if sqlnamestr == "insertFtdry" {
  3600. s_params = append(s_params, actweight)
  3601. } else if sqlnamestr == "updateFtdry" {
  3602. sql = fmt.Sprintf(sql, actweight)
  3603. }
  3604. queryData, err := execDataBySqlT(sql, s_params, tx)
  3605. if err != nil {
  3606. logging.Error("AddFtdry err: ", err)
  3607. msg := geterrmsg(err.Error())
  3608. appG.Response(http.StatusOK, e.ERROR, msg)
  3609. } else {
  3610. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3611. }
  3612. } else {
  3613. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3614. }
  3615. }
  3616. func CheckDates(c *gin.Context) {
  3617. tx := restful.Engine.NewSession()
  3618. defer tx.Close()
  3619. appG := app.Gin{C: c}
  3620. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3621. tempval_ := make(map[string]interface{})
  3622. tempCommon := make(map[string]interface{})
  3623. tempval := make([]map[string]interface{}, 0)
  3624. err := json.Unmarshal(dataByte, &tempval_)
  3625. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3626. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3627. if err != nil {
  3628. } else {
  3629. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3630. tempCommon = v
  3631. }
  3632. if v, ok := tempval_["data"].([]interface{}); ok {
  3633. for _, Tvalue := range v {
  3634. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3635. tempval = append(tempval, v1)
  3636. }
  3637. }
  3638. }
  3639. if err == nil {
  3640. if tempv, exists := c.Get("jwt_username"); exists {
  3641. tempCommon["jwt_username"] = tempv.(string)
  3642. }
  3643. for _, paramvalue := range tempval {
  3644. if _, ok := paramvalue["resultname"]; !ok {
  3645. paramvalue["resultname"] = paramvalue["name"]
  3646. }
  3647. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3648. if err != nil {
  3649. logging.Error("ExecDataParam error:", err)
  3650. }
  3651. }
  3652. if err == nil {
  3653. vmsg := ""
  3654. for _, item := range tempval {
  3655. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3656. for _, childrenList := range list.([]interface{}) {
  3657. for k, children := range childrenList.(map[string]interface{}) {
  3658. if k != "children" {
  3659. continue
  3660. }
  3661. for _, v := range children.([]map[string]interface{}) {
  3662. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3663. if k1 == "list" {
  3664. for _, v2 := range v1.([]map[string]interface{}) {
  3665. if v2["vmsg"].(string) != "1" {
  3666. if len(vmsg) == 0 {
  3667. vmsg = v2["vmsg"].(string)
  3668. } else {
  3669. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3670. }
  3671. }
  3672. }
  3673. }
  3674. }
  3675. }
  3676. }
  3677. }
  3678. }
  3679. }
  3680. if len(vmsg) > 0 {
  3681. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3682. } else {
  3683. appG.Response(http.StatusOK, e.SUCCESS, true)
  3684. }
  3685. } else {
  3686. msg := geterrmsg(err.Error())
  3687. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3688. }
  3689. }
  3690. }
  3691. if err != nil {
  3692. msg := geterrmsg(err.Error())
  3693. appG.Response(http.StatusOK, e.ERROR, msg)
  3694. }
  3695. }
  3696. 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) {
  3697. sqlname := fasion["name"].(string)
  3698. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3699. if v, ok := fasion["type"]; ok {
  3700. sqltype = v.(string)
  3701. }
  3702. sql := ""
  3703. p := ""
  3704. s_params := make([]interface{}, 0)
  3705. if sqltype != "" {
  3706. sql, p = restful.GetSqlByName(sqlname, tx)
  3707. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3708. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3709. paramslist := strings.Split(p, ",")
  3710. if len(paramslist) > 0 && p != "" {
  3711. for _, value := range paramslist {
  3712. ss := ""
  3713. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3714. ids, err := setting.SnowIds.NextId()
  3715. if err != nil {
  3716. ids = time.Now().UnixNano()
  3717. logging.Info("create SnowIds err", err)
  3718. }
  3719. s_params = append(s_params, ids)
  3720. } else {
  3721. if ss == "" && CommonParamMap != nil {
  3722. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3723. ss = valuestring
  3724. tempstrb := strings.IndexAny(valuestring, "@")
  3725. tempstre := strings.IndexAny(valuestring, ".")
  3726. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3727. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3728. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3729. }
  3730. } else {
  3731. ss = ""
  3732. }
  3733. }
  3734. }
  3735. if ss == "" && ParentParamMap != nil {
  3736. ss = getParamValue_(v, value, ParentParamMap)
  3737. }
  3738. if ss == "" && sameParamMap != nil {
  3739. ss = getParamValue(v, value, sameParamMap)
  3740. }
  3741. if ss == "" && ParamMap != nil {
  3742. ss = getParamValue(v, value, ParamMap)
  3743. }
  3744. s_params = append(s_params, ss)
  3745. }
  3746. }
  3747. }
  3748. }
  3749. }
  3750. if sql == "" {
  3751. sqltype = ""
  3752. }
  3753. if sql != "" {
  3754. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3755. if err != nil {
  3756. return nil, err
  3757. }
  3758. // fmt.Println(tempValParam)
  3759. return tempValParam.(map[string]interface{}), nil
  3760. } else {
  3761. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3762. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3763. if err != nil {
  3764. return nil, err
  3765. }
  3766. return nil, err
  3767. }
  3768. }
  3769. return nil, nil
  3770. }
  3771. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3772. var err error
  3773. subarray, ok := fasion["children"]
  3774. if ok {
  3775. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3776. tempVal_arrary := make([]map[string]interface{}, 0)
  3777. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3778. tempVal_ := make(map[string]interface{})
  3779. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3780. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3781. } else {
  3782. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3783. }
  3784. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3785. if err != nil {
  3786. return err
  3787. }
  3788. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3789. }
  3790. v.(map[string]interface{})["children"] = tempVal_arrary
  3791. }
  3792. }
  3793. return nil
  3794. }
  3795. func FpdImportExcel(c *gin.Context) {
  3796. appG := app.Gin{C: c}
  3797. inputdata := ""
  3798. c.Request.ParseForm()
  3799. params := c.Request.Form
  3800. file, _, err := c.Request.FormFile("file")
  3801. if err != nil {
  3802. appG.Response(http.StatusOK, e.ERROR, err)
  3803. return
  3804. }
  3805. sqlnamestrs := params.Get("name")
  3806. sheetname := params.Get("sheetname")
  3807. pastureid := params.Get("pastureid")
  3808. // importParams := params.Get("importParams")
  3809. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3810. // 必输项参数 (字符串格式 "field1,field2,field3")
  3811. requiredParams := params.Get("requiredParams")
  3812. // 日期参数
  3813. dateParams := params.Get("dateParams")
  3814. // 数字参数
  3815. numParams := params.Get("numParams")
  3816. //将字符串分割开
  3817. dateParamslist := strings.Split(dateParams, ",")
  3818. requiredParamslist := strings.Split(requiredParams, ",")
  3819. numParamslist := strings.Split(numParams, ",")
  3820. queryData := make([]interface{}, 0)
  3821. sqlslist := strings.Split(sqlnamestrs, ",")
  3822. xlsx1, err := excelize.OpenReader(file)
  3823. if err != nil {
  3824. fmt.Println(err)
  3825. return
  3826. }
  3827. ok := 0
  3828. error := 0
  3829. isdone := true
  3830. tx := restful.Engine.NewSession()
  3831. defer tx.Close()
  3832. 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
  3833. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3834. if err != nil {
  3835. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3836. return
  3837. }
  3838. rows, _ := xlsx1.GetRows(sheetname)
  3839. // 限制10000条,多余的截取掉
  3840. if len(rows) > 10000 {
  3841. rows = rows[:10000]
  3842. }
  3843. for i, row := range rows {
  3844. if i > 0 {
  3845. entry := make(map[string]interface{})
  3846. outentry := make(map[string]interface{})
  3847. for j, colCell := range rows[0] {
  3848. for k, colCell1 := range row {
  3849. if j == k {
  3850. outentry[colCell] = colCell1
  3851. entry[colCell] = colCell1
  3852. }
  3853. }
  3854. }
  3855. inputdata = ""
  3856. a := ""
  3857. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3858. //校验日期格式
  3859. for _, v := range dateParamslist {
  3860. if v == "" {
  3861. continue
  3862. }
  3863. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3864. dtime, err := TransfTime(d.(string))
  3865. if err != nil {
  3866. a = strings.Trim(v, " ")
  3867. break
  3868. }
  3869. outentry[strings.Trim(v, " ")] = dtime
  3870. }
  3871. }
  3872. if a != "" {
  3873. outentry["error_msg"] = a + " 格式错误"
  3874. error++
  3875. queryData = append(queryData, outentry)
  3876. continue
  3877. }
  3878. a = ""
  3879. //校验必填格式
  3880. for _, v := range requiredParamslist {
  3881. if v == "" {
  3882. continue
  3883. }
  3884. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3885. a = strings.Trim(v, " ")
  3886. break
  3887. }
  3888. }
  3889. if a != "" {
  3890. outentry["error_msg"] = a + " 未填或格式错误"
  3891. error++
  3892. queryData = append(queryData, outentry)
  3893. continue
  3894. }
  3895. a = ""
  3896. //校验数字格式
  3897. for _, v := range numParamslist {
  3898. if v == "" {
  3899. continue
  3900. }
  3901. d, ok := outentry[strings.Trim(v, " ")]
  3902. if !ok || d == "" {
  3903. outentry[strings.Trim(v, " ")] = 0
  3904. } else {
  3905. var fl float64
  3906. switch d.(type) {
  3907. case string:
  3908. fl, err = strconv.ParseFloat(d.(string), 64)
  3909. }
  3910. if err != nil || fl < 0 {
  3911. a = strings.Trim(v, " ")
  3912. break
  3913. }
  3914. }
  3915. }
  3916. if a != "" {
  3917. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3918. error++
  3919. queryData = append(queryData, outentry)
  3920. continue
  3921. }
  3922. errExist := false
  3923. for _, sqlnamestr := range sqlslist {
  3924. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3925. paramslist := strings.Split(paramslists, ",")
  3926. if len(paramslist) > 0 {
  3927. s_params := make([]interface{}, 0)
  3928. for _, value := range paramslist {
  3929. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3930. if tempv, exists := c.Get("jwt_username"); exists {
  3931. s_params = append(s_params, tempv.(string))
  3932. } else {
  3933. s_params = append(s_params, "")
  3934. }
  3935. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3936. s_params = append(s_params, pastureid)
  3937. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3938. ids, err := setting.SnowIds.NextId()
  3939. if err != nil {
  3940. ids = time.Now().UnixNano()
  3941. logging.Info("create SnowIds err", err)
  3942. }
  3943. s_params = append(s_params, ids)
  3944. } else {
  3945. if outentry[strings.Trim(value, " ")] == nil {
  3946. s_params = append(s_params, "")
  3947. } else {
  3948. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3949. }
  3950. }
  3951. }
  3952. outentry["input"] = inputdata
  3953. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3954. if err != nil {
  3955. errExist = true
  3956. // if tx != nil {
  3957. // tx.Rollback()
  3958. // }
  3959. // if tx != nil {
  3960. // tx.Close()
  3961. // }
  3962. msg := geterrmsg(err.Error())
  3963. outentry["error_msg"] = msg
  3964. error++
  3965. queryData = append(queryData, outentry)
  3966. isdone = true
  3967. break
  3968. } else {
  3969. if len(returnmsgmap1) > 0 {
  3970. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3971. // if tx != nil {
  3972. // tx.Rollback()
  3973. // }
  3974. // if tx != nil {
  3975. // tx.Close()
  3976. // }
  3977. msg := geterrmsg(va.(string))
  3978. outentry["error_msg"] = msg
  3979. error++
  3980. queryData = append(queryData, outentry)
  3981. isdone = true
  3982. break
  3983. }
  3984. }
  3985. isdone = false
  3986. }
  3987. }
  3988. }
  3989. if !errExist {
  3990. dataexcel := make(map[string]interface{}, 0)
  3991. if _, ok := outentry["栏舍名称"]; ok {
  3992. dataexcel["barname"] = outentry["栏舍名称"]
  3993. }
  3994. if _, ok := outentry["实际牛头数"]; ok {
  3995. dataexcel["ccount"] = outentry["实际牛头数"]
  3996. }
  3997. if _, ok := outentry["系数(%)"]; ok {
  3998. dataexcel["ratio"] = outentry["系数(%)"]
  3999. }
  4000. if _, ok := outentry["配方模板"]; ok {
  4001. dataexcel["ftname"] = outentry["配方模板"]
  4002. }
  4003. if _, ok := outentry["补料配方"]; ok {
  4004. dataexcel["ptsfname"] = outentry["补料配方"]
  4005. }
  4006. if _, ok := outentry["第一班比例(%)"]; ok {
  4007. dataexcel["1"] = outentry["第一班比例(%)"]
  4008. }
  4009. if _, ok := outentry["第二班比例(%)"]; ok {
  4010. dataexcel["2"] = outentry["第二班比例(%)"]
  4011. }
  4012. if _, ok := outentry["第三班比例(%)"]; ok {
  4013. dataexcel["3"] = outentry["第三班比例(%)"]
  4014. }
  4015. if _, ok := outentry["第四班比例(%)"]; ok {
  4016. dataexcel["4"] = outentry["第四班比例(%)"]
  4017. }
  4018. if _, ok := outentry["第五班比例(%)"]; ok {
  4019. dataexcel["5"] = outentry["第四班比例(%)"]
  4020. }
  4021. if _, ok := outentry["第六班比例(%)"]; ok {
  4022. dataexcel["6"] = outentry["第六班比例(%)"]
  4023. }
  4024. existbar, err := tx.SQL(` select id from bar where bname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4025. if err != nil {
  4026. logs.Error(err)
  4027. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4028. return
  4029. }
  4030. if !existbar {
  4031. continue
  4032. }
  4033. ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
  4034. if err != nil {
  4035. logs.Error(err)
  4036. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4037. return
  4038. }
  4039. if !ftexist {
  4040. fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
  4041. tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4042. if err != nil {
  4043. logs.Error(err)
  4044. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4045. return
  4046. }
  4047. tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4048. if err != nil {
  4049. logs.Error(err)
  4050. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4051. return
  4052. }
  4053. }
  4054. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  4055. if err != nil {
  4056. logs.Error(err)
  4057. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4058. return
  4059. }
  4060. if !exist {
  4061. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  4062. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  4063. if err != nil {
  4064. logs.Error(err)
  4065. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4066. return
  4067. }
  4068. }
  4069. var feedpargs []interface{}
  4070. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  4071. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  4072. if _, ok := dataexcel["ftname"]; ok {
  4073. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  4074. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  4075. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  4076. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  4077. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4078. } else {
  4079. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  4080. }
  4081. if _, ok := dataexcel["ptsfname"]; ok {
  4082. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  4083. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  4084. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  4085. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  4086. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  4087. } else {
  4088. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  4089. }
  4090. upFeedpSql += " where barname = ? and pastureid = ? "
  4091. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  4092. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  4093. if err != nil {
  4094. logs.Error(err)
  4095. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4096. return
  4097. }
  4098. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
  4099. if err != nil {
  4100. logs.Error(err)
  4101. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4102. return
  4103. }
  4104. if !exist1 {
  4105. _, 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) `,
  4106. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4107. if err != nil {
  4108. logs.Error(err)
  4109. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4110. return
  4111. }
  4112. }
  4113. exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
  4114. if err != nil {
  4115. logs.Error(err)
  4116. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4117. return
  4118. }
  4119. if !exist2 {
  4120. _, 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) `,
  4121. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4122. if err != nil {
  4123. logs.Error(err)
  4124. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4125. return
  4126. }
  4127. }
  4128. exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
  4129. if err != nil {
  4130. logs.Error(err)
  4131. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4132. return
  4133. }
  4134. if !exist3 {
  4135. _, 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) `,
  4136. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4137. if err != nil {
  4138. logs.Error(err)
  4139. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4140. return
  4141. }
  4142. }
  4143. exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
  4144. if err != nil {
  4145. logs.Error(err)
  4146. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4147. return
  4148. }
  4149. if !exist4 {
  4150. _, 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) `,
  4151. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4152. if err != nil {
  4153. logs.Error(err)
  4154. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4155. return
  4156. }
  4157. }
  4158. exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
  4159. if err != nil {
  4160. logs.Error(err)
  4161. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4162. return
  4163. }
  4164. if !exist5 {
  4165. _, 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) `,
  4166. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4167. if err != nil {
  4168. logs.Error(err)
  4169. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4170. return
  4171. }
  4172. }
  4173. exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
  4174. if err != nil {
  4175. logs.Error(err)
  4176. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4177. return
  4178. }
  4179. if !exist6 {
  4180. _, 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) `,
  4181. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  4182. if err != nil {
  4183. logs.Error(err)
  4184. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4185. return
  4186. }
  4187. }
  4188. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4189. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4190. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4191. and pastureid = ? and times = ?`
  4192. var fpdargs1 []interface{}
  4193. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  4194. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4195. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  4196. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  4197. if err != nil {
  4198. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4199. return
  4200. }
  4201. var fpdargs2 []interface{}
  4202. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4203. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4204. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4205. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4206. if err != nil {
  4207. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4208. return
  4209. }
  4210. var fpdargs3 []interface{}
  4211. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4212. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4213. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4214. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4215. if err != nil {
  4216. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4217. return
  4218. }
  4219. var fpdargs4 []interface{}
  4220. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4221. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4222. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4223. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4224. if err != nil {
  4225. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4226. return
  4227. }
  4228. var fpdargs5 []interface{}
  4229. fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  4230. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4231. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  4232. _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  4233. if err != nil {
  4234. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4235. return
  4236. }
  4237. var fpdargs6 []interface{}
  4238. fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  4239. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4240. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  4241. _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  4242. if err != nil {
  4243. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4244. return
  4245. }
  4246. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4247. 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()
  4248. if err != nil {
  4249. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4250. return
  4251. }
  4252. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4253. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4254. upFpdetailList := make([]*upFpdetail, 0)
  4255. for _, newfpd := range newList {
  4256. for _, oldfpd := range oldFpdList {
  4257. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4258. var oldweight, newweight float64
  4259. if oldfpd["weight"] != nil {
  4260. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4261. }
  4262. if newfpd["weight"] != nil {
  4263. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4264. }
  4265. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4266. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4267. Old: oldweight,
  4268. New: newweight,
  4269. Times: newfpd["times"].(int64),
  4270. Ptid: newfpd["ptid"].(int64),
  4271. Fweight: fweight,
  4272. Id: oldfpd["id"].(int64),
  4273. })
  4274. break
  4275. }
  4276. }
  4277. }
  4278. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4279. }
  4280. }
  4281. if !isdone {
  4282. ok++
  4283. isdone = true
  4284. }
  4285. }
  4286. data := make(map[string]interface{})
  4287. data["result"] = queryData
  4288. data["success"] = ok
  4289. data["err_count"] = error
  4290. appG.Response(http.StatusOK, e.SUCCESS, data)
  4291. }
  4292. type upFpdetail struct {
  4293. Old float64
  4294. New float64
  4295. Times int64
  4296. Ptid int64
  4297. Fweight float64
  4298. Id int64
  4299. // Ptsid string
  4300. }
  4301. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  4302. tx := restful.Engine.NewSession()
  4303. defer tx.Close()
  4304. tx.Begin()
  4305. 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 `,
  4306. pastureid, barname).Query().List()
  4307. if err != nil {
  4308. logs.Error(err)
  4309. }
  4310. for _, fpd := range fpdList {
  4311. lpplandList, err := tx.SQL(` select lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid
  4312. where lppland.pastureid = ? and lppland.fpdid = ? and lpp.times = ? order by lpp.sort desc `,
  4313. pastureid, fpd["id"], fpd["times"]).Query().List()
  4314. if err != nil {
  4315. tx.Rollback()
  4316. logs.Error(err)
  4317. return err
  4318. }
  4319. var lweight float64
  4320. for _, lppland := range lpplandList {
  4321. lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4322. lweight += lweight1
  4323. }
  4324. fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4325. ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4326. if fpdweight >= ptuse && lweight == ptuse {
  4327. continue
  4328. } else {
  4329. if lweight <= fpdweight {
  4330. _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
  4331. if err != nil {
  4332. tx.Rollback()
  4333. logs.Error(err)
  4334. return err
  4335. }
  4336. } else {
  4337. weight := lweight - fpdweight
  4338. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
  4339. WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
  4340. if err != nil {
  4341. tx.Rollback()
  4342. logs.Error(err)
  4343. return err
  4344. }
  4345. for _, lppland := range lpplandList {
  4346. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4347. if weight >= lpplandlweight {
  4348. weight = weight - lpplandlweight
  4349. _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
  4350. if err != nil {
  4351. tx.Rollback()
  4352. logs.Error(err)
  4353. return err
  4354. }
  4355. } else {
  4356. lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
  4357. _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
  4358. if err != nil {
  4359. tx.Rollback()
  4360. logs.Error(err)
  4361. return err
  4362. }
  4363. weight = 0
  4364. break
  4365. }
  4366. }
  4367. }
  4368. }
  4369. }
  4370. for _, list := range dataList {
  4371. ftmap := make(map[string]interface{})
  4372. ftmap["old"] = list.Old
  4373. ftmap["new"] = list.New
  4374. ftmap["times"] = list.Times
  4375. ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
  4376. ftmap["ptsid"] = ""
  4377. // fmt.Println(ftmap)
  4378. fpdDataList, err := tx.SQL(`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 ,
  4379. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  4380. WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  4381. UNION
  4382. 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 ,
  4383. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  4384. WHERE fpdetail.pastureid = ? and barname = ? and times = ? ) t
  4385. order by t.barname,t.times`, pastureid, barname, ftmap["times"], pastureid, barname, ftmap["times"]).Query().List()
  4386. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  4387. if err != nil {
  4388. tx.Rollback()
  4389. logs.Error(err)
  4390. }
  4391. for _, fpd := range fpdDataList {
  4392. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  4393. fttype := -1
  4394. if ftmap["ptid"].(string) != "-1" {
  4395. fttype = 1
  4396. }
  4397. var fweight float64
  4398. var lweight float64
  4399. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4400. err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4401. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4402. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4403. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  4404. if err != nil {
  4405. tx.Rollback()
  4406. logs.Error(err)
  4407. }
  4408. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4409. // ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
  4410. var w float64
  4411. var status int
  4412. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  4413. if weight >= 0 {
  4414. continue
  4415. }
  4416. w = weight
  4417. status = 0
  4418. } else {
  4419. if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  4420. continue
  4421. }
  4422. w = weight
  4423. status = 1
  4424. }
  4425. for _, lppland := range lpplandtl1List {
  4426. lweight += lppland.Lweight
  4427. }
  4428. for _, lppland := range lpplandtl1List {
  4429. if status == 1 {
  4430. // if w <= lppland.Lweight {
  4431. if lppland.Maxweight <= lweight {
  4432. continue
  4433. }
  4434. if w+lweight <= lppland.Maxweight {
  4435. lppland.Lweight += w
  4436. lweight += w
  4437. fweight += w
  4438. w = 0
  4439. } else {
  4440. w = w - (lppland.Maxweight - lweight)
  4441. n := (lppland.Maxweight - lweight)
  4442. lppland.Lweight = lppland.Lweight + n
  4443. lweight += n
  4444. fweight += n
  4445. }
  4446. } else {
  4447. if lppland.Lweight == 0 {
  4448. continue
  4449. }
  4450. if w+lppland.Lweight >= 0 {
  4451. lppland.Lweight = lppland.Lweight + w
  4452. lweight = lweight + w
  4453. fweight = fweight + w
  4454. w = 0
  4455. } else {
  4456. w = w + lppland.Lweight
  4457. lweight = lweight - lppland.Lweight
  4458. fweight = fweight - lppland.Lweight
  4459. lppland.Lweight = 0
  4460. }
  4461. }
  4462. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4463. if err != nil {
  4464. tx.Rollback()
  4465. logs.Error(err)
  4466. return err
  4467. }
  4468. break
  4469. }
  4470. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4471. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4472. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  4473. if err != nil {
  4474. tx.Rollback()
  4475. logs.Error(err)
  4476. }
  4477. if w == 0 {
  4478. break
  4479. }
  4480. }
  4481. }
  4482. }
  4483. // for _, data := range dataList {
  4484. // fttype := -1
  4485. // if data.Ptid != -1 {
  4486. // fttype = 1
  4487. // }
  4488. // var fweight float64
  4489. // var lweight float64
  4490. // lpplandtl1List := make([]*lpplandtlInfo, 0)
  4491. // err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4492. // join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4493. // and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4494. // data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  4495. // if err != nil {
  4496. // tx.Rollback()
  4497. // logs.Error(err)
  4498. // return err
  4499. // }
  4500. // weight := data.Fweight
  4501. // // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4502. // var w float64
  4503. // var status int
  4504. // if data.New < data.Old {
  4505. // if weight >= 0 {
  4506. // continue
  4507. // }
  4508. // w = weight
  4509. // status = 0
  4510. // } else {
  4511. // // if weight-(data.New-data.Old) > 0 {
  4512. // // continue
  4513. // // }
  4514. // w = data.New - data.Old
  4515. // status = 1
  4516. // }
  4517. // for _, lppland := range lpplandtl1List {
  4518. // var lppdata lpplandtlInfo
  4519. // tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  4520. // lppland.Lppid, pastureid).GetFirst(&lppdata)
  4521. // if err != nil {
  4522. // tx.Rollback()
  4523. // logs.Error(err)
  4524. // return err
  4525. // }
  4526. // lweight = lppdata.Lweight
  4527. // if status == 1 {
  4528. // // if w <= lppland.Lweight {
  4529. // if lppland.Maxweight <= lweight {
  4530. // continue
  4531. // }
  4532. // if w+lweight <= lppland.Maxweight {
  4533. // lppland.Lweight += w
  4534. // lweight += w
  4535. // fweight += w
  4536. // w = 0
  4537. // } else {
  4538. // w = w - (lppland.Maxweight - lweight)
  4539. // n := (lppland.Maxweight - lweight)
  4540. // lppland.Lweight = lppland.Lweight + n
  4541. // lweight += n
  4542. // fweight += n
  4543. // }
  4544. // } else {
  4545. // if lppland.Lweight == 0 {
  4546. // continue
  4547. // }
  4548. // if w+lppland.Lweight >= 0 {
  4549. // lppland.Lweight = lppland.Lweight + w
  4550. // lweight = lweight + w
  4551. // fweight = fweight + w
  4552. // w = 0
  4553. // } else {
  4554. // w = w + lppland.Lweight
  4555. // lweight = lweight - lppland.Lweight
  4556. // fweight = fweight - lppland.Lweight
  4557. // lppland.Lweight = 0
  4558. // }
  4559. // }
  4560. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4561. // if err != nil {
  4562. // tx.Rollback()
  4563. // logs.Error(err)
  4564. // return err
  4565. // }
  4566. // break
  4567. // }
  4568. // _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4569. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4570. // WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  4571. // if err != nil {
  4572. // tx.Rollback()
  4573. // logs.Error(err)
  4574. // return err
  4575. // }
  4576. // // if w == 0 {
  4577. // // break
  4578. // // }
  4579. // // }
  4580. // }
  4581. err = tx.Commit()
  4582. if err != nil {
  4583. logs.Error(err)
  4584. tx.Rollback()
  4585. return err
  4586. }
  4587. now := time.Now()
  4588. newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4589. if err != nil {
  4590. logs.Error(err)
  4591. return nil
  4592. }
  4593. newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4594. if err != nil {
  4595. logs.Error(err)
  4596. return nil
  4597. }
  4598. newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
  4599. if err != nil {
  4600. logs.Error(err)
  4601. return nil
  4602. }
  4603. for _, newLpplandtl1 := range newLpplandtl1List {
  4604. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4605. background,cowcount,ccountradio,lweighthis,createdate)
  4606. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4607. newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  4608. newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  4609. newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  4610. newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  4611. newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  4612. if err != nil {
  4613. logs.Error(err)
  4614. // appG.Response(http.StatusOK, e.ERROR, false)
  4615. return nil
  4616. }
  4617. }
  4618. for _, newFpd := range newFpdDataList {
  4619. _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  4620. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  4621. newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  4622. newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  4623. if err != nil {
  4624. logs.Error(err)
  4625. // appG.Response(http.StatusOK, e.ERROR, false)
  4626. return nil
  4627. }
  4628. }
  4629. for _, newFeedp := range newFeedpList {
  4630. _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  4631. ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  4632. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4633. newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  4634. newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  4635. newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  4636. newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  4637. newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  4638. if err != nil {
  4639. logs.Error(err)
  4640. // appG.Response(http.StatusOK, e.ERROR, false)
  4641. return nil
  4642. }
  4643. }
  4644. return nil
  4645. }
  4646. func DeleteFTdetail(c *gin.Context) {
  4647. appG := app.Gin{C: c}
  4648. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4649. fsion := gofasion.NewFasion(string(dataByte))
  4650. parammaps := fsion.Get("parammaps")
  4651. pastureid := parammaps.Get("pastureid").ValueStr()
  4652. ftid := parammaps.Get("ftid").ValueStr()
  4653. tx := restful.Engine.NewSession()
  4654. defer tx.Close()
  4655. tx.Begin()
  4656. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  4657. if err != nil {
  4658. tx.Rollback()
  4659. logs.Error(err)
  4660. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4661. return
  4662. }
  4663. if parammaps.Get("type").ValueStr() == "1" {
  4664. _, err := tx.SQL(`UPDATE feedp fp
  4665. set
  4666. fp.ftweight= IFNULL(IF(
  4667. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4668. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4669. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4670. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4671. ),0),fp.feedweight = IFNULL(IF(
  4672. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4673. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4674. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4675. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4676. ),0) +ifnull(fp.supplyweight,0)
  4677. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4678. if err != nil {
  4679. tx.Rollback()
  4680. logs.Error(err)
  4681. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4682. return
  4683. }
  4684. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  4685. _, err = tx.SQL(`
  4686. UPDATE fpdetail fpd
  4687. INNER JOIN feedp fp
  4688. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4689. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4690. ptuse= 0
  4691. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4692. if err != nil {
  4693. tx.Rollback()
  4694. logs.Error(err)
  4695. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4696. return
  4697. }
  4698. } else {
  4699. _, err := tx.SQL(`UPDATE feedp fp
  4700. SET
  4701. fp.supplyweight= IFNULL(IF(
  4702. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4703. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4704. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4705. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4706. ),0),fp.feedweight = IFNULL(IF(
  4707. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4708. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4709. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4710. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4711. ),0) + ifnull(fp.supplyweight,0)
  4712. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4713. if err != nil {
  4714. tx.Rollback()
  4715. logs.Error(err)
  4716. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4717. return
  4718. }
  4719. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4720. _, err = tx.SQL(`
  4721. UPDATE fpdetail fpd
  4722. INNER JOIN feedp fp
  4723. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4724. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4725. ptsrate = 0
  4726. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4727. if err != nil {
  4728. tx.Rollback()
  4729. logs.Error(err)
  4730. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4731. return
  4732. }
  4733. }
  4734. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  4735. if err != nil {
  4736. tx.Rollback()
  4737. logs.Error(err)
  4738. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4739. return
  4740. }
  4741. err = tx.Commit()
  4742. if err != nil {
  4743. tx.Rollback()
  4744. logs.Error(err)
  4745. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4746. return
  4747. }
  4748. appG.Response(http.StatusOK, e.SUCCESS, true)
  4749. }
  4750. func DeleteSpillageAll(c *gin.Context) {
  4751. appG := app.Gin{C: c}
  4752. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4753. fsion := gofasion.NewFasion(string(dataByte))
  4754. parammaps := fsion.Get("parammaps")
  4755. pastureid := parammaps.Get("pastureid").ValueStr()
  4756. times := parammaps.Get("times").ValueStr()
  4757. barid := parammaps.Get("barid").ValueStr()
  4758. tx := restful.Engine.NewSession()
  4759. defer tx.Close()
  4760. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  4761. if err != nil {
  4762. logs.Error(err)
  4763. appG.Response(http.StatusOK, e.ERROR, false)
  4764. return
  4765. }
  4766. now := time.Now()
  4767. for _, item := range lpplandtl1List {
  4768. go func(item map[string]interface{}) {
  4769. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4770. background,cowcount,ccountradio,lweighthis,createdate)
  4771. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4772. item["pastureid"], item["lppid"], item["barid"],
  4773. item["barname"], item["fpdid"], item["fttype"],
  4774. item["lweight"], item["sort"], item["tmrid"],
  4775. item["tmrname"], item["background"], item["cowcount"],
  4776. item["ccountradio"], item["lweighthis"], now).Execute()
  4777. if err != nil {
  4778. logs.Error(err)
  4779. appG.Response(http.StatusOK, e.ERROR, false)
  4780. return
  4781. }
  4782. }(item)
  4783. }
  4784. tx.Begin()
  4785. _, 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()
  4786. if err != nil {
  4787. tx.Rollback()
  4788. logs.Error(err)
  4789. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4790. return
  4791. }
  4792. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4793. WHERE pastureid=? and times = ? and find_in_set(barid,?) `, pastureid, times, barid).Execute()
  4794. if err != nil {
  4795. tx.Rollback()
  4796. logs.Error(err)
  4797. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4798. return
  4799. }
  4800. err = tx.Commit()
  4801. if err != nil {
  4802. tx.Rollback()
  4803. logs.Error(err)
  4804. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4805. return
  4806. }
  4807. appG.Response(http.StatusOK, e.SUCCESS, true)
  4808. }
  4809. func GetTMRListEnableTypeAll(c *gin.Context) {
  4810. appG := app.Gin{C: c}
  4811. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4812. fsion := gofasion.NewFasion(string(dataByte))
  4813. parammaps := fsion.Get("parammaps")
  4814. pastureid := parammaps.Get("pastureid").ValueStr()
  4815. tx := restful.Engine.NewSession()
  4816. defer tx.Close()
  4817. dataList, err := tx.SQL(`SELECT
  4818. eqcode,
  4819. tname,
  4820. datacaptureno,
  4821. trim(tclassid) tclassid,
  4822. concat(tname,' / ',eqcode) tmrmix,
  4823. d.label tclassname,
  4824. maxstirfeed,
  4825. remark,
  4826. tmr.enable,
  4827. TRIM(tmr.id) id,
  4828. TRIM(tmr.pastureid)pastureid
  4829. FROM
  4830. tmr
  4831. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  4832. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  4833. ORDER BY id DESC`, pastureid).Query().List()
  4834. if err != nil {
  4835. logs.Error(err)
  4836. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4837. return
  4838. }
  4839. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  4840. if err != nil {
  4841. logs.Error(err)
  4842. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4843. return
  4844. }
  4845. var carNum int64
  4846. for _, sysopt := range sysoptData {
  4847. if sysopt["inforvalue"] == nil {
  4848. carNum = 1
  4849. } else {
  4850. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  4851. }
  4852. }
  4853. id := 200
  4854. n := 0
  4855. for i := carNum; i > 0; i-- {
  4856. id++
  4857. n++
  4858. data := make(map[string]interface{}, 0)
  4859. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  4860. data["tname"] = fmt.Sprintf("任意车%d", n)
  4861. data["datacaptureno"] = -2
  4862. data["tclassid"] = -2
  4863. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  4864. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  4865. data["maxstirfeed"] = 100000
  4866. data["remark"] = fmt.Sprintf("任意车%d", n)
  4867. data["enable"] = 1
  4868. data["id"] = fmt.Sprintf("%d", id)
  4869. data["pastureid"] = pastureid
  4870. dataList = append(dataList, data)
  4871. }
  4872. // UNION ALL
  4873. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  4874. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4875. }
  4876. func GetFeedpHistory(c *gin.Context) {
  4877. appG := app.Gin{C: c}
  4878. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4879. fsion := gofasion.NewFasion(string(dataByte))
  4880. // parammaps := fsion.Get("parammaps")
  4881. bar := fsion.Get("barname").ValueStr()
  4882. startDate := fsion.Get("startDate").ValueStr()
  4883. endDate := fsion.Get("endDate").ValueStr()
  4884. tx := restful.Engine.NewSession()
  4885. defer tx.Close()
  4886. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4887. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,(select empname from user where id = feedphistory.userId)empname from feedphistory where barname = ?
  4888. and createdate between ? and ? order by createdate desc `, bar, startDate, endDate).Query().List()
  4889. if err != nil {
  4890. logs.Error(err)
  4891. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4892. return
  4893. }
  4894. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate,
  4895. (select empname from user where id = fpdetailhistory.userId)empname from fpdetailhistory where barname = ?
  4896. and createdate between ? and ? order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
  4897. if err != nil {
  4898. logs.Error(err)
  4899. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4900. return
  4901. }
  4902. for _, feedp := range feedpList {
  4903. // LastftList, err := tx.SQL(` select tname ,id
  4904. // from feedtemplethistory where id = ?
  4905. // and createdate < ? order by createdate desc limit 0,1 `, feedp["ftid"], feedp["createdate"]).Query().List()
  4906. // if err != nil {
  4907. // logs.Error(err)
  4908. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4909. // return
  4910. // }
  4911. nextfeedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname,
  4912. DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barname = ?
  4913. and createdate < ? order by createdate desc limit 0,1 `, bar, feedp["createdate"]).Query().List()
  4914. if err != nil {
  4915. logs.Error(err)
  4916. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4917. return
  4918. }
  4919. var ftname interface{}
  4920. ftnamestatus := 0
  4921. ftname = feedp["ftname"]
  4922. var lastftid int64
  4923. if len(nextfeedpList) > 0 {
  4924. for _, ft := range nextfeedpList {
  4925. if ft["ftname"].(string) != feedp["ftname"].(string) {
  4926. ftname = fmt.Sprintf("%v/%v", feedp["ftname"], ft["ftname"])
  4927. lastftid = ft["ftid"].(int64)
  4928. ftnamestatus = 1
  4929. break
  4930. }
  4931. }
  4932. }
  4933. for i, fpd := range fpdList {
  4934. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4935. fpd["weightstatus"] = 0
  4936. fpd["tratiostatus"] = 0
  4937. fpd["ftnamestatus"] = ftnamestatus
  4938. for k, fpd2 := range fpdList {
  4939. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4940. if fpd["weight"].(string) != fpd2["weight"].(string) {
  4941. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4942. fpd["weightstatus"] = 1
  4943. }
  4944. if fpd["tratio"].(string) != fpd2["tratio"].(string) {
  4945. fpd["tratio"] = fmt.Sprintf("%v/%v", fpd2["tratio"], fpd["tratio"])
  4946. fpd["tratiostatus"] = 1
  4947. }
  4948. break
  4949. }
  4950. }
  4951. fpd["barid"] = feedp["barid"]
  4952. fpd["barname"] = feedp["barname"]
  4953. fpd["ccount"] = feedp["ccount"]
  4954. fpd["ratio"] = feedp["ratio"]
  4955. fpd["ccountratio"] = feedp["ccountratio"]
  4956. fpd["ftid"] = feedp["ftid"]
  4957. fpd["ftname"] = ftname
  4958. fpd["ccountstatus"] = 0
  4959. fpd["ccountratiostatus"] = 0
  4960. fpd["ratiostatus"] = 0
  4961. fpd["ftnamestatus"] = 0
  4962. fpd["lastftid"] = lastftid
  4963. for _, next := range nextfeedpList {
  4964. if next["ccount"].(int64) != fpd["ccount"].(int64) {
  4965. fpd["ccount"] = fmt.Sprintf("%v/%v", next["ccount"], fpd["ccount"])
  4966. fpd["ccountstatus"] = 1
  4967. }
  4968. if next["ccountratio"].(string) != fpd["ccountratio"].(string) {
  4969. fpd["ccountratio"] = fmt.Sprintf("%v/%v", next["ccountratio"], fpd["ccountratio"])
  4970. fpd["ccountratiostatus"] = 1
  4971. }
  4972. if next["ratio"].(string) != fpd["ratio"].(string) {
  4973. fpd["ratio"] = fmt.Sprintf("%v/%v", next["ratio"], fpd["ratio"])
  4974. fpd["ratiostatus"] = 1
  4975. }
  4976. // if next["ftname"].(string) != fpd["ftname"].(string) {
  4977. // fpd["ftname"] = fmt.Sprintf("%v/%v", next["ftname"], fpd["ftname"])
  4978. // fpd["ftnamestatus"] = 1
  4979. // }
  4980. }
  4981. }
  4982. }
  4983. }
  4984. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  4985. }
  4986. // func GetLpplandtl1History(c *gin.Context) {
  4987. // appG := app.Gin{C: c}
  4988. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4989. // fsion := gofasion.NewFasion(string(dataByte))
  4990. // // parammaps := fsion.Get("parammaps")
  4991. // barid := fsion.Get("barid").ValueStr()
  4992. // startDate := fsion.Get("startDate").ValueStr()
  4993. // endDate := fsion.Get("endDate").ValueStr()
  4994. // tx := restful.Engine.NewSession()
  4995. // defer tx.Close()
  4996. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  4997. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  4998. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  4999. // // if err != nil {
  5000. // // logs.Error(err)
  5001. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5002. // // return
  5003. // // }
  5004. // // for _, feedp := range feedpList {
  5005. // // fmt.Println(feedp)
  5006. // // for i, fpd := range fpdList {
  5007. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  5008. // // for k, fpd2 := range fpdList {
  5009. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  5010. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  5011. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  5012. // // }
  5013. // // break
  5014. // // }
  5015. // // }
  5016. // // fpd["barid"] = feedp["barid"]
  5017. // // fpd["barname"] = feedp["barname"]
  5018. // // fpd["ccount"] = feedp["ccount"]
  5019. // // fpd["ratio"] = feedp["ratio"]
  5020. // // fpd["ccountratio"] = feedp["ccountratio"]
  5021. // // fpd["ftid"] = feedp["ftid"]
  5022. // // fpd["ftname"] = feedp["ftname"]
  5023. // // }
  5024. // // }
  5025. // // }
  5026. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  5027. // }
  5028. func GetRemind(c *gin.Context) {
  5029. appG := app.Gin{C: c}
  5030. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5031. fsion := gofasion.NewFasion(string(dataByte))
  5032. parammaps := fsion.Get("parammaps")
  5033. pastureid := parammaps.Get("pastureid").ValueStr()
  5034. tx := restful.Engine.NewSession()
  5035. defer tx.Close()
  5036. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  5037. if err != nil {
  5038. logs.Error(err)
  5039. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5040. return
  5041. }
  5042. // pastureid = "3"
  5043. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  5044. if err != nil {
  5045. logs.Error(err)
  5046. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5047. return
  5048. }
  5049. defer resp.Body.Close()
  5050. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5051. buf.ReadFrom(resp.Body)
  5052. fmt.Println(string(buf.Bytes()))
  5053. respMap := make(map[string]interface{}, 0)
  5054. err = json.Unmarshal(buf.Bytes(), &respMap)
  5055. if err != nil {
  5056. logs.Error(err)
  5057. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5058. return
  5059. }
  5060. for _, data := range dataList {
  5061. r := make(map[string]interface{}, 0)
  5062. r["sys_name"] = ""
  5063. r["service_id"] = ""
  5064. r["pasture_id"] = ""
  5065. r["type_name"] = ""
  5066. r["remind_type_id"] = ""
  5067. r["remind_type"] = ""
  5068. r["push_date"] = ""
  5069. r["push_time"] = ""
  5070. r["interval_time"] = ""
  5071. r["push_limit"] = ""
  5072. r["template_id"] = ""
  5073. r["roles_id"] = ""
  5074. r["users_id"] = ""
  5075. r["date_type"] = ""
  5076. r["cycle_type"] = ""
  5077. data["data"] = r
  5078. for _, resp := range respMap["data"].([]interface{}) {
  5079. resp1 := resp.(map[string]interface{})
  5080. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  5081. if resp1["push_time"] == nil {
  5082. resp1["push_time"] = ""
  5083. }
  5084. data["data"] = resp1
  5085. break
  5086. }
  5087. }
  5088. }
  5089. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  5090. }
  5091. type NoticeMsgtype struct {
  5092. SysName string `json:"sys_name"`
  5093. PastureId int64 `json:"pasture_id"`
  5094. ServiceId int64 `json:"service_id"`
  5095. TypeName string `json:"type_name"`
  5096. RemindType int64 `json:"remind_type"`
  5097. PushDate int64 `json:"push_date"`
  5098. PushTime string `json:"push_time"`
  5099. IntervalTime int64 `json:"interval_time"`
  5100. PushLimit int64 `json:"push_limit"`
  5101. TemplateId string `json:"template_id"`
  5102. UsersId string `json:"users_id"`
  5103. DateType int64 `json:"date_type"`
  5104. CycleType int64 `json:"cycle_type"`
  5105. DelayTime int64 `json:"delay_time"`
  5106. Status int64 `json:"status"`
  5107. }
  5108. func UpdateRemind(c *gin.Context) {
  5109. appG := app.Gin{C: c}
  5110. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5111. parammaps := gofasion.NewFasion(string(dataByte))
  5112. // parammaps := fsion.Get("parammaps")
  5113. // user := parammaps.Get("user").ValueStr()
  5114. id := parammaps.Get("id").ValueInt64()
  5115. noticeMsgtype := new(NoticeMsgtype)
  5116. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  5117. noticeMsgtype.ServiceId = id
  5118. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  5119. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  5120. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  5121. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  5122. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  5123. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  5124. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  5125. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  5126. // noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  5127. noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
  5128. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  5129. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  5130. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  5131. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  5132. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  5133. //TODO
  5134. noticeMsgtype.SysName = "tmrWatch"
  5135. userList := parammaps.Get("user").Array()
  5136. var userstr []string
  5137. for _, user := range userList {
  5138. userstr = append(userstr, user.ValueStr())
  5139. }
  5140. tx := restful.Engine.NewSession()
  5141. defer tx.Close()
  5142. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  5143. if err != nil {
  5144. logs.Error(err)
  5145. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5146. return
  5147. }
  5148. // var jsonStr = []byte(noticeMsgtype
  5149. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  5150. fmt.Println(string(noticeMsgtypebyte), "aaaaaaaaaa")
  5151. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  5152. req.Header.Set("Content-Type", "application/json")
  5153. client := &http.Client{}
  5154. resp, err := client.Do(req)
  5155. if err != nil {
  5156. logs.Error(err)
  5157. }
  5158. defer resp.Body.Close()
  5159. body, _ := ioutil.ReadAll(resp.Body)
  5160. fmt.Println("response Body:", string(body))
  5161. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  5162. if err != nil {
  5163. logs.Error(err)
  5164. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5165. return
  5166. }
  5167. defer getresp.Body.Close()
  5168. buf := bytes.NewBuffer(make([]byte, 0, 512))
  5169. buf.ReadFrom(getresp.Body)
  5170. // fmt.Println(string(buf.Bytes()))
  5171. respMap := make(map[string]interface{}, 0)
  5172. err = json.Unmarshal(buf.Bytes(), &respMap)
  5173. if err != nil {
  5174. logs.Error(err)
  5175. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5176. return
  5177. }
  5178. for _, resp := range respMap["data"].([]interface{}) {
  5179. resp1 := resp.(map[string]interface{})
  5180. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  5181. if err != nil {
  5182. logs.Error(err)
  5183. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5184. return
  5185. }
  5186. }
  5187. appG.Response(http.StatusOK, e.SUCCESS, true)
  5188. }
  5189. func GetSpillageallHistory(c *gin.Context) {
  5190. appG := app.Gin{C: c}
  5191. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5192. parammaps := gofasion.NewFasion(string(dataByte))
  5193. barname := parammaps.Get("barname").ValueStr()
  5194. pastureid := parammaps.Get("pastureid").ValueStr()
  5195. startdate := parammaps.Get("startDate").ValueStr()
  5196. enddate := parammaps.Get("endDate").ValueStr()
  5197. tx := restful.Engine.NewSession()
  5198. defer tx.Close()
  5199. historyList, err := tx.SQL(` select lpp.id,lpp.times,lppland.lweight,lppland.tmrid,lppland.tmrname,lpp.sort,DATE_FORMAT(lppland.createdate,'%Y-%m-%d %H:%i:%s') as createdate from lpplandtl1history lppland
  5200. join lpplan lpp on lpp.id = lppland.lppid where lppland.barname = ? and lppland.pastureid = ? and lppland.createdate between ? and ?
  5201. order by lppland.createdate desc ,lpp.times,lpp.sort asc `, barname, pastureid, startdate, enddate).Query().List()
  5202. if err != nil {
  5203. logs.Error(err)
  5204. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5205. return
  5206. }
  5207. respMap := make([]map[string]interface{}, 0)
  5208. data := make(map[interface{}]interface{})
  5209. for _, history := range historyList {
  5210. data[history["createdate"]] = history["createdate"]
  5211. }
  5212. createList := []string{}
  5213. for _, v := range data {
  5214. createList = append(createList, v.(string))
  5215. }
  5216. // sort.Sort()
  5217. // sort.Sort(sort.Reverse(sort.StringSlice(createList)))
  5218. sort.Slice(createList, func(i, j int) bool {
  5219. return createList[i] > createList[j]
  5220. })
  5221. for _, v := range createList {
  5222. a := make(map[string]interface{})
  5223. a["createdate"] = data[v]
  5224. // createList = append(createList, v.(string))
  5225. respMap = append(respMap, a)
  5226. }
  5227. number := 0
  5228. dataMap := make([]interface{}, 0)
  5229. for k, resp := range respMap {
  5230. createdate := resp["createdate"].(string)
  5231. var nextcreatedate string
  5232. if len(respMap) > k+1 {
  5233. nextcreatedate = respMap[k+1]["createdate"].(string)
  5234. }
  5235. // dataList := make(map[string][]interface{})
  5236. // list := make(map[string]interface{})
  5237. times := make(map[interface{}]int)
  5238. for _, history := range historyList {
  5239. // List := make(map[interface{}][]interface{})
  5240. i := 0
  5241. if history["createdate"].(string) == createdate {
  5242. times[history["times"]]++
  5243. data := make(map[string]interface{})
  5244. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v", history["lweight"])
  5245. // exist := false
  5246. if nextcreatedate != "" {
  5247. for _, history1 := range historyList {
  5248. if history1["createdate"].(string) == nextcreatedate && history1["id"].(int64) == history["id"].(int64) &&
  5249. history1["times"].(int64) == history["times"].(int64) {
  5250. data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v/%v", data[fmt.Sprintf("a%d", times[history["times"]])], history["lweight"])
  5251. break
  5252. // exist = true
  5253. }
  5254. }
  5255. }
  5256. // data[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5257. i++
  5258. // list[fmt.Sprintf("a%d", m)] = append(list[fmt.Sprintf("a%d", m)], data)
  5259. // dataList[strconv.FormatInt(history["times"].(int64), 10)][fmt.Sprintf("a%d", m)] = nil
  5260. // dataList[strconv.FormatInt(history["times"].(int64), 10)] = append(dataList[strconv.FormatInt(history["times"].(int64), 10)], data)
  5261. // resp["times"] = history["times"]
  5262. // resp[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5263. data1 := make(map[string]interface{})
  5264. data1["times"] = history["times"]
  5265. data1[fmt.Sprintf("a%d", times[history["times"]])] = fmt.Sprintf("%v(%v)", data[fmt.Sprintf("a%d", times[history["times"]])], history["tmrname"])
  5266. data1["createdate"] = resp["createdate"]
  5267. // fmt.Println(dataList)
  5268. dataMap = append(dataMap, data1)
  5269. }
  5270. if i > number {
  5271. number = i
  5272. }
  5273. // respMap = append(respMap, dataList)
  5274. }
  5275. // for k, data := range dataList {
  5276. // resp[k] = data
  5277. // }
  5278. // resp["data"] = dataList
  5279. }
  5280. // resp := make(map[string]interface{})
  5281. // sort.Strings(createList)
  5282. //
  5283. // for _, create := range createList {
  5284. // for _, r := range respMap {
  5285. // if create == r["createdate"].(string) {
  5286. // resp[create] = r
  5287. // break
  5288. // }
  5289. // }
  5290. // }
  5291. sz := []string{"一", "二", "三", "四", "五", "六", "七", "八", "九"}
  5292. var trainsList []interface{}
  5293. for i := 0; i < number; i++ {
  5294. trains := make(map[string]interface{})
  5295. trains["label"] = fmt.Sprintf("第%s车", sz[i])
  5296. trains["prop"] = fmt.Sprintf("a%d", i+1)
  5297. trainsList = append(trainsList, trains)
  5298. }
  5299. respdata := make(map[string]interface{})
  5300. respdata["data"] = dataMap
  5301. respdata["trains"] = trainsList
  5302. appG.Response(http.StatusOK, e.SUCCESS, respdata)
  5303. }
  5304. func GetRecipeTemplateRecordHistory(c *gin.Context) {
  5305. appG := app.Gin{C: c}
  5306. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5307. parammaps := gofasion.NewFasion(string(dataByte))
  5308. ftid := parammaps.Get("ftid").ValueInt64()
  5309. lastftid := parammaps.Get("lastftid").ValueInt64()
  5310. pastureid := parammaps.Get("pastureid").ValueInt64()
  5311. // createdate := parammaps.Get("createdate").ValueStr()
  5312. tx := restful.Engine.NewSession()
  5313. defer tx.Close()
  5314. data := make(map[string]interface{})
  5315. feedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5316. and fthis.pastureId = ?`, ftid, pastureid).Query().List()
  5317. if err != nil {
  5318. logs.Error(err)
  5319. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5320. return
  5321. }
  5322. feedtemplet := make(map[string]interface{})
  5323. for _, f := range feedtempletList {
  5324. feedtemplet = f
  5325. }
  5326. fitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, ftid, pastureid).Query().List()
  5327. if err != nil {
  5328. logs.Error(err)
  5329. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5330. return
  5331. }
  5332. feedtemplet["fit"] = fitList
  5333. data["current"] = feedtemplet
  5334. lastfeedtempletList, err := tx.SQL(`select * from feedtemplet fthis where fthis.id = ?
  5335. and fthis.pastureId = ?`, lastftid, pastureid).Query().List()
  5336. if err != nil {
  5337. logs.Error(err)
  5338. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5339. return
  5340. }
  5341. lastfeedtemplet := make(map[string]interface{})
  5342. for _, f := range lastfeedtempletList {
  5343. lastfeedtemplet = f
  5344. }
  5345. lastfitList, err := tx.SQL(` select * from ftdetail fit where fit.ftid = ? and fit.pastureid = ?`, lastftid, pastureid).Query().List()
  5346. if err != nil {
  5347. logs.Error(err)
  5348. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5349. return
  5350. }
  5351. lastfeedtemplet["fit"] = lastfitList
  5352. data["last"] = lastfeedtemplet
  5353. appG.Response(http.StatusOK, e.SUCCESS, data)
  5354. }
  5355. func GetFeedtempletHistory(c *gin.Context) {
  5356. appG := app.Gin{C: c}
  5357. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5358. parammaps := gofasion.NewFasion(string(dataByte))
  5359. ftid := parammaps.Get("ftid").ValueStr()
  5360. pastureid := parammaps.Get("pastureid").ValueInt64()
  5361. start := parammaps.Get("startdate").ValueStr()
  5362. end := parammaps.Get("enddate").ValueStr()
  5363. tx := restful.Engine.NewSession()
  5364. defer tx.Close()
  5365. 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 ?
  5366. and id = ? and pastureid = ? order by createdate desc `,
  5367. start, end, ftid, pastureid).Query().List()
  5368. if err != nil {
  5369. logs.Error(err)
  5370. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5371. return
  5372. }
  5373. ftdetailList, err := tx.SQL(` select * from ftdetail where ftid = ? and pastureid = ? order by sort `,
  5374. ftid, pastureid).Query().List()
  5375. if err != nil {
  5376. logs.Error(err)
  5377. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5378. return
  5379. }
  5380. // join feed f on f.fname = fit.name and f.pastureId = fit.pastureId
  5381. for i, ft := range ftList {
  5382. fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
  5383. ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail ft where ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
  5384. (select empname from user where id = fit.userId) empname,
  5385. 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
  5386. where fit.fitid = ?
  5387. and fit.dateTime1 = ( select dateTime1 from fit_history where fitid = ?
  5388. and dateTime1 <= ? group by dateTime1 order by dateTime1 desc limit 0,1 )`, ftid, ftid, ft["createdate"]).Query().List()
  5389. if err != nil {
  5390. logs.Error(err)
  5391. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5392. return
  5393. }
  5394. ft["createdate"] = ft["createdate1"]
  5395. // data["tname"] = ft["tname"]
  5396. // data["tcode"] = ft["tcode"]
  5397. // data["tcolor"] = ft["tcolor"]
  5398. // data["fttype"] = ft["fttype"]
  5399. // data["ccname"] = ft["ccname"]
  5400. // data["source"] = ft["source"]
  5401. // data["version"] = ft["version"]
  5402. // data["remark"] = ft["remark"]
  5403. for n, ft2 := range ftList {
  5404. if i < n {
  5405. if ft["tname"].(string) != ft2["tname"].(string) {
  5406. ft["tname"] = fmt.Sprintf("%v/%v", ft["tname"], ft2["tname"])
  5407. }
  5408. if _, ok := ft["tcode"]; ok {
  5409. if _, ok := ft2["tcode"]; ok {
  5410. if ft["tcode"].(string) != ft2["tcode"].(string) {
  5411. ft["tcode"] = fmt.Sprintf("%v/%v", ft["tcode"], ft2["tcode"])
  5412. }
  5413. }
  5414. }
  5415. if _, ok := ft["tcolor"]; ok {
  5416. if _, ok := ft2["tcolor"]; ok {
  5417. if ft["tcolor"].(string) != ft2["tcolor"].(string) {
  5418. ft["tcolor"] = fmt.Sprintf("%v/%v", ft["tcolor"], ft2["tcolor"])
  5419. }
  5420. }
  5421. }
  5422. if _, ok := ft["fttype"]; ok {
  5423. if _, ok := ft2["fttype"]; ok {
  5424. if ft["fttype"].(string) != ft2["fttype"].(string) {
  5425. ft["fttype"] = fmt.Sprintf("%v/%v", ft["fttype"], ft2["fttype"])
  5426. }
  5427. }
  5428. }
  5429. if _, ok := ft["ccname"]; ok {
  5430. if _, ok := ft2["ccname"]; ok {
  5431. if ft["ccname"].(string) != ft2["ccname"].(string) {
  5432. ft["ccname"] = fmt.Sprintf("%v/%v", ft["ccname"], ft2["ccname"])
  5433. }
  5434. }
  5435. }
  5436. if _, ok := ft["source"]; ok {
  5437. if _, ok := ft2["source"]; ok {
  5438. if ft["source"].(string) != ft2["source"].(string) {
  5439. ft["source"] = fmt.Sprintf("%v/%v", ft["source"], ft2["source"])
  5440. }
  5441. }
  5442. }
  5443. if _, ok := ft["version"]; ok {
  5444. if _, ok := ft2["version"]; ok {
  5445. if ft["version"].(int64) != ft2["version"].(int64) {
  5446. ft["version"] = fmt.Sprintf("%v/%v", ft["version"], ft2["version"])
  5447. }
  5448. }
  5449. }
  5450. if _, ok := ft["remark"]; ok {
  5451. if _, ok := ft2["remark"]; ok {
  5452. if ft["remark"].(string) != ft2["remark"].(string) {
  5453. ft["remark"] = fmt.Sprintf("%v/%v", ft["remark"], ft2["remark"])
  5454. }
  5455. }
  5456. }
  5457. break
  5458. }
  5459. }
  5460. dataList := make([]map[string]interface{}, 0)
  5461. if len(fithisList) > 0 {
  5462. for _, fit := range fithisList {
  5463. data := make(map[string]interface{})
  5464. data["feedgroup"] = fit["feedgroup"]
  5465. data["fname"] = fit["fname"]
  5466. data["empname"] = fit["empname"]
  5467. if fit["Eweight"] != nil {
  5468. if fit["Eweight"].(string) != fit["weight"].(string) {
  5469. data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
  5470. } else {
  5471. data["fweight"] = fit["Eweight"]
  5472. }
  5473. data["fweightstatus"] = 1
  5474. } else {
  5475. data["fweight"] = fit["weight"]
  5476. data["fweightstatus"] = 0
  5477. }
  5478. data["autosecond"] = fit["autosecond"]
  5479. // data["tname"] = ft["tname"]
  5480. // data["tcode"] = ft["tcode"]
  5481. // data["tcolor"] = ft["tcolor"]
  5482. // data["fttype"] = ft["fttype"]
  5483. // data["ccname"] = ft["ccname"]
  5484. // data["source"] = ft["source"]
  5485. // data["version"] = ft["version"]
  5486. // data["remark"] = ft["remark"]
  5487. // data["createdate"] = ft["createdate1"]
  5488. // ft["fit"] = data
  5489. dataList = append(dataList, data)
  5490. }
  5491. } else {
  5492. for _, fit := range ftdetailList {
  5493. data := make(map[string]interface{})
  5494. data["feedgroup"] = fit["feedgroup"]
  5495. data["fname"] = fit["fname"]
  5496. // if fit["Eweight"] != nil {
  5497. // data["weight"] = fit["Eweight"]
  5498. // } else {
  5499. data["fweight"] = fit["fweight"]
  5500. // }
  5501. data["autosecond"] = fit["autosecond"]
  5502. // ft["fit"] = data
  5503. dataList = append(dataList, data)
  5504. }
  5505. }
  5506. ft["fit"] = dataList
  5507. }
  5508. appG.Response(http.StatusOK, e.SUCCESS, ftList)
  5509. }
  5510. func UpdateMaterialTMR(c *gin.Context) {
  5511. appG := app.Gin{C: c}
  5512. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5513. parammaps := gofasion.NewFasion(string(dataByte))
  5514. tmrid := parammaps.Get("tmrid").ValueStr()
  5515. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5516. lppid := parammaps.Get("lppid").ValueStr()
  5517. times := parammaps.Get("times").ValueStr()
  5518. pastureid := parammaps.Get("pastureid").ValueStr()
  5519. // oldtmrid := parammaps.Get("oldtmrid").ValueStr()
  5520. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5521. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5522. tx := restful.Engine.NewSession()
  5523. defer tx.Close()
  5524. tx.Begin()
  5525. if tmrid != "1000" {
  5526. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5527. if err != nil {
  5528. logs.Error(err)
  5529. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5530. return
  5531. }
  5532. var maxstirfeed float64
  5533. for _, tmr := range tmrList {
  5534. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5535. }
  5536. if status == 0 {
  5537. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5538. if err != nil {
  5539. tx.Rollback()
  5540. logs.Error(err)
  5541. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5542. return
  5543. }
  5544. var lweight float64
  5545. for _, item := range lpplandtl1List {
  5546. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5547. lweight += fl
  5548. }
  5549. if lweight > maxstirfeed {
  5550. lweight = lweight - maxstirfeed
  5551. } else {
  5552. lweight = 0
  5553. }
  5554. if lweight > 0 {
  5555. lweight1 := lweight / float64(len(lpplandtl1List))
  5556. number := 0
  5557. for _, item := range lpplandtl1List {
  5558. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5559. if lweight1 >= fl {
  5560. number++
  5561. }
  5562. }
  5563. lweight := lweight / float64((len(lpplandtl1List) - number))
  5564. for _, item := range lpplandtl1List {
  5565. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5566. if lweight1 >= fl {
  5567. continue
  5568. }
  5569. if tmrtype == "1" {
  5570. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?),lweight = lweight- ? where id = ? ", tmrid, tmrid, lweight, item["id"]).Execute()
  5571. if err != nil {
  5572. tx.Rollback()
  5573. logs.Error(err)
  5574. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5575. return
  5576. }
  5577. } else if tmrtype == "2" {
  5578. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1',lweight = lweight- ? where id = ? ", lweight, item["id"]).Execute()
  5579. if err != nil {
  5580. tx.Rollback()
  5581. logs.Error(err)
  5582. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5583. return
  5584. }
  5585. }
  5586. if item["fttype"].(int64) == 0 {
  5587. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5588. if err != nil {
  5589. tx.Rollback()
  5590. logs.Error(err)
  5591. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5592. return
  5593. }
  5594. } else {
  5595. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5596. if err != nil {
  5597. tx.Rollback()
  5598. logs.Error(err)
  5599. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5600. return
  5601. }
  5602. }
  5603. }
  5604. } else {
  5605. for _, item := range lpplandtl1List {
  5606. // 自走式
  5607. if tmrtype == "1" {
  5608. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5609. if err != nil {
  5610. logs.Error(err)
  5611. tx.Rollback()
  5612. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5613. return
  5614. }
  5615. } else if tmrtype == "2" {
  5616. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5617. if err != nil {
  5618. logs.Error(err)
  5619. tx.Rollback()
  5620. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5621. return
  5622. }
  5623. }
  5624. }
  5625. }
  5626. } else if status == 1 {
  5627. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? order by sort desc ", lppid, pastureid).Query().List()
  5628. if err != nil {
  5629. logs.Error(err)
  5630. tx.Rollback()
  5631. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5632. return
  5633. }
  5634. var lweight float64
  5635. for _, item := range lpplandtl1List {
  5636. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5637. lweight += fl
  5638. }
  5639. if lweight > maxstirfeed {
  5640. lweight = lweight - maxstirfeed
  5641. } else {
  5642. lweight = 0
  5643. }
  5644. for _, item := range lpplandtl1List {
  5645. if lweight > 0 {
  5646. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5647. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5648. if fl >= lweight {
  5649. item["lweight"] = fl - lweight
  5650. lweight = 0
  5651. if tmrtype == "1" {
  5652. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) ,lweight = ? where id = ? ", tmrid, tmrid, item["lweight"], item["id"]).Execute()
  5653. if err != nil {
  5654. logs.Error(err)
  5655. tx.Rollback()
  5656. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5657. return
  5658. }
  5659. } else if tmrtype == "2" {
  5660. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? ", item["lweight"], item["id"]).Execute()
  5661. if err != nil {
  5662. logs.Error(err)
  5663. tx.Rollback()
  5664. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5665. return
  5666. }
  5667. }
  5668. if item["fttype"].(int64) == 0 {
  5669. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5670. if err != nil {
  5671. logs.Error(err)
  5672. tx.Rollback()
  5673. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5674. return
  5675. }
  5676. } else {
  5677. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", lweight, times, item["barid"]).Execute()
  5678. if err != nil {
  5679. logs.Error(err)
  5680. tx.Rollback()
  5681. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5682. return
  5683. }
  5684. }
  5685. } else {
  5686. lweight = lweight - fl
  5687. _, err = tx.SQL(" delete from lpplandtl1 where id = ? ", item["id"]).Execute()
  5688. if err != nil {
  5689. logs.Error(err)
  5690. tx.Rollback()
  5691. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5692. return
  5693. }
  5694. if item["fttype"].(int64) == 0 {
  5695. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5696. if err != nil {
  5697. logs.Error(err)
  5698. tx.Rollback()
  5699. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5700. return
  5701. }
  5702. } else {
  5703. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5704. if err != nil {
  5705. logs.Error(err)
  5706. tx.Rollback()
  5707. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5708. return
  5709. }
  5710. }
  5711. }
  5712. } else {
  5713. // 自走式
  5714. if tmrtype == "1" {
  5715. _, err = tx.SQL(" update lpplandtl1 set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? ", tmrid, tmrid, item["id"]).Execute()
  5716. if err != nil {
  5717. logs.Error(err)
  5718. tx.Rollback()
  5719. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5720. return
  5721. }
  5722. } else if tmrtype == "2" {
  5723. _, err = tx.SQL(" update lpplandtl1 set tmrid = 201 , tmrname = '任意车1' where id = ? ", item["id"]).Execute()
  5724. if err != nil {
  5725. logs.Error(err)
  5726. tx.Rollback()
  5727. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5728. return
  5729. }
  5730. }
  5731. }
  5732. }
  5733. } else {
  5734. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1 where lppid = ? and pastureid = ? ", lppid, pastureid).Query().List()
  5735. if err != nil {
  5736. logs.Error(err)
  5737. tx.Rollback()
  5738. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5739. return
  5740. }
  5741. for _, item := range lpplandtl1List {
  5742. if item["fttype"].(int64) == 0 {
  5743. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5744. if err != nil {
  5745. logs.Error(err)
  5746. tx.Rollback()
  5747. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5748. return
  5749. }
  5750. } else {
  5751. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5752. if err != nil {
  5753. logs.Error(err)
  5754. tx.Rollback()
  5755. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5756. return
  5757. }
  5758. }
  5759. _, err = tx.SQL(" delete from lpplandtl1 where `id` = ? ", item["id"]).Execute()
  5760. if err != nil {
  5761. logs.Error(err)
  5762. tx.Rollback()
  5763. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5764. return
  5765. }
  5766. }
  5767. }
  5768. _, err = tx.SQL(" update lpplan set tmrid = ? , tmrname = ( select tname from tmr where id = ?) , maxweight = ? where id = ? ", tmrid, tmrid, maxstirfeed, lppid).Execute()
  5769. if err != nil {
  5770. logs.Error(err)
  5771. tx.Rollback()
  5772. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5773. return
  5774. }
  5775. } else {
  5776. if status == 2 {
  5777. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1 where lppid = ? `, lppid).Query().List()
  5778. if err != nil {
  5779. logs.Error(err)
  5780. tx.Rollback()
  5781. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5782. return
  5783. }
  5784. for _, item := range lpplandtl1List {
  5785. if item["fttype"].(int64) == 0 {
  5786. _, err = tx.SQL(" update fpdetail set ptsuse = ptsuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5787. if err != nil {
  5788. logs.Error(err)
  5789. tx.Rollback()
  5790. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5791. return
  5792. }
  5793. } else {
  5794. _, err = tx.SQL(" update fpdetail set ptuse = ptuse - ? where times = ? and barid = ? ", item["lweight"], times, item["barid"]).Execute()
  5795. if err != nil {
  5796. logs.Error(err)
  5797. tx.Rollback()
  5798. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5799. return
  5800. }
  5801. }
  5802. }
  5803. _, err = tx.SQL(" delete from lpplandtl1 where `lppid` = ? ", lppid).Execute()
  5804. if err != nil {
  5805. logs.Error(err)
  5806. tx.Rollback()
  5807. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5808. return
  5809. }
  5810. } else {
  5811. _, err := tx.SQL(" update lpplan set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid).Execute()
  5812. if err != nil {
  5813. logs.Error(err)
  5814. tx.Rollback()
  5815. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5816. return
  5817. }
  5818. }
  5819. }
  5820. err := tx.Commit()
  5821. if err != nil {
  5822. logs.Error(err)
  5823. tx.Rollback()
  5824. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5825. return
  5826. }
  5827. appG.Response(http.StatusOK, e.SUCCESS, true)
  5828. }
  5829. func UpdateMaterialTMRDate(c *gin.Context) {
  5830. appG := app.Gin{C: c}
  5831. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  5832. parammaps := gofasion.NewFasion(string(dataByte))
  5833. tmrid := parammaps.Get("tmrid").ValueStr()
  5834. tmrtype := parammaps.Get("tmrtype").ValueStr()
  5835. lppid := parammaps.Get("lppid").ValueStr()
  5836. times := parammaps.Get("times").ValueStr()
  5837. pastureid := parammaps.Get("pastureid").ValueStr()
  5838. date := parammaps.Get("date").ValueStr()
  5839. // oldtmrtype := parammaps.Get("oldtmrtype").ValueStr()
  5840. status := parammaps.Get("status").ValueInt64() // 0 多出的饲料平均从已分配的各栏舍中扣减 1 多出的饲料从最后一个栏舍依次往前扣减 2 清空已分配的撒料车
  5841. tx := restful.Engine.NewSession()
  5842. defer tx.Close()
  5843. tx.Begin()
  5844. if tmrid != "1000" {
  5845. tmrList, err := tx.SQL(" select maxstirfeed from tmr where id = ? ", tmrid).Query().List()
  5846. if err != nil {
  5847. logs.Error(err)
  5848. tx.Rollback()
  5849. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5850. return
  5851. }
  5852. var maxstirfeed float64
  5853. for _, tmr := range tmrList {
  5854. maxstirfeed += float64(tmr["maxstirfeed"].(int64))
  5855. }
  5856. if status == 0 {
  5857. 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()
  5858. if err != nil {
  5859. logs.Error(err)
  5860. tx.Rollback()
  5861. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5862. return
  5863. }
  5864. var lweight float64
  5865. for _, item := range lpplandtl1List {
  5866. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5867. lweight += fl
  5868. }
  5869. if lweight > maxstirfeed {
  5870. lweight = lweight - maxstirfeed
  5871. } else {
  5872. lweight = 0
  5873. }
  5874. if lweight > 0 {
  5875. lweight1 := lweight / float64(len(lpplandtl1List))
  5876. number := 0
  5877. for _, item := range lpplandtl1List {
  5878. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5879. if lweight1 >= fl {
  5880. number++
  5881. }
  5882. }
  5883. lweight := lweight / float64((len(lpplandtl1List) - number))
  5884. for _, item := range lpplandtl1List {
  5885. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5886. if lweight1 >= fl {
  5887. continue
  5888. }
  5889. if tmrtype == "1" {
  5890. _, 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()
  5891. if err != nil {
  5892. logs.Error(err)
  5893. tx.Rollback()
  5894. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5895. return
  5896. }
  5897. } else if tmrtype == "2" {
  5898. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201, tmrname = '任意车1',lweight = lweight- ? where id = ? and date = ? ", lweight, item["id"], date).Execute()
  5899. if err != nil {
  5900. logs.Error(err)
  5901. tx.Rollback()
  5902. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5903. return
  5904. }
  5905. }
  5906. if item["fttype"].(int64) == 0 {
  5907. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5908. if err != nil {
  5909. logs.Error(err)
  5910. tx.Rollback()
  5911. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5912. return
  5913. }
  5914. } else {
  5915. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5916. if err != nil {
  5917. logs.Error(err)
  5918. tx.Rollback()
  5919. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5920. return
  5921. }
  5922. }
  5923. }
  5924. } else {
  5925. for _, item := range lpplandtl1List {
  5926. // 自走式
  5927. if tmrtype == "1" {
  5928. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  5929. if err != nil {
  5930. logs.Error(err)
  5931. tx.Rollback()
  5932. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5933. return
  5934. }
  5935. } else if tmrtype == "2" {
  5936. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  5937. if err != nil {
  5938. logs.Error(err)
  5939. tx.Rollback()
  5940. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5941. return
  5942. }
  5943. }
  5944. }
  5945. }
  5946. } else if status == 1 {
  5947. 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()
  5948. if err != nil {
  5949. logs.Error(err)
  5950. tx.Rollback()
  5951. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5952. return
  5953. }
  5954. var lweight float64
  5955. for _, item := range lpplandtl1List {
  5956. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5957. lweight += fl
  5958. }
  5959. if lweight > maxstirfeed {
  5960. lweight = lweight - maxstirfeed
  5961. } else {
  5962. lweight = 0
  5963. }
  5964. for _, item := range lpplandtl1List {
  5965. if lweight > 0 {
  5966. // `ttype` tinyint(4) DEFAULT NULL COMMENT '设备类型0铲车,1tmr,3撒料设备
  5967. fl, _ := strconv.ParseFloat(item["lweight"].(string), 64)
  5968. if fl >= lweight {
  5969. item["lweight"] = fl - lweight
  5970. lweight = 0
  5971. if tmrtype == "1" {
  5972. _, 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()
  5973. if err != nil {
  5974. logs.Error(err)
  5975. tx.Rollback()
  5976. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5977. return
  5978. }
  5979. } else if tmrtype == "2" {
  5980. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' ,lweight = ? where id = ? and date = ? ", item["lweight"], item["id"], date).Execute()
  5981. if err != nil {
  5982. logs.Error(err)
  5983. tx.Rollback()
  5984. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5985. return
  5986. }
  5987. }
  5988. if item["fttype"].(int64) == 0 {
  5989. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5990. if err != nil {
  5991. logs.Error(err)
  5992. tx.Rollback()
  5993. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  5994. return
  5995. }
  5996. } else {
  5997. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", lweight, times, item["barid"], date).Execute()
  5998. if err != nil {
  5999. logs.Error(err)
  6000. tx.Rollback()
  6001. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6002. return
  6003. }
  6004. }
  6005. } else {
  6006. lweight = lweight - fl
  6007. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6008. if err != nil {
  6009. logs.Error(err)
  6010. tx.Rollback()
  6011. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6012. return
  6013. }
  6014. if item["fttype"].(int64) == 0 {
  6015. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6016. if err != nil {
  6017. logs.Error(err)
  6018. tx.Rollback()
  6019. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6020. return
  6021. }
  6022. } else {
  6023. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6024. if err != nil {
  6025. logs.Error(err)
  6026. tx.Rollback()
  6027. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6028. return
  6029. }
  6030. }
  6031. }
  6032. } else {
  6033. // 自走式
  6034. if tmrtype == "1" {
  6035. _, err = tx.SQL(" update lpplandtl1date set tmrid = ? , tmrname = ( select tname from tmr where id = ?) where id = ? and date = ? ", tmrid, tmrid, item["id"], date).Execute()
  6036. if err != nil {
  6037. logs.Error(err)
  6038. tx.Rollback()
  6039. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6040. return
  6041. }
  6042. } else if tmrtype == "2" {
  6043. _, err = tx.SQL(" update lpplandtl1date set tmrid = 201 , tmrname = '任意车1' where id = ? and date = ? ", item["id"], date).Execute()
  6044. if err != nil {
  6045. logs.Error(err)
  6046. tx.Rollback()
  6047. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6048. return
  6049. }
  6050. }
  6051. }
  6052. }
  6053. } else {
  6054. lpplandtl1List, err := tx.SQL(" select id,lweight,fttype,barid from lpplandtl1date where lppid = ? and pastureid = ? and date = ? ", lppid, pastureid, date).Query().List()
  6055. if err != nil {
  6056. logs.Error(err)
  6057. tx.Rollback()
  6058. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6059. return
  6060. }
  6061. for _, item := range lpplandtl1List {
  6062. if item["fttype"].(int64) == 0 {
  6063. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6064. if err != nil {
  6065. logs.Error(err)
  6066. tx.Rollback()
  6067. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6068. return
  6069. }
  6070. } else {
  6071. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6072. if err != nil {
  6073. logs.Error(err)
  6074. tx.Rollback()
  6075. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6076. return
  6077. }
  6078. }
  6079. _, err = tx.SQL(" delete from lpplandtl1date where id = ? and date = ? ", item["id"], date).Execute()
  6080. if err != nil {
  6081. logs.Error(err)
  6082. tx.Rollback()
  6083. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6084. return
  6085. }
  6086. }
  6087. }
  6088. _, 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()
  6089. if err != nil {
  6090. logs.Error(err)
  6091. tx.Rollback()
  6092. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6093. return
  6094. }
  6095. } else {
  6096. if status == 2 {
  6097. lpplandtl1List, err := tx.SQL(`select * from lpplandtl1date where lppid = ? and date = ? `, lppid, date).Query().List()
  6098. if err != nil {
  6099. logs.Error(err)
  6100. tx.Rollback()
  6101. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6102. return
  6103. }
  6104. for _, item := range lpplandtl1List {
  6105. if item["fttype"].(int64) == 0 {
  6106. _, err = tx.SQL(" update fpdetaildate set ptsuse = ptsuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6107. if err != nil {
  6108. logs.Error(err)
  6109. tx.Rollback()
  6110. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6111. return
  6112. }
  6113. } else {
  6114. _, err = tx.SQL(" update fpdetaildate set ptuse = ptuse - ? where times = ? and barid = ? and date = ? ", item["lweight"], times, item["barid"], date).Execute()
  6115. if err != nil {
  6116. logs.Error(err)
  6117. tx.Rollback()
  6118. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6119. return
  6120. }
  6121. }
  6122. }
  6123. _, err = tx.SQL(" delete from lpplandtl1date where `lppid` = ? and date = ? ", lppid, date).Execute()
  6124. if err != nil {
  6125. logs.Error(err)
  6126. tx.Rollback()
  6127. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6128. return
  6129. }
  6130. } else {
  6131. _, err := tx.SQL(" update lpplandate set tmrid = ? , tmrname = ?, maxweight = ? where id = ? ", tmrid, "搅拌任意车", 100000, lppid, date).Execute()
  6132. if err != nil {
  6133. logs.Error(err)
  6134. tx.Rollback()
  6135. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6136. return
  6137. }
  6138. }
  6139. }
  6140. err := tx.Commit()
  6141. if err != nil {
  6142. logs.Error(err)
  6143. tx.Rollback()
  6144. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6145. return
  6146. }
  6147. appG.Response(http.StatusOK, e.SUCCESS, true)
  6148. }
  6149. func Decimal(value float64) float64 {
  6150. value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
  6151. return value
  6152. }
  6153. func UpdateDailyData(c *gin.Context) {
  6154. appG := app.Gin{C: c}
  6155. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6156. parammaps := gofasion.NewFasion(string(dataByte))
  6157. pid := parammaps.Get("pid").ValueDefaultStr("0")
  6158. weight := parammaps.Get("weight").ValueDefaultFloat64(0)
  6159. sort := parammaps.Get("sort").ValueDefaultStr("0")
  6160. location := parammaps.Get("location").ValueInt64() // 0 饲料 1 撒料车辆
  6161. date := parammaps.Get("date").ValueStr()
  6162. tx := restful.Engine.NewSession()
  6163. defer tx.Close()
  6164. tx.Begin()
  6165. if location == 0 {
  6166. fid := parammaps.Get("fid").ValueStr()
  6167. downloadplandtl1, err := tx.SQL(`select lweight from downloadplandtl1 where pid = ? and sort = ? and fid = ? `, pid, sort, fid).Query().List()
  6168. if err != nil {
  6169. logs.Error("UpdateDailyData-error-1:", err)
  6170. tx.Rollback()
  6171. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6172. return
  6173. }
  6174. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6175. if err != nil {
  6176. logs.Error("UpdateDailyData-error-1:", err)
  6177. tx.Rollback()
  6178. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6179. return
  6180. }
  6181. num, err := strconv.ParseFloat(downloadplandtl1[0]["lweight"].(string), 64)
  6182. if err != nil {
  6183. fmt.Println("Error:", err)
  6184. return
  6185. }
  6186. actualWeight := weight - num
  6187. _, err = tx.SQL(`update downloadplandtl1 set lweight = ? where pid = ? and sort = ? and fid = ? `, weight, pid, sort, fid).Execute()
  6188. if err != nil {
  6189. logs.Error("UpdateDailyData-error-2:", err)
  6190. tx.Rollback()
  6191. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6192. return
  6193. }
  6194. _, err = tx.SQL(`update downloadplandtl1_exec set lweight = lweight + ? where pid = ? and sort = ? `, actualWeight, pid, sort).Execute()
  6195. if err != nil {
  6196. logs.Error("UpdateDailyData-error-3:", err)
  6197. tx.Rollback()
  6198. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6199. return
  6200. }
  6201. _, err = tx.SQL(`update downloadplandtl2 set lweight =lweight+ lweight / ?*? where pid = ? `, downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6202. if err != nil {
  6203. logs.Error("UpdateDailyData-error-4:", err)
  6204. tx.Rollback()
  6205. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6206. return
  6207. }
  6208. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6209. if err != nil {
  6210. logs.Error("UpdateDailyData-error-5:", err)
  6211. tx.Rollback()
  6212. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6213. return
  6214. }
  6215. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6216. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6217. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6218. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6219. if err != nil {
  6220. fmt.Println("Error:", err)
  6221. return
  6222. }
  6223. // actual := actualWeight / float64(len(downloadedplanList))
  6224. for _, item := range downloadedplanList {
  6225. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6226. if err != nil {
  6227. fmt.Println("Error:", err)
  6228. return
  6229. }
  6230. actual := itemLweight / lweight * actualWeight
  6231. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6232. if err != nil {
  6233. logs.Error("UpdateDailyData-error-6:", err)
  6234. tx.Rollback()
  6235. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6236. return
  6237. }
  6238. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6239. if err != nil {
  6240. logs.Error("UpdateDailyData-error-7:", err)
  6241. tx.Rollback()
  6242. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6243. return
  6244. }
  6245. _, 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()
  6246. if err != nil {
  6247. logs.Error("UpdateDailyData-error-8:", err)
  6248. tx.Rollback()
  6249. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6250. return
  6251. }
  6252. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, lweight, actual, item["id"]).Execute()
  6253. if err != nil {
  6254. logs.Error("UpdateDailyData-error-9:", err)
  6255. tx.Rollback()
  6256. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6257. return
  6258. }
  6259. }
  6260. } else {
  6261. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6262. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6263. // lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6264. // if err != nil {
  6265. // fmt.Println("Error:", err)
  6266. // return
  6267. // }
  6268. for _, item := range downloadedplanList {
  6269. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6270. if err != nil {
  6271. logs.Error("UpdateDailyData-error-6:", err)
  6272. tx.Rollback()
  6273. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6274. return
  6275. }
  6276. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6277. item["lweight"], actualWeight, item["id"]).Execute()
  6278. if err != nil {
  6279. logs.Error("UpdateDailyData-error-7:", err)
  6280. tx.Rollback()
  6281. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6282. return
  6283. }
  6284. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6285. where pid = ?`, item["id"]).Execute()
  6286. if err != nil {
  6287. logs.Error("UpdateDailyData-error-8:", err)
  6288. tx.Rollback()
  6289. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6290. return
  6291. }
  6292. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6293. if err != nil {
  6294. logs.Error("UpdateDailyData-error-9:", err)
  6295. tx.Rollback()
  6296. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6297. return
  6298. }
  6299. }
  6300. }
  6301. } else {
  6302. fbarid := parammaps.Get("fbarid").ValueStr()
  6303. downloadplandtl2, err := tx.SQL(`select lweight from downloadplandtl2 where pid = ? and sort = ? and fbarid = ? `, pid, sort, fbarid).Query().List()
  6304. if err != nil {
  6305. logs.Error("UpdateDailyData-error-10:", err)
  6306. tx.Rollback()
  6307. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6308. return
  6309. }
  6310. downloadedplan, err := tx.SQL(`select lweight,lpplantype from downloadedplan where id = ? `, pid).Query().List()
  6311. if err != nil {
  6312. logs.Error("UpdateDailyData-error-1:", err)
  6313. tx.Rollback()
  6314. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6315. return
  6316. }
  6317. num, err := strconv.ParseFloat(downloadplandtl2[0]["lweight"].(string), 64)
  6318. if err != nil {
  6319. fmt.Println("Error:", err)
  6320. return
  6321. }
  6322. actualWeight := weight - num
  6323. _, err = tx.SQL(`update downloadplandtl2 set lweight = ? where pid = ? and sort = ? and fbarid = ? `, weight, pid, sort, fbarid).Execute()
  6324. if err != nil {
  6325. logs.Error("UpdateDailyData-error-11:", err)
  6326. tx.Rollback()
  6327. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6328. return
  6329. }
  6330. _, err = tx.SQL(`update downloadplandtl1 set lweight = lweight + lweight /? * ? where pid = ? `,
  6331. downloadedplan[0]["lweight"], actualWeight, pid).Execute()
  6332. if err != nil {
  6333. logs.Error("UpdateDailyData-error-12:", err)
  6334. tx.Rollback()
  6335. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6336. return
  6337. }
  6338. _, err = tx.SQL(`update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6339. where pid = ? `, pid).Execute()
  6340. if err != nil {
  6341. logs.Error("UpdateDailyData-error-13:", err)
  6342. tx.Rollback()
  6343. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6344. return
  6345. }
  6346. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, pid).Execute()
  6347. if err != nil {
  6348. logs.Error("UpdateDailyData-error-14:", err)
  6349. tx.Rollback()
  6350. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改栏舍计划失败:%s", err.Error()))
  6351. return
  6352. }
  6353. if downloadedplan[0]["lpplantype"].(int64) == 0 || downloadedplan[0]["lpplantype"].(int64) == 1 {
  6354. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6355. and id != ? and lpplantype != 5 and mydate = ? `, pid, pid, date).Query().List()
  6356. lweight, err := strconv.ParseFloat(downloadedplan[0]["lweight"].(string), 64)
  6357. if err != nil {
  6358. fmt.Println("Error:", err)
  6359. return
  6360. }
  6361. for _, item := range downloadedplanList {
  6362. itemLweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6363. if err != nil {
  6364. fmt.Println("Error:", err)
  6365. return
  6366. }
  6367. actual := itemLweight / lweight * actualWeight
  6368. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actual, item["id"]).Execute()
  6369. if err != nil {
  6370. logs.Error("UpdateDailyData-error-6:", err)
  6371. tx.Rollback()
  6372. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6373. return
  6374. }
  6375. _, err = tx.SQL(` update downloadplandtl1 d1 set lweight =lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6376. if err != nil {
  6377. logs.Error("UpdateDailyData-error-7:", err)
  6378. tx.Rollback()
  6379. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6380. return
  6381. }
  6382. _, 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()
  6383. if err != nil {
  6384. logs.Error("UpdateDailyData-error-8:", err)
  6385. tx.Rollback()
  6386. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6387. return
  6388. }
  6389. _, err = tx.SQL(` update downloadplandtl2 set lweight = lweight+ lweight /? *? where pid = ?`, itemLweight, actual, item["id"]).Execute()
  6390. if err != nil {
  6391. logs.Error("UpdateDailyData-error-9:", err)
  6392. tx.Rollback()
  6393. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6394. return
  6395. }
  6396. }
  6397. } else {
  6398. downloadedplanList, _ := tx.SQL(`select id,lweight from downloadedplan where pid = (select pid from downloadedplan where id = ? )
  6399. and id != ? and lpplantype in(0,1) and mydate = ? `, pid, pid, date).Query().List()
  6400. for _, item := range downloadedplanList {
  6401. // lweight, err := strconv.ParseFloat(item["lweight"].(string), 64)
  6402. // if err != nil {
  6403. // fmt.Println("Error:", err)
  6404. // return
  6405. // }
  6406. _, err = tx.SQL(` update downloadedplan set lweight = lweight + ? where id = ?`, actualWeight, item["id"]).Execute()
  6407. if err != nil {
  6408. logs.Error("UpdateDailyData-error-6:", err)
  6409. tx.Rollback()
  6410. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6411. return
  6412. }
  6413. _, err = tx.SQL(` update downloadplandtl1 set lweight =lweight+ lweight /? *? where pid = ?`,
  6414. item["lweight"], actualWeight, item["id"]).Execute()
  6415. if err != nil {
  6416. logs.Error("UpdateDailyData-error-7:", err)
  6417. tx.Rollback()
  6418. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6419. return
  6420. }
  6421. _, err = tx.SQL(` update downloadplandtl1_exec d1e set lweight = (select sum(lweight) from downloadplandtl1 where pid = d1e.pid and sort = d1e.sort )
  6422. where pid = ?`, item["id"]).Execute()
  6423. if err != nil {
  6424. logs.Error("UpdateDailyData-error-8:", err)
  6425. tx.Rollback()
  6426. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6427. return
  6428. }
  6429. _, err = tx.SQL(` update downloadplandtl2 set lweight =lweight+ lweight /? *? where pid = ?`, item["lweight"], actualWeight, item["id"]).Execute()
  6430. if err != nil {
  6431. logs.Error("UpdateDailyData-error-9:", err)
  6432. tx.Rollback()
  6433. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("修改饲料计划失败:%s", err.Error()))
  6434. return
  6435. }
  6436. }
  6437. }
  6438. }
  6439. err := tx.Commit()
  6440. if err != nil {
  6441. logs.Error("UpdateDailyData-error-20:", err)
  6442. tx.Rollback()
  6443. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  6444. return
  6445. }
  6446. appG.Response(http.StatusOK, e.SUCCESS, true)
  6447. }
  6448. func GetFormulaStatistics(c *gin.Context) {
  6449. appG := app.Gin{C: c}
  6450. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6451. parammaps := gofasion.NewFasion(string(dataByte))
  6452. startTime := parammaps.Get("startTime").ValueStr()
  6453. endTime := parammaps.Get("endTime").ValueStr()
  6454. pastureId := parammaps.Get("pastureId").ValueStr()
  6455. tx := restful.Engine.NewSession()
  6456. feedtempletList, err := tx.SQL(`select id,tname from feedtemplet where pastureId = ? and enable = 1`, pastureId).Query().List()
  6457. if err != nil {
  6458. logs.Error("GetFormulaStatistics-error-1:", err)
  6459. tx.Rollback()
  6460. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6461. return
  6462. }
  6463. var feedtemplet, dateList []string
  6464. for _, f := range feedtempletList {
  6465. feedtemplet = append(feedtemplet, f["tname"].(string))
  6466. }
  6467. layout := "2006-01-02"
  6468. // s := "2023-05-01"
  6469. // e := "2023-05-23"
  6470. start, err := time.Parse(layout, startTime)
  6471. if err != nil {
  6472. fmt.Println(err)
  6473. return
  6474. }
  6475. end, err := time.Parse(layout, endTime)
  6476. if err != nil {
  6477. fmt.Println(err)
  6478. return
  6479. }
  6480. end = end.AddDate(0, 0, 1)
  6481. for d := start; d.Before(end); d = d.AddDate(0, 0, 1) {
  6482. dateList = append(dateList, d.Format("2006-01-02"))
  6483. }
  6484. downloadedplanList, err := tx.SQL(`select count(1) total,ft.tname,date_format(d.mydate ,'%Y-%m-%d') mydate from downloadedplan d
  6485. join feedtemplet ft on ft.id = d.tempid where d.mydate between ? and ? and d.lpplantype in(0,1) and d.iscompleted = 1 and d.pastureId= ?
  6486. group by d.tempid,d.mydate `, startTime, endTime, pastureId).Query().List()
  6487. if err != nil {
  6488. logs.Error("GetFormulaStatistics-error-2:", err)
  6489. tx.Rollback()
  6490. appG.Response(http.StatusInternalServerError, e.ERROR, fmt.Sprintf("查看配方统计图标报错:%s", err.Error()))
  6491. return
  6492. }
  6493. var data2 [][]interface{}
  6494. for _, f := range feedtemplet {
  6495. var data1 []interface{}
  6496. for _, date := range dateList {
  6497. exist := false
  6498. for _, item := range downloadedplanList {
  6499. if date == item["mydate"].(string) && f == item["tname"].(string) {
  6500. data1 = append(data1, item["total"])
  6501. exist = true
  6502. break
  6503. }
  6504. }
  6505. if !exist {
  6506. data1 = append(data1, 0)
  6507. }
  6508. }
  6509. data2 = append(data2, data1)
  6510. }
  6511. //前端让加的
  6512. feedtemplet = append(feedtemplet, "")
  6513. {
  6514. var data1 []interface{}
  6515. for _, f := range dateList {
  6516. // f = f + "\n"
  6517. fmt.Println(f)
  6518. data1 = append(data1, 0)
  6519. }
  6520. data2 = append(data2, data1)
  6521. }
  6522. resp := make(map[string]interface{}, 0)
  6523. resp["xdata"] = dateList
  6524. resp["data1"] = feedtemplet
  6525. resp["data2"] = data2
  6526. appG.Response(http.StatusOK, e.SUCCESS, resp)
  6527. }
  6528. func GetPlanData(c *gin.Context) {
  6529. appG := app.Gin{C: c}
  6530. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6531. fsion := gofasion.NewFasion(string(dataByte))
  6532. sqlnamestr := fsion.Get("name").ValueStr()
  6533. sqlnamestr1 := fsion.Get("name1").ValueStr()
  6534. offset := fsion.Get("offset").ValueDefaultInt(0)
  6535. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  6536. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  6537. month := fsion.Get("month").ValueDefaultStr("map")
  6538. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  6539. tx := restful.Engine.NewSession()
  6540. err := tx.Begin()
  6541. defer func() {
  6542. switch {
  6543. case err != nil:
  6544. if tx != nil {
  6545. tx.Rollback()
  6546. }
  6547. default:
  6548. if tx != nil {
  6549. err = tx.Commit()
  6550. }
  6551. }
  6552. if tx != nil {
  6553. tx.Close()
  6554. }
  6555. }()
  6556. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  6557. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  6558. if sql != "" {
  6559. s_params := make([]interface{}, 0)
  6560. if fsion.HasKey("parammaps") {
  6561. parammaps := fsion.Get("parammaps")
  6562. paramslist := strings.Split(p, ",")
  6563. if len(paramslist) > 0 && p != "" {
  6564. for _, value := range paramslist {
  6565. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  6566. if tempv, exists := c.Get("jwt_username"); exists {
  6567. s_params = append(s_params, tempv.(string))
  6568. } else {
  6569. s_params = append(s_params, "")
  6570. }
  6571. } else {
  6572. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6573. }
  6574. }
  6575. }
  6576. }
  6577. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6578. if err != nil {
  6579. appG.Response(http.StatusOK, e.ERROR, err.Error())
  6580. } else {
  6581. paramslist1 := strings.Split(p1, ",")
  6582. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6583. s_params1 := make([]interface{}, 0)
  6584. if len(paramslist1) > 0 && p1 != "" {
  6585. for _, v := range paramslist1 {
  6586. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  6587. }
  6588. }
  6589. arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
  6590. for _, item := range arr {
  6591. trgaddressList := []string{}
  6592. if _, ok := item["trgaddress"]; ok {
  6593. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  6594. for _, str := range trgaddressList1 {
  6595. if str != "" {
  6596. trgaddressList = append(trgaddressList, str)
  6597. }
  6598. }
  6599. }
  6600. item["trgaddressList"] = trgaddressList
  6601. }
  6602. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  6603. }
  6604. // var wg sync.WaitGroup
  6605. // for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6606. // wg.Add(1)
  6607. // go func(value map[string]interface{}) {
  6608. // defer wg.Done()
  6609. // _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  6610. // }(value)
  6611. // }
  6612. // wg.Wait()
  6613. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6614. }
  6615. } else {
  6616. appG.Response(http.StatusOK, e.SUCCESS, nil)
  6617. }
  6618. }
  6619. func PostPlanData(c *gin.Context) {
  6620. appG := app.Gin{C: c}
  6621. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6622. fsion := gofasion.NewFasion(string(dataByte))
  6623. logging.Info("PostRJSBData err: ", string(dataByte))
  6624. s_params := make([]interface{}, 0)
  6625. tx := restful.Engine.NewSession()
  6626. err := tx.Begin()
  6627. defer func() {
  6628. switch {
  6629. case err != nil:
  6630. if tx != nil {
  6631. tx.Rollback()
  6632. }
  6633. default:
  6634. if tx != nil {
  6635. err = tx.Commit()
  6636. }
  6637. }
  6638. if tx != nil {
  6639. tx.Close()
  6640. }
  6641. }()
  6642. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  6643. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  6644. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  6645. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  6646. if !fsion.HasKey("parammaps") {
  6647. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  6648. return
  6649. }
  6650. parammaps := fsion.Get("parammaps")
  6651. paramslist := strings.Split(p, ",")
  6652. if len(paramslist) > 0 && p != "" {
  6653. for _, value := range paramslist {
  6654. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6655. }
  6656. }
  6657. _, err = tx.SQL(sql, s_params...).Execute()
  6658. if err != nil {
  6659. logging.Error("PostRJSBData err: ", err)
  6660. msg := geterrmsg(err.Error())
  6661. appG.Response(http.StatusOK, e.ERROR, msg)
  6662. return
  6663. }
  6664. s_params = make([]interface{}, 0)
  6665. paramslist = strings.Split(p1, ",")
  6666. if len(paramslist) > 0 && p1 != "" {
  6667. for _, value := range paramslist {
  6668. // if value == "ID" {
  6669. // id := parammaps.Get("ID").ValueStr()
  6670. // pastureid := parammaps.Get("pastureid").ValueStr()
  6671. // 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
  6672. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  6673. // if err != nil {
  6674. // logging.Error("PostRJSBData err: ", err)
  6675. // msg := geterrmsg(err.Error())
  6676. // appG.Response(http.StatusOK, e.ERROR, msg)
  6677. // return
  6678. // }
  6679. // for _, item := range datalist {
  6680. // id = item["id"]
  6681. // }
  6682. // s_params = append(s_params, id)
  6683. // } else {
  6684. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6685. // }
  6686. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6687. }
  6688. }
  6689. _, err = tx.SQL(sql1, s_params...).Execute()
  6690. if err != nil {
  6691. logging.Error("PostRJSBData1 err: ", err)
  6692. msg := geterrmsg(err.Error())
  6693. appG.Response(http.StatusOK, e.ERROR, msg)
  6694. return
  6695. }
  6696. s_params = make([]interface{}, 0)
  6697. paramslist = strings.Split(p2, ",")
  6698. if len(paramslist) > 0 && p2 != "" {
  6699. for _, value := range paramslist {
  6700. if value == "ID" {
  6701. id := parammaps.Get("ID").ValueStr()
  6702. pastureid := parammaps.Get("pastureid").ValueStr()
  6703. 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
  6704. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  6705. if err != nil {
  6706. logging.Error("PostRJSBData err: ", err)
  6707. msg := geterrmsg(err.Error())
  6708. appG.Response(http.StatusOK, e.ERROR, msg)
  6709. return
  6710. }
  6711. for _, item := range datalist {
  6712. id = item["id"]
  6713. }
  6714. s_params = append(s_params, id)
  6715. } else {
  6716. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6717. }
  6718. }
  6719. }
  6720. _, err = tx.SQL(sql2, s_params...).Execute()
  6721. if err != nil {
  6722. logging.Error("PostRJSBData2 err: ", err)
  6723. msg := geterrmsg(err.Error())
  6724. appG.Response(http.StatusOK, e.ERROR, msg)
  6725. return
  6726. }
  6727. s_params = make([]interface{}, 0)
  6728. paramslist = strings.Split(p3, ",")
  6729. if len(paramslist) > 0 && p3 != "" {
  6730. for _, value := range paramslist {
  6731. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6732. }
  6733. }
  6734. _, err = tx.SQL(sql3, s_params...).Execute()
  6735. if err != nil {
  6736. logging.Error("PostRJSBData3 err: ", err)
  6737. msg := geterrmsg(err.Error())
  6738. appG.Response(http.StatusOK, e.ERROR, msg)
  6739. return
  6740. }
  6741. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  6742. }
  6743. func CheckFeedTrgaddress(c *gin.Context) {
  6744. appG := app.Gin{C: c}
  6745. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6746. fsion := gofasion.NewFasion(string(dataByte))
  6747. fclassid := fsion.Get("fclassid").ValueStr()
  6748. feedId := fsion.Get("feedId").ValueStr()
  6749. backup1 := fsion.Get("backup1").ValueStr()
  6750. backup1List := strings.Split(backup1, ",")
  6751. tx := restful.Engine.NewSession()
  6752. defer tx.Close()
  6753. // if backup1 != "" {
  6754. feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
  6755. for _, feed := range feedList {
  6756. if feed["backup1"] == "" {
  6757. continue
  6758. }
  6759. feedbackupList := strings.Split(feed["backup1"], ",")
  6760. for _, feedbackup := range feedbackupList {
  6761. for _, backup := range backup1List {
  6762. if feedbackup == backup {
  6763. appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
  6764. return
  6765. }
  6766. }
  6767. }
  6768. }
  6769. // }
  6770. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  6771. }
  6772. func ThiGetDataByName(c *gin.Context) {
  6773. appG := app.Gin{C: c}
  6774. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6775. fsion := gofasion.NewFasion(string(dataByte))
  6776. sqlnamestr := fsion.Get("name").ValueStr()
  6777. offset := fsion.Get("offset").ValueDefaultInt(0)
  6778. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  6779. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  6780. tx := restful.Engine.NewSession()
  6781. err := tx.Begin()
  6782. defer func() {
  6783. switch {
  6784. case err != nil:
  6785. logging.Error("tx.Begin 事务启动失败__error:", err)
  6786. if tx != nil {
  6787. tx.Rollback()
  6788. }
  6789. default:
  6790. if tx != nil {
  6791. err = tx.Commit()
  6792. }
  6793. }
  6794. if tx != nil {
  6795. tx.Close()
  6796. }
  6797. }()
  6798. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  6799. if sql != "" {
  6800. s_params := make([]interface{}, 0)
  6801. if fsion.HasKey("parammaps") {
  6802. parammaps := fsion.Get("parammaps")
  6803. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  6804. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  6805. }
  6806. paramslist := strings.Split(p, ",")
  6807. if len(paramslist) > 0 && p != "" {
  6808. for _, value := range paramslist {
  6809. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  6810. if tempv, exists := c.Get("jwt_username"); exists {
  6811. s_params = append(s_params, tempv.(string))
  6812. } else {
  6813. s_params = append(s_params, "")
  6814. }
  6815. } else {
  6816. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  6817. }
  6818. }
  6819. }
  6820. } else if fsion.HasKey("params") {
  6821. params := fsion.Get("params").Array()
  6822. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  6823. for _, v_params := range params {
  6824. s_params = append(s_params, v_params.ValueStr())
  6825. }
  6826. }
  6827. if returntype == "xlsx" {
  6828. var xlsxfile *xlsx.File
  6829. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  6830. //c.File("c:/dd.xlsx")
  6831. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  6832. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  6833. c.Header("Content-Transfer-Encoding", "binary")
  6834. _ = xlsxfile.Write(c.Writer)
  6835. } else {
  6836. if sqlnamestr == "getHomepageStr" {
  6837. parammaps := fsion.Get("parammaps")
  6838. pastureid := parammaps.Get("pastureid").ValueStr()
  6839. var montimeList []float64
  6840. var montime float64
  6841. var wg sync.WaitGroup
  6842. now := time.Now()
  6843. for i := 0; i < 30; i++ {
  6844. wg.Add(1)
  6845. nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
  6846. go func(nowstr string) {
  6847. defer wg.Done()
  6848. sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
  6849. slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
  6850. m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
  6851. montimeList = append(montimeList, m)
  6852. }(nowstr)
  6853. }
  6854. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6855. if err != nil {
  6856. logging.Error("GetDataByName err: ", err)
  6857. msg := geterrmsg(err.Error())
  6858. appG.Response(http.StatusOK, e.ERROR, msg)
  6859. }
  6860. wg.Wait()
  6861. for _, m := range montimeList {
  6862. montime += m
  6863. }
  6864. queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
  6865. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6866. return
  6867. }
  6868. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  6869. if err != nil {
  6870. logging.Error("GetDataByName err: ", err)
  6871. msg := geterrmsg(err.Error())
  6872. appG.Response(http.StatusOK, e.ERROR, msg)
  6873. } else {
  6874. if sqlnamestr == "getFeedTrgaddressList" {
  6875. for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  6876. trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
  6877. trgaddressList := []string{}
  6878. for _, str := range trgaddressList1 {
  6879. if str != "" {
  6880. trgaddressList = append(trgaddressList, str)
  6881. }
  6882. }
  6883. item["trgaddressList"] = trgaddressList
  6884. }
  6885. }
  6886. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  6887. }
  6888. }
  6889. } else {
  6890. appG.Response(http.StatusOK, e.SUCCESS, nil)
  6891. }
  6892. }
  6893. // func ToggleCcount(c *gin.Context) {
  6894. // appG := app.Gin{C: c}
  6895. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  6896. // fsion := gofasion.NewFasion(string(dataByte))
  6897. // // 0 实际 1 软件
  6898. // status := fsion.Get("status").ValueDefaultInt64(0)
  6899. // pastureId := fsion.Get("pastureId").ValueStr()
  6900. // tx := restful.Engine.NewSession()
  6901. // err := tx.Begin()
  6902. // defer func() {
  6903. // switch {
  6904. // case err != nil:
  6905. // logging.Error("tx.Begin 事务启动失败__error:", err)
  6906. // if tx != nil {
  6907. // tx.Rollback()
  6908. // }
  6909. // default:
  6910. // if tx != nil {
  6911. // err = tx.Commit()
  6912. // }
  6913. // }
  6914. // if tx != nil {
  6915. // tx.Close()
  6916. // }
  6917. // }()
  6918. // barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
  6919. // if err != nil {
  6920. // logs.Error(err)
  6921. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6922. // return
  6923. // }
  6924. // for _, bar := range barList {
  6925. // exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, bar["bname"], pastureId).Exist()
  6926. // if err != nil {
  6927. // logs.Error(err)
  6928. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6929. // return
  6930. // }
  6931. // if !exist {
  6932. // _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  6933. // pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
  6934. // if err != nil {
  6935. // logs.Error(err)
  6936. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6937. // return
  6938. // }
  6939. // }
  6940. // }
  6941. // if status == 0 {
  6942. // tx.Exec(`update feedp set ccount = actualcount `)
  6943. // }else{
  6944. // tx.Exec(`update feedp set ccount = softccount `)
  6945. // }
  6946. // feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
  6947. // if err != nil {
  6948. // logs.Error(err)
  6949. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6950. // return
  6951. // }
  6952. // for _, feedpData :=range feedpList{
  6953. // var feedpargs []interface{}
  6954. // upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  6955. // feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
  6956. // if _, ok := feedpData["ftname"]; ok {
  6957. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
  6958. // upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  6959. // upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  6960. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  6961. // feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  6962. // } else {
  6963. // upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  6964. // }
  6965. // if _, ok := feedpData["ptsfname"]; ok {
  6966. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
  6967. // upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  6968. // upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  6969. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  6970. // feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
  6971. // } else {
  6972. // upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  6973. // }
  6974. // upFeedpSql += " where barname = ? and pastureid = ? "
  6975. // feedpargs = append(feedpargs, feedpData["barname"], pastureid)
  6976. // _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  6977. // if err != nil {
  6978. // logs.Error(err)
  6979. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6980. // return
  6981. // }
  6982. // exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
  6983. // if err != nil {
  6984. // logs.Error(err)
  6985. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6986. // return
  6987. // }
  6988. // if !exist1 {
  6989. // _, 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) `,
  6990. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  6991. // if err != nil {
  6992. // logs.Error(err)
  6993. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  6994. // return
  6995. // }
  6996. // }
  6997. // exist2, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
  6998. // if err != nil {
  6999. // logs.Error(err)
  7000. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7001. // return
  7002. // }
  7003. // if !exist2 {
  7004. // _, 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) `,
  7005. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7006. // if err != nil {
  7007. // logs.Error(err)
  7008. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7009. // return
  7010. // }
  7011. // }
  7012. // exist3, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
  7013. // if err != nil {
  7014. // logs.Error(err)
  7015. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7016. // return
  7017. // }
  7018. // if !exist3 {
  7019. // _, 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) `,
  7020. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7021. // if err != nil {
  7022. // logs.Error(err)
  7023. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7024. // return
  7025. // }
  7026. // }
  7027. // exist4, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
  7028. // if err != nil {
  7029. // logs.Error(err)
  7030. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7031. // return
  7032. // }
  7033. // if !exist4 {
  7034. // _, 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) `,
  7035. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7036. // if err != nil {
  7037. // logs.Error(err)
  7038. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7039. // return
  7040. // }
  7041. // }
  7042. // exist5, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
  7043. // if err != nil {
  7044. // logs.Error(err)
  7045. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7046. // return
  7047. // }
  7048. // if !exist5 {
  7049. // _, 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) `,
  7050. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7051. // if err != nil {
  7052. // logs.Error(err)
  7053. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7054. // return
  7055. // }
  7056. // }
  7057. // exist6, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
  7058. // if err != nil {
  7059. // logs.Error(err)
  7060. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7061. // return
  7062. // }
  7063. // if !exist6 {
  7064. // _, 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) `,
  7065. // pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
  7066. // if err != nil {
  7067. // logs.Error(err)
  7068. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7069. // return
  7070. // }
  7071. // }
  7072. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  7073. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  7074. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  7075. // and pastureid = ? and times = ?`
  7076. // var fpdargs1 []interface{}
  7077. // fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  7078. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7079. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  7080. // _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  7081. // if err != nil {
  7082. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7083. // return
  7084. // }
  7085. // var fpdargs2 []interface{}
  7086. // fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  7087. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7088. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  7089. // _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  7090. // if err != nil {
  7091. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7092. // return
  7093. // }
  7094. // var fpdargs3 []interface{}
  7095. // fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  7096. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7097. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  7098. // _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  7099. // if err != nil {
  7100. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7101. // return
  7102. // }
  7103. // var fpdargs4 []interface{}
  7104. // fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  7105. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7106. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  7107. // _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  7108. // if err != nil {
  7109. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7110. // return
  7111. // }
  7112. // var fpdargs5 []interface{}
  7113. // fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
  7114. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7115. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
  7116. // _, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
  7117. // if err != nil {
  7118. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7119. // return
  7120. // }
  7121. // var fpdargs6 []interface{}
  7122. // fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
  7123. // dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  7124. // dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
  7125. // _, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
  7126. // if err != nil {
  7127. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7128. // return
  7129. // }
  7130. // // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  7131. // 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()
  7132. // if err != nil {
  7133. // appG.Response(http.StatusInternalServerError, e.ERROR, false)
  7134. // return
  7135. // }
  7136. // // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  7137. // // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  7138. // upFpdetailList := make([]*upFpdetail, 0)
  7139. // for _, newfpd := range newList {
  7140. // for _, oldfpd := range oldFpdList {
  7141. // if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  7142. // var oldweight, newweight float64
  7143. // if oldfpd["weight"] != nil {
  7144. // oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  7145. // }
  7146. // if newfpd["weight"] != nil {
  7147. // newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  7148. // }
  7149. // fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  7150. // upFpdetailList = append(upFpdetailList, &upFpdetail{
  7151. // Old: oldweight,
  7152. // New: newweight,
  7153. // Times: newfpd["times"].(int64),
  7154. // Ptid: newfpd["ptid"].(int64),
  7155. // Fweight: fweight,
  7156. // Id: oldfpd["id"].(int64),
  7157. // })
  7158. // break
  7159. // }
  7160. // }
  7161. // }
  7162. // updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
  7163. // }
  7164. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  7165. // }
  7166. func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
  7167. feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp where id = ? `, data["id"]).Query().List()
  7168. if err != nil {
  7169. return err
  7170. }
  7171. for _, item := range feedpList {
  7172. // if item["ftid"].(string) != data["ftid"].(string) {
  7173. _, err = tx.SQL(` delete from lpplandtl1 where barid = ? and ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
  7174. if err != nil {
  7175. return err
  7176. }
  7177. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  7178. WHERE pastureid=? and find_in_set(barid,?) and ? != ? `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
  7179. if err != nil {
  7180. return err
  7181. }
  7182. // }
  7183. }
  7184. return nil
  7185. }