db.go 149 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594
  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. "strconv"
  14. "strings"
  15. "sync"
  16. "time"
  17. "../../pkg/app"
  18. "../../pkg/e"
  19. "../../pkg/logging"
  20. "../../pkg/setting"
  21. "../../routers/restful"
  22. "github.com/360EntSecGroup-Skylar/excelize"
  23. "github.com/Anderson-Lu/gofasion/gofasion"
  24. "github.com/astaxie/beego/logs"
  25. "github.com/gin-gonic/gin"
  26. "github.com/tealeg/xlsx"
  27. "github.com/xormplus/xorm"
  28. )
  29. // @Summary 根据SQL执行得到数据集
  30. // @Tags getData
  31. // @Accept json
  32. // @Produce json
  33. // @Param sql query string true "sql"
  34. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  35. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  36. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  37. // @Router /data/getdata [POST]
  38. func GetData(c *gin.Context) {
  39. appG := app.Gin{C: c}
  40. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  41. fsion := gofasion.NewFasion(string(dataByte))
  42. sqlstr := fsion.Get("sql").ValueStr()
  43. offset := fsion.Get("offset").ValueDefaultInt(0)
  44. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  45. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  46. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  47. if err != nil {
  48. appG.Response(http.StatusOK, e.ERROR, err.Error())
  49. } else {
  50. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  51. }
  52. }
  53. func Testpartitions(c *gin.Context) {
  54. appG := app.Gin{C: c}
  55. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  56. fsion := gofasion.NewFasion(string(dataByte))
  57. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  58. user := fsion.Get("user").ValueStr() //获取新数据库用户
  59. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  60. host := fsion.Get("host").ValueStr() //获取新数据库名称
  61. port := fsion.Get("port").ValueStr() //获取新数据库名称
  62. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  63. if sqls == nil || err1 != nil {
  64. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  65. }
  66. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  67. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  68. mydb, err := sql.Open("mysql", connecting) //连接新连接
  69. if err != nil {
  70. println("err1", err.Error())
  71. }
  72. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  73. if err != nil {
  74. println("err2", err.Error())
  75. }
  76. mydb.Close()
  77. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  78. mydb, err = sql.Open("mysql", connecting)
  79. if err != nil {
  80. println("err3", err.Error())
  81. }
  82. defer mydb.Close()
  83. if err == nil {
  84. mydb.SetMaxOpenConns(10)
  85. mydb.SetMaxIdleConns(10)
  86. }
  87. errmsg := ""
  88. if err == nil {
  89. //tx ,_ :=mydb.Begin()
  90. for _, sqlstr := range sqlstrs {
  91. //println("sqlstr---",sqlstr)
  92. if sqlstr == "" {
  93. continue
  94. }
  95. _, err = mydb.Exec(sqlstr)
  96. if err != nil {
  97. println("err4", err.Error())
  98. errmsg = err.Error()
  99. //err1 :=tx.Rollback()
  100. }
  101. }
  102. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  103. //err =tx.Commit()
  104. }
  105. if errmsg == "" {
  106. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  107. } else {
  108. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  109. }
  110. }
  111. func TestData(c *gin.Context) {
  112. appG := app.Gin{C: c}
  113. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  114. fsion := gofasion.NewFasion(string(dataByte))
  115. sqlstr := fsion.Get("sql").ValueStr()
  116. token := ""
  117. if tempv, exists := c.Get("jwt_username"); exists {
  118. token = tempv.(string)
  119. }
  120. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  121. }
  122. // @Summary 根据APISQL表中SQL执行得到数据集
  123. // @Tags GetDataByName
  124. // @Accept json
  125. // @Produce json
  126. // @Param sqlname body string true "sqlname"
  127. // @Param offset body int true "offset"
  128. // @Param pagecount body int true "pagecount"
  129. // @Param returntype body string true "returntype"
  130. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  131. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  132. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  133. // @Router /data/GetDataByName [POST]
  134. func GetDataByName(c *gin.Context) {
  135. appG := app.Gin{C: c}
  136. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  137. fsion := gofasion.NewFasion(string(dataByte))
  138. sqlnamestr := fsion.Get("name").ValueStr()
  139. offset := fsion.Get("offset").ValueDefaultInt(0)
  140. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  141. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  142. tx := restful.Engine.NewSession()
  143. err := tx.Begin()
  144. defer func() {
  145. switch {
  146. case err != nil:
  147. logging.Error("tx.Begin 事务启动失败__error:", err)
  148. if tx != nil {
  149. tx.Rollback()
  150. }
  151. default:
  152. if tx != nil {
  153. err = tx.Commit()
  154. }
  155. }
  156. if tx != nil {
  157. tx.Close()
  158. }
  159. }()
  160. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  161. if sql != "" {
  162. s_params := make([]interface{}, 0)
  163. if fsion.HasKey("parammaps") {
  164. parammaps := fsion.Get("parammaps")
  165. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  166. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  167. }
  168. paramslist := strings.Split(p, ",")
  169. if len(paramslist) > 0 && p != "" {
  170. for _, value := range paramslist {
  171. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  172. if tempv, exists := c.Get("jwt_username"); exists {
  173. s_params = append(s_params, tempv.(string))
  174. } else {
  175. s_params = append(s_params, "")
  176. }
  177. } else {
  178. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  179. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  180. // tmrNameList := []string{}
  181. // for _, tmr := range tmrArray {
  182. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  183. // }
  184. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  185. // } else {
  186. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  187. // }
  188. }
  189. }
  190. }
  191. } else if fsion.HasKey("params") {
  192. params := fsion.Get("params").Array()
  193. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  194. for _, v_params := range params {
  195. s_params = append(s_params, v_params.ValueStr())
  196. }
  197. }
  198. if returntype == "xlsx" {
  199. var xlsxfile *xlsx.File
  200. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  201. //c.File("c:/dd.xlsx")
  202. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  203. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  204. c.Header("Content-Transfer-Encoding", "binary")
  205. _ = xlsxfile.Write(c.Writer)
  206. } else {
  207. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  208. if err != nil {
  209. logging.Error("GetDataByName err: ", err)
  210. msg := geterrmsg(err.Error())
  211. appG.Response(http.StatusOK, e.ERROR, msg)
  212. } else {
  213. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  214. }
  215. }
  216. } else {
  217. appG.Response(http.StatusOK, e.SUCCESS, nil)
  218. }
  219. }
  220. // @Summary 根据APISQL表中SQL执行得到数据集
  221. // @Tags GetDataByName
  222. // @Accept json
  223. // @Produce json
  224. // @Param sqlname body string true "sqlname"
  225. // @Param offset body int true "offset"
  226. // @Param pagecount body int true "pagecount"
  227. // @Param returntype body string true "returntype"
  228. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  229. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  230. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  231. // @Router /data/GetDataByName [POST]
  232. func GetDataBySqlIN(c *gin.Context) {
  233. appG := app.Gin{C: c}
  234. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  235. fsion := gofasion.NewFasion(string(dataByte))
  236. sqlnamestr := fsion.Get("name").ValueStr()
  237. offset := fsion.Get("offset").ValueDefaultInt(0)
  238. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  239. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  240. tx := restful.Engine.NewSession()
  241. err := tx.Begin()
  242. defer func() {
  243. switch {
  244. case err != nil:
  245. logging.Error("tx.Begin 事务启动失败__error:", err)
  246. if tx != nil {
  247. tx.Rollback()
  248. }
  249. default:
  250. if tx != nil {
  251. err = tx.Commit()
  252. }
  253. }
  254. if tx != nil {
  255. tx.Close()
  256. }
  257. }()
  258. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  259. if sql != "" {
  260. s_params := make([]interface{}, 0)
  261. if fsion.HasKey("parammaps") {
  262. parammaps := fsion.Get("parammaps")
  263. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  264. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  265. }
  266. paramslist := strings.Split(p, ",")
  267. if len(paramslist) > 0 && p != "" {
  268. for _, value := range paramslist {
  269. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  270. if tempv, exists := c.Get("jwt_username"); exists {
  271. s_params = append(s_params, tempv.(string))
  272. } else {
  273. s_params = append(s_params, "")
  274. }
  275. } else {
  276. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  277. }
  278. }
  279. }
  280. } else if fsion.HasKey("params") {
  281. params := fsion.Get("params").Array()
  282. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  283. for _, v_params := range params {
  284. s_params = append(s_params, v_params.ValueStr())
  285. }
  286. }
  287. if returntype == "xlsx" {
  288. var xlsxfile *xlsx.File
  289. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  290. //c.File("c:/dd.xlsx")
  291. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  292. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  293. c.Header("Content-Transfer-Encoding", "binary")
  294. _ = xlsxfile.Write(c.Writer)
  295. } else {
  296. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  297. if err != nil {
  298. logging.Error("GetDataByName err: ", err)
  299. msg := geterrmsg(err.Error())
  300. appG.Response(http.StatusOK, e.ERROR, msg)
  301. } else {
  302. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  303. }
  304. }
  305. } else {
  306. appG.Response(http.StatusOK, e.SUCCESS, nil)
  307. }
  308. }
  309. // 错误处理
  310. // 将报错信息处理成汉字
  311. func geterrmsg(errstr string) (msgstr string) {
  312. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  313. rs := []rune(errstr)
  314. if hzRegexp.MatchString(string(rs[0])) {
  315. msgstr = errstr
  316. return
  317. }
  318. if strings.Contains(errstr, "Duplicate entry") {
  319. strs := strings.Split(errstr, ` key '`)
  320. if len(strs) > 1 {
  321. if len(strs[len(strs)-1]) > 1 {
  322. errstr = "Duplicate entry :" + strs[len(strs)-1]
  323. }
  324. }
  325. }
  326. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  327. if err != nil {
  328. msgstr = errstr
  329. return
  330. }
  331. if msg == nil || len(msg) == 0 {
  332. var param []interface{}
  333. param = append(param, errstr, errstr)
  334. go func() {
  335. tx := restful.Engine.NewSession()
  336. err := tx.Begin()
  337. defer func() {
  338. switch {
  339. case err != nil:
  340. logging.Error("tx.Begin 事务启动失败__error:", err)
  341. if tx != nil {
  342. tx.Rollback()
  343. }
  344. default:
  345. if tx != nil {
  346. err = tx.Commit()
  347. }
  348. }
  349. if tx != nil {
  350. tx.Close()
  351. }
  352. }()
  353. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  354. if err != nil {
  355. logging.Error("insert into err_msg(err,msg) err", err)
  356. }
  357. }()
  358. msgstr = errstr
  359. } else {
  360. msgstr = msg[0]["msg"]
  361. }
  362. return
  363. }
  364. // @Summary 根据APISQL表中SQL执行得到数据集
  365. // @Tags GetDataByNameForm
  366. // @Accept json
  367. // @Produce json
  368. // @Param sqlname body json true "sqlname"
  369. // @Param offset query int true "offset"
  370. // @Param pagecount query int true "pagecount"
  371. // @Param returntype query string true "returntype"
  372. // @Param s formData json true "ss"
  373. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  374. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  375. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  376. // @Router /data/GetDataByNameForm [POST]
  377. func GetDataByNameForm(c *gin.Context) {
  378. appG := app.Gin{C: c}
  379. //sqlnamestr := c.PostForm("measureNumber")
  380. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  381. //fsion := gofasion.NewFasion(string(dataByte))
  382. //sqlnamestr := fsion.Get("name").ValueStr()
  383. //offset := fsion.Get("offset").ValueInt()
  384. //pagecount := fsion.Get("pagecount").ValueInt()
  385. //returntype := fsion.Get("returntype").ValueStr()
  386. //params := fsion.Get("params").Array()
  387. c.Request.ParseForm()
  388. params := c.Request.Form
  389. offset := 0
  390. pageSize_ := 0
  391. returntype := params.Get("page")
  392. if returntype == "" {
  393. returntype = "0"
  394. }
  395. if tempv, exists := c.Get("jwt_username"); exists {
  396. params.Set("JwtUserName", tempv.(string))
  397. } else {
  398. params.Set("JwtUserName", "")
  399. }
  400. sqlnamestr := params.Get("name")
  401. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  402. s_params := make([]interface{}, 0)
  403. if returntype == "1" {
  404. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  405. if error != nil {
  406. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  407. }
  408. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  409. if error != nil {
  410. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  411. }
  412. pageSize_ = pageSize
  413. offset = pageNum
  414. }
  415. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  416. paramslist := strings.Split(p, ",")
  417. if len(paramslist) > 0 && p != "" {
  418. for _, value := range paramslist {
  419. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  420. }
  421. }
  422. if sql != "" {
  423. if returntype == "xlsx" {
  424. var xlsxfile *xlsx.File
  425. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  426. c.Header("Content-Type", "application/octet-stream")
  427. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  428. c.Header("Content-Transfer-Encoding", "binary")
  429. _ = xlsxfile.Write(c.Writer)
  430. } else {
  431. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  432. if err != nil {
  433. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  434. } else {
  435. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  436. }
  437. }
  438. } else {
  439. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  440. }
  441. }
  442. // @Summary 递归获取所有
  443. // @Tags menu
  444. // @Accept json
  445. // @Produce json
  446. // @Param Ton query string true "Ton"
  447. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  448. // @Router /authdata/GetRoleMenus [GET]
  449. func GetRecuDataByName(c *gin.Context) {
  450. appG := app.Gin{C: c}
  451. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  452. fsion := gofasion.NewFasion(string(dataByte))
  453. sqlnamestr := fsion.Get("name").ValueStr()
  454. parentidname := fsion.Get("idname").ValueStr()
  455. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  456. params := make(map[string]interface{})
  457. s_params := make([]interface{}, 0)
  458. if fsion.HasKey("params") {
  459. for _, v_params := range fsion.Get("params").Array() {
  460. s_params = append(s_params, v_params.ValueStr())
  461. }
  462. params["params"] = s_params
  463. } else {
  464. jparams := fsion.Get("parammaps")
  465. paramslist := strings.Split(p, ",")
  466. if len(paramslist) > 0 && p != "" {
  467. for _, value := range paramslist {
  468. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  469. if tempv, exists := c.Get("jwt_username"); exists {
  470. params[value] = tempv.(string)
  471. } else {
  472. params[value] = ""
  473. }
  474. } else {
  475. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  476. }
  477. }
  478. }
  479. }
  480. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  481. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  482. if err != nil {
  483. appG.Response(http.StatusOK, e.ERROR, err.Error())
  484. }
  485. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  486. }
  487. // @Summary 根据APISQL表中SQL执行得到数据集
  488. // @Tags GetDataByNames
  489. // @Accept json
  490. // @Produce json
  491. // @RequestBody sqlname query string true "sqlname"
  492. // @Param offset query int true "offset"
  493. // @Param pagecount query int true "pagecount"
  494. // @Param returntype query string true "returntype"
  495. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  496. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  497. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  498. // @Router /data/GetDataByNames [POST]
  499. func GetDataByNames(c *gin.Context) {
  500. appG := app.Gin{C: c}
  501. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  502. fsion := gofasion.NewFasion(string(dataByte))
  503. sqlParams := fsion.Array()
  504. queryData := make(map[string]interface{})
  505. for _, v := range sqlParams {
  506. fsion2 := gofasion.NewFasion(v.Json())
  507. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  508. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  509. if sql == "" {
  510. errorm := make(map[string]interface{})
  511. errorm["code"] = e.ERROR
  512. errorm["message"] = "sql没找到"
  513. queryData[fsion2.Get("name").ValueStr()] = errorm
  514. continue
  515. } else if sql != "" {
  516. offset := fsion2.Get("offset").ValueInt()
  517. pagecount := fsion2.Get("pagecount").ValueInt()
  518. returntype := fsion2.Get("returntype").ValueStr()
  519. s_params := make([]interface{}, 0)
  520. if fsion2.HasKey("parammaps") {
  521. parammaps := fsion2.Get("parammaps")
  522. paramslist := strings.Split(p, ",")
  523. if len(paramslist) > 0 && p != "" {
  524. for _, value := range paramslist {
  525. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  526. if tempv, exists := c.Get("jwt_username"); exists {
  527. s_params = append(s_params, tempv.(string))
  528. } else {
  529. s_params = append(s_params, "")
  530. }
  531. } else {
  532. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  533. }
  534. }
  535. }
  536. } else if fsion2.HasKey("params") {
  537. params := fsion2.Get("params").Array()
  538. for _, v_params := range params {
  539. s_params = append(s_params, v_params.ValueStr())
  540. }
  541. }
  542. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  543. if err != nil {
  544. errorm := make(map[string]interface{})
  545. errorm["code"] = e.ERROR
  546. errorm["message"] = err.Error()
  547. queryData[fsion2.Get("name").ValueStr()] = errorm
  548. logging.Error("GetDataByNames err: ", err)
  549. continue
  550. } else {
  551. queryData[fsion2.Get("name").ValueStr()] = queryData1
  552. }
  553. }
  554. }
  555. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  556. }
  557. // @Summary 根据APISQL表中SQL执行得到数据集
  558. // @Tags PostDataByNameForm
  559. // @Accept json
  560. // @Produce json
  561. // @Param sqlname query string true "sqlname"
  562. // @Param offset query int true "offset"
  563. // @Param pagecount query int true "pagecount"
  564. // @Param returntype query string true "returntype"
  565. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  566. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  567. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  568. // @Router /data/PostDataByNameForm [POST]
  569. func PostDataByNameForm(c *gin.Context) {
  570. appG := app.Gin{C: c}
  571. c.Request.ParseForm()
  572. params := c.Request.Form
  573. sqlnamestr := params.Get("name")
  574. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  575. s_params := make([]interface{}, 0)
  576. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  577. paramslist := strings.Split(p, ",")
  578. if len(paramslist) > 0 {
  579. for _, value := range paramslist {
  580. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  581. }
  582. }
  583. if sql != "" {
  584. queryData, err := execDataBySql(sql, s_params)
  585. if err != nil {
  586. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  587. } else {
  588. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  589. }
  590. } else {
  591. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  592. }
  593. }
  594. // @Summary 将数据集转换格式
  595. // @Tags PostDataByNameForm
  596. // @Accept json
  597. // @Produce json
  598. // @Param sqlname query string true "sqlname"
  599. // @Param offset query int true "offset"
  600. // @Param pagecount query int true "pagecount"
  601. // @Param returntype query string true "returntype"
  602. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  603. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  604. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  605. func GetReportform(c *gin.Context) {
  606. appG := app.Gin{C: c}
  607. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  608. fsion := gofasion.NewFasion(string(dataByte))
  609. sqlnamestr := fsion.Get("name").ValueStr()
  610. checked := fsion.Get("checked").ValueStr()
  611. offset := fsion.Get("offset").ValueDefaultInt(0)
  612. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  613. parammaps := fsion.Get("parammaps")
  614. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  615. tx := restful.Engine.NewSession()
  616. err := tx.Begin()
  617. defer func() {
  618. switch {
  619. case err != nil:
  620. if tx != nil {
  621. tx.Rollback()
  622. }
  623. default:
  624. if tx != nil {
  625. err = tx.Commit()
  626. }
  627. }
  628. if tx != nil {
  629. tx.Close()
  630. }
  631. }()
  632. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount)
  633. if err != nil {
  634. appG.Response(http.StatusOK, e.ERROR, err.Error())
  635. } else {
  636. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  637. }
  638. }
  639. //保养计划
  640. func GetUpkeepPlan(c *gin.Context) {
  641. appG := app.Gin{C: c}
  642. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  643. fsion := gofasion.NewFasion(string(dataByte))
  644. sqlnamestr := fsion.Get("name").ValueStr()
  645. offset := fsion.Get("offset").ValueDefaultInt(0)
  646. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  647. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  648. month := fsion.Get("month").ValueDefaultStr("map")
  649. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  650. tx := restful.Engine.NewSession()
  651. err := tx.Begin()
  652. defer func() {
  653. switch {
  654. case err != nil:
  655. if tx != nil {
  656. tx.Rollback()
  657. }
  658. default:
  659. if tx != nil {
  660. err = tx.Commit()
  661. }
  662. }
  663. if tx != nil {
  664. tx.Close()
  665. }
  666. }()
  667. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  668. if sql != "" {
  669. s_params := make([]interface{}, 0)
  670. if fsion.HasKey("parammaps") {
  671. parammaps := fsion.Get("parammaps")
  672. paramslist := strings.Split(p, ",")
  673. if len(paramslist) > 0 && p != "" {
  674. for _, value := range paramslist {
  675. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  676. if tempv, exists := c.Get("jwt_username"); exists {
  677. s_params = append(s_params, tempv.(string))
  678. } else {
  679. s_params = append(s_params, "")
  680. }
  681. } else {
  682. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  683. }
  684. }
  685. }
  686. } else if fsion.HasKey("params") {
  687. params := fsion.Get("params").Array()
  688. for _, v_params := range params {
  689. s_params = append(s_params, v_params.ValueStr())
  690. }
  691. }
  692. if returntype == "xlsx" {
  693. var xlsxfile *xlsx.File
  694. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  695. //c.File("c:/dd.xlsx")
  696. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  697. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  698. c.Header("Content-Transfer-Encoding", "binary")
  699. _ = xlsxfile.Write(c.Writer)
  700. } else {
  701. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  702. if err != nil {
  703. appG.Response(http.StatusOK, e.ERROR, err.Error())
  704. } else {
  705. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  706. if v, ok := value["id"]; ok {
  707. //month = "2020-03"
  708. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  709. if seviceplans != nil {
  710. for _, va := range seviceplans { //根据保养计划获取保养单
  711. //day,_ :=strconv.Atoi(va["day"])
  712. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  713. //buk := make(map[string]map[string]string)
  714. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  715. jstr := ""
  716. if bu["plantime"][8:9] == "0" {
  717. jstr = "m" + bu["plantime"][9:]
  718. } else {
  719. jstr = "m" + bu["plantime"][8:]
  720. }
  721. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  722. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  723. } else {
  724. if bu["flowCompeleted"] >= "2" {
  725. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  726. } else {
  727. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  728. }
  729. }
  730. }
  731. }
  732. }
  733. }
  734. }
  735. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  736. }
  737. }
  738. } else {
  739. appG.Response(http.StatusOK, e.SUCCESS, nil)
  740. }
  741. }
  742. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  743. // todo 优化性能 children统一查询
  744. // @Tags PostDataByNameForm
  745. // @Accept json
  746. // @Produce json
  747. // @Param sqlname query string true "sqlname"
  748. // @Param offset query int true "offset"
  749. // @Param pagecount query int true "pagecount"
  750. // @Param returntype query string true "returntype"
  751. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  752. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  753. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  754. func GetArrList(c *gin.Context) {
  755. appG := app.Gin{C: c}
  756. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  757. fsion := gofasion.NewFasion(string(dataByte))
  758. sqlnamestr := fsion.Get("name").ValueStr()
  759. sqlnamestr1 := fsion.Get("name1").ValueStr()
  760. offset := fsion.Get("offset").ValueDefaultInt(0)
  761. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  762. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  763. month := fsion.Get("month").ValueDefaultStr("map")
  764. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  765. tx := restful.Engine.NewSession()
  766. err := tx.Begin()
  767. defer func() {
  768. switch {
  769. case err != nil:
  770. if tx != nil {
  771. tx.Rollback()
  772. }
  773. default:
  774. if tx != nil {
  775. err = tx.Commit()
  776. }
  777. }
  778. if tx != nil {
  779. tx.Close()
  780. }
  781. }()
  782. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  783. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  784. if sql != "" {
  785. s_params := make([]interface{}, 0)
  786. if fsion.HasKey("parammaps") {
  787. parammaps := fsion.Get("parammaps")
  788. paramslist := strings.Split(p, ",")
  789. if len(paramslist) > 0 && p != "" {
  790. for _, value := range paramslist {
  791. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  792. if tempv, exists := c.Get("jwt_username"); exists {
  793. s_params = append(s_params, tempv.(string))
  794. } else {
  795. s_params = append(s_params, "")
  796. }
  797. } else {
  798. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  799. }
  800. }
  801. }
  802. }
  803. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  804. if err != nil {
  805. appG.Response(http.StatusOK, e.ERROR, err.Error())
  806. } else {
  807. paramslist1 := strings.Split(p1, ",")
  808. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  809. s_params1 := make([]interface{}, 0)
  810. if len(paramslist1) > 0 && p1 != "" {
  811. for _, v := range paramslist1 {
  812. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  813. }
  814. }
  815. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  816. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  817. }
  818. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  819. }
  820. } else {
  821. appG.Response(http.StatusOK, e.SUCCESS, nil)
  822. }
  823. }
  824. func GetAccount(c *gin.Context) {
  825. appG := app.Gin{C: c}
  826. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  827. fsion := gofasion.NewFasion(string(dataByte))
  828. sqlnamestr := fsion.Get("name").ValueStr()
  829. offset := fsion.Get("offset").ValueDefaultInt(0)
  830. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  831. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  832. tx := restful.Engine.NewSession()
  833. err := tx.Begin()
  834. defer func() {
  835. switch {
  836. case err != nil:
  837. logging.Error("tx.Begin 事务启动失败__error:", err)
  838. if tx != nil {
  839. tx.Rollback()
  840. }
  841. default:
  842. if tx != nil {
  843. err = tx.Commit()
  844. }
  845. }
  846. if tx != nil {
  847. tx.Close()
  848. }
  849. }()
  850. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  851. if sql != "" {
  852. s_params := make([]interface{}, 0)
  853. if fsion.HasKey("parammaps") {
  854. parammaps := fsion.Get("parammaps")
  855. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  856. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  857. }
  858. paramslist := strings.Split(p, ",")
  859. if len(paramslist) > 0 && p != "" {
  860. for _, value := range paramslist {
  861. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  862. if tempv, exists := c.Get("jwt_username"); exists {
  863. s_params = append(s_params, tempv.(string))
  864. } else {
  865. s_params = append(s_params, "")
  866. }
  867. } else {
  868. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  869. }
  870. }
  871. }
  872. } else if fsion.HasKey("params") {
  873. params := fsion.Get("params").Array()
  874. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  875. for _, v_params := range params {
  876. s_params = append(s_params, v_params.ValueStr())
  877. }
  878. }
  879. if returntype == "xlsx" {
  880. var xlsxfile *xlsx.File
  881. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  882. //c.File("c:/dd.xlsx")
  883. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  884. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  885. c.Header("Content-Transfer-Encoding", "binary")
  886. _ = xlsxfile.Write(c.Writer)
  887. } else {
  888. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  889. if err != nil {
  890. logging.Error("GetDataByName err: ", err)
  891. msg := geterrmsg(err.Error())
  892. appG.Response(http.StatusOK, e.ERROR, msg)
  893. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  894. } else {
  895. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  896. }
  897. }
  898. } else {
  899. appG.Response(http.StatusOK, e.SUCCESS, nil)
  900. }
  901. }
  902. // @Summary 根据APISQL表中SQL执行得到数据集
  903. // @Tags PostDataByName
  904. // @Accept json
  905. // @Produce json
  906. // @Param sqlname query string true "sqlname"
  907. // @Param offset query int true "offset"
  908. // @Param pagecount query int true "pagecount"
  909. // @Param returntype query string true "returntype"
  910. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  911. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  912. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  913. // @Router /data/PostDataByName [POST]
  914. func PostDataByName(c *gin.Context) {
  915. appG := app.Gin{C: c}
  916. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  917. fsion := gofasion.NewFasion(string(dataByte))
  918. sqlnamestr := fsion.Get("name").ValueStr()
  919. s_params := make([]interface{}, 0)
  920. tx := restful.Engine.NewSession()
  921. err := tx.Begin()
  922. defer func() {
  923. switch {
  924. case err != nil:
  925. if tx != nil {
  926. tx.Rollback()
  927. }
  928. default:
  929. if tx != nil {
  930. err = tx.Commit()
  931. }
  932. }
  933. if tx != nil {
  934. tx.Close()
  935. }
  936. }()
  937. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  938. if sql != "" {
  939. if fsion.HasKey("parammaps") {
  940. parammaps := fsion.Get("parammaps")
  941. logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  942. paramslist := strings.Split(p, ",")
  943. if len(paramslist) > 0 && p != "" {
  944. for _, value := range paramslist {
  945. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  946. if tempv, exists := c.Get("jwt_username"); exists {
  947. s_params = append(s_params, tempv.(string))
  948. } else {
  949. s_params = append(s_params, "")
  950. }
  951. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  952. ids, err := setting.SnowIds.NextId()
  953. if err != nil {
  954. ids = time.Now().UnixNano()
  955. logging.Info("create SnowIds err", err)
  956. }
  957. s_params = append(s_params, ids)
  958. } else {
  959. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  960. }
  961. }
  962. }
  963. } else if fsion.HasKey("params") {
  964. params := fsion.Get("params").Array()
  965. logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  966. //ids,err := setting.SnowIds.NextId()
  967. //if err !=nil{
  968. // ids = time.Now().UnixNano()
  969. // logging.Info("create SnowIds err",err)
  970. //}
  971. //s_params = append(s_params, ids)
  972. for _, v_params := range params {
  973. s_params = append(s_params, v_params.ValueStr())
  974. }
  975. }
  976. queryData, err := execDataBySqlT(sql, s_params, tx)
  977. if err != nil {
  978. logging.Error("PostDataByName err: ", err)
  979. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  980. if (sqlnamestr == "copybarfeedremain" || sqlnamestr == "copyFtdry" || sqlnamestr == "copyPennsieve") &&
  981. strings.Contains(err.Error(), "Duplicate entry") {
  982. appG.Response(http.StatusOK, e.ERROR, "同一栏舍,同一班次不可重复录入")
  983. } else if (sqlnamestr == "copybarmilk" || sqlnamestr == "copyBodyscore" || sqlnamestr == "copyDungsieve" || sqlnamestr == "copyDungscore") &&
  984. strings.Contains(err.Error(), "Duplicate entry") {
  985. appG.Response(http.StatusOK, e.ERROR, "同一栏舍不可重复录入")
  986. } else {
  987. msg := geterrmsg(err.Error())
  988. appG.Response(http.StatusOK, e.ERROR, msg)
  989. }
  990. } else {
  991. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  992. }
  993. } else {
  994. appG.Response(http.StatusOK, e.SUCCESS, nil)
  995. }
  996. }
  997. //人脸识别/格润富德接口
  998. func GetRJSBData(c *gin.Context) {
  999. appG := app.Gin{C: c}
  1000. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1001. fsion := gofasion.NewFasion(string(dataByte))
  1002. sqlnamestr := fsion.Get("name").ValueStr()
  1003. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1004. offset := fsion.Get("offset").ValueDefaultInt(0)
  1005. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1006. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1007. month := fsion.Get("month").ValueDefaultStr("map")
  1008. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1009. tx := restful.Engine.NewSession()
  1010. err := tx.Begin()
  1011. defer func() {
  1012. switch {
  1013. case err != nil:
  1014. if tx != nil {
  1015. tx.Rollback()
  1016. }
  1017. default:
  1018. if tx != nil {
  1019. err = tx.Commit()
  1020. }
  1021. }
  1022. if tx != nil {
  1023. tx.Close()
  1024. }
  1025. }()
  1026. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1027. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1028. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1029. if sql != "" {
  1030. s_params := make([]interface{}, 0)
  1031. if fsion.HasKey("parammaps") {
  1032. parammaps := fsion.Get("parammaps")
  1033. paramslist := strings.Split(p, ",")
  1034. if len(paramslist) > 0 && p != "" {
  1035. for _, value := range paramslist {
  1036. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1037. if tempv, exists := c.Get("jwt_username"); exists {
  1038. s_params = append(s_params, tempv.(string))
  1039. } else {
  1040. s_params = append(s_params, "")
  1041. }
  1042. } else {
  1043. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1044. }
  1045. }
  1046. }
  1047. }
  1048. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1049. if err != nil {
  1050. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1051. } else {
  1052. paramslist1 := strings.Split(p1, ",")
  1053. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1054. s_params1 := make([]interface{}, 0)
  1055. if len(paramslist1) > 0 && p1 != "" {
  1056. for _, v := range paramslist1 {
  1057. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1058. }
  1059. }
  1060. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1061. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1062. }
  1063. var wg sync.WaitGroup
  1064. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1065. wg.Add(1)
  1066. go func(value map[string]interface{}) {
  1067. defer wg.Done()
  1068. _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1069. }(value)
  1070. }
  1071. wg.Wait()
  1072. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1073. }
  1074. } else {
  1075. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1076. }
  1077. }
  1078. func PostRJSBData(c *gin.Context) {
  1079. appG := app.Gin{C: c}
  1080. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1081. fsion := gofasion.NewFasion(string(dataByte))
  1082. logging.Info("PostRJSBData err: ", string(dataByte))
  1083. s_params := make([]interface{}, 0)
  1084. tx := restful.Engine.NewSession()
  1085. err := tx.Begin()
  1086. defer func() {
  1087. switch {
  1088. case err != nil:
  1089. if tx != nil {
  1090. tx.Rollback()
  1091. }
  1092. default:
  1093. if tx != nil {
  1094. err = tx.Commit()
  1095. }
  1096. }
  1097. if tx != nil {
  1098. tx.Close()
  1099. }
  1100. }()
  1101. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1102. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1103. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1104. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1105. if !fsion.HasKey("parammaps") {
  1106. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1107. return
  1108. }
  1109. parammaps := fsion.Get("parammaps")
  1110. paramslist := strings.Split(p, ",")
  1111. if len(paramslist) > 0 && p != "" {
  1112. for _, value := range paramslist {
  1113. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1114. }
  1115. }
  1116. _, err = tx.SQL(sql, s_params...).Execute()
  1117. if err != nil {
  1118. logging.Error("PostRJSBData err: ", err)
  1119. msg := geterrmsg(err.Error())
  1120. appG.Response(http.StatusOK, e.ERROR, msg)
  1121. return
  1122. }
  1123. s_params = make([]interface{}, 0)
  1124. paramslist = strings.Split(p1, ",")
  1125. if len(paramslist) > 0 && p1 != "" {
  1126. for _, value := range paramslist {
  1127. // if value == "ID" {
  1128. // id := parammaps.Get("ID").ValueStr()
  1129. // pastureid := parammaps.Get("pastureid").ValueStr()
  1130. // 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
  1131. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1132. // if err != nil {
  1133. // logging.Error("PostRJSBData err: ", err)
  1134. // msg := geterrmsg(err.Error())
  1135. // appG.Response(http.StatusOK, e.ERROR, msg)
  1136. // return
  1137. // }
  1138. // for _, item := range datalist {
  1139. // id = item["id"]
  1140. // }
  1141. // s_params = append(s_params, id)
  1142. // } else {
  1143. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1144. // }
  1145. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1146. }
  1147. }
  1148. _, err = tx.SQL(sql1, s_params...).Execute()
  1149. if err != nil {
  1150. logging.Error("PostRJSBData1 err: ", err)
  1151. msg := geterrmsg(err.Error())
  1152. appG.Response(http.StatusOK, e.ERROR, msg)
  1153. return
  1154. }
  1155. s_params = make([]interface{}, 0)
  1156. paramslist = strings.Split(p2, ",")
  1157. if len(paramslist) > 0 && p2 != "" {
  1158. for _, value := range paramslist {
  1159. if value == "ID" {
  1160. id := parammaps.Get("ID").ValueStr()
  1161. pastureid := parammaps.Get("pastureid").ValueStr()
  1162. 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
  1163. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1164. if err != nil {
  1165. logging.Error("PostRJSBData err: ", err)
  1166. msg := geterrmsg(err.Error())
  1167. appG.Response(http.StatusOK, e.ERROR, msg)
  1168. return
  1169. }
  1170. for _, item := range datalist {
  1171. id = item["id"]
  1172. }
  1173. s_params = append(s_params, id)
  1174. } else {
  1175. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1176. }
  1177. }
  1178. }
  1179. _, err = tx.SQL(sql2, s_params...).Execute()
  1180. if err != nil {
  1181. logging.Error("PostRJSBData2 err: ", err)
  1182. msg := geterrmsg(err.Error())
  1183. appG.Response(http.StatusOK, e.ERROR, msg)
  1184. return
  1185. }
  1186. s_params = make([]interface{}, 0)
  1187. paramslist = strings.Split(p3, ",")
  1188. if len(paramslist) > 0 && p3 != "" {
  1189. for _, value := range paramslist {
  1190. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1191. }
  1192. }
  1193. _, err = tx.SQL(sql3, s_params...).Execute()
  1194. if err != nil {
  1195. logging.Error("PostRJSBData3 err: ", err)
  1196. msg := geterrmsg(err.Error())
  1197. appG.Response(http.StatusOK, e.ERROR, msg)
  1198. return
  1199. }
  1200. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1201. }
  1202. func PostRJSBDatas(c *gin.Context) {
  1203. appG := app.Gin{C: c}
  1204. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1205. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1206. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1207. tx := restful.Engine.NewSession()
  1208. err := tx.Begin()
  1209. defer func() {
  1210. switch {
  1211. case err != nil:
  1212. if tx != nil {
  1213. tx.Rollback()
  1214. }
  1215. default:
  1216. if tx != nil {
  1217. err = tx.Commit()
  1218. }
  1219. }
  1220. if tx != nil {
  1221. tx.Close()
  1222. }
  1223. }()
  1224. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1225. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1226. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1227. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1228. for _, fsion := range fsions {
  1229. if !fsion.HasKey("parammaps") {
  1230. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1231. return
  1232. }
  1233. parammaps := fsion.Get("parammaps")
  1234. s_params := make([]interface{}, 0)
  1235. paramslist := strings.Split(p, ",")
  1236. if len(paramslist) > 0 && p != "" {
  1237. for _, value := range paramslist {
  1238. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1239. }
  1240. }
  1241. _, err = tx.SQL(sql, s_params...).Execute()
  1242. if err != nil {
  1243. logging.Error("PostRJSBData err: ", err)
  1244. msg := geterrmsg(err.Error())
  1245. appG.Response(http.StatusOK, e.ERROR, msg)
  1246. return
  1247. }
  1248. s_params = make([]interface{}, 0)
  1249. paramslist = strings.Split(p1, ",")
  1250. if len(paramslist) > 0 && p1 != "" {
  1251. for _, value := range paramslist {
  1252. // if value == "ID" {
  1253. // id := parammaps.Get("ID").ValueStr()
  1254. // pastureid := parammaps.Get("pastureid").ValueStr()
  1255. // 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
  1256. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1257. // if err != nil {
  1258. // logging.Error("PostRJSBData err: ", err)
  1259. // msg := geterrmsg(err.Error())
  1260. // appG.Response(http.StatusOK, e.ERROR, msg)
  1261. // return
  1262. // }
  1263. // for _, item := range datalist {
  1264. // id = item["id"]
  1265. // }
  1266. // s_params = append(s_params, id)
  1267. // } else {
  1268. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1269. // }
  1270. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1271. }
  1272. }
  1273. _, err = tx.SQL(sql1, s_params...).Execute()
  1274. if err != nil {
  1275. logging.Error("PostRJSBData1 err: ", err)
  1276. msg := geterrmsg(err.Error())
  1277. appG.Response(http.StatusOK, e.ERROR, msg)
  1278. return
  1279. }
  1280. s_params = make([]interface{}, 0)
  1281. paramslist = strings.Split(p2, ",")
  1282. if len(paramslist) > 0 && p2 != "" {
  1283. for _, value := range paramslist {
  1284. if value == "ID" {
  1285. id := parammaps.Get("ID").ValueStr()
  1286. pastureid := parammaps.Get("pastureid").ValueStr()
  1287. 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
  1288. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1289. if err != nil {
  1290. logging.Error("PostRJSBData err: ", err)
  1291. msg := geterrmsg(err.Error())
  1292. appG.Response(http.StatusOK, e.ERROR, msg)
  1293. return
  1294. }
  1295. for _, item := range datalist {
  1296. id = item["id"]
  1297. }
  1298. s_params = append(s_params, id)
  1299. } else {
  1300. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1301. }
  1302. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1303. }
  1304. }
  1305. _, err = tx.SQL(sql2, s_params...).Execute()
  1306. if err != nil {
  1307. logging.Error("PostRJSBData2 err: ", err)
  1308. msg := geterrmsg(err.Error())
  1309. appG.Response(http.StatusOK, e.ERROR, msg)
  1310. return
  1311. }
  1312. s_params = make([]interface{}, 0)
  1313. paramslist = strings.Split(p3, ",")
  1314. if len(paramslist) > 0 && p3 != "" {
  1315. for _, value := range paramslist {
  1316. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1317. }
  1318. }
  1319. _, err = tx.SQL(sql3, s_params...).Execute()
  1320. if err != nil {
  1321. logging.Error("PostRJSBData3 err: ", err)
  1322. msg := geterrmsg(err.Error())
  1323. appG.Response(http.StatusOK, e.ERROR, msg)
  1324. return
  1325. }
  1326. }
  1327. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1328. }
  1329. // @Summary 根据APISQL表中SQL执行得到数据集
  1330. // @Tags ExecDataByConfig
  1331. // @Accept json
  1332. // @Produce json
  1333. // @Param sqlname query string true "sqlname"
  1334. // @Param offset query int true "offset"
  1335. // @Param pagecount query int true "pagecount"
  1336. // @Param returntype query string true "returntype"
  1337. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1338. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1339. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1340. // @Router /data/PostDataByName [POST]
  1341. func ExecDataByConfig(c *gin.Context) {
  1342. appG := app.Gin{C: c}
  1343. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1344. tempval_ := make(map[string]interface{})
  1345. tempCommon := make(map[string]interface{})
  1346. tempval := make([]map[string]interface{}, 0)
  1347. err := json.Unmarshal(dataByte, &tempval_)
  1348. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1349. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1350. if err != nil {
  1351. } else {
  1352. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1353. tempCommon = v
  1354. }
  1355. if v, ok := tempval_["data"].([]interface{}); ok {
  1356. for _, Tvalue := range v {
  1357. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1358. tempval = append(tempval, v1)
  1359. }
  1360. }
  1361. }
  1362. tx := restful.Engine.NewSession()
  1363. err := tx.Begin()
  1364. if err != nil {
  1365. logging.Error("tx.Begin 事务启动失败__error:", err)
  1366. }
  1367. defer func() {
  1368. switch {
  1369. case err != nil:
  1370. if tx != nil {
  1371. tx.Rollback()
  1372. }
  1373. default:
  1374. if tx != nil {
  1375. err = tx.Commit()
  1376. }
  1377. }
  1378. if tx != nil {
  1379. tx.Close()
  1380. }
  1381. }()
  1382. if err == nil {
  1383. if tempv, exists := c.Get("jwt_username"); exists {
  1384. tempCommon["jwt_username"] = tempv.(string)
  1385. }
  1386. for _, paramvalue := range tempval {
  1387. if _, ok := paramvalue["resultname"]; !ok {
  1388. paramvalue["resultname"] = paramvalue["name"]
  1389. }
  1390. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1391. if err != nil {
  1392. logging.Error("ExecDataParam error:", err)
  1393. break
  1394. }
  1395. }
  1396. if err == nil {
  1397. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1398. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1399. } else {
  1400. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1401. }
  1402. } else {
  1403. msg := geterrmsg(err.Error())
  1404. appG.Response(http.StatusOK, e.ERROR, msg)
  1405. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1406. }
  1407. }
  1408. }
  1409. if err != nil {
  1410. msg := geterrmsg(err.Error())
  1411. appG.Response(http.StatusOK, e.ERROR, msg)
  1412. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1413. }
  1414. }
  1415. func interfacetostring(val interface{}) string {
  1416. switch val.(type) {
  1417. case string:
  1418. ss := val.(string)
  1419. return ss
  1420. break
  1421. case int:
  1422. ss := val.(int)
  1423. return strconv.Itoa(ss)
  1424. break
  1425. case int64:
  1426. ss := val.(int64)
  1427. return strconv.FormatInt(ss, 10)
  1428. break
  1429. case float64:
  1430. ss := val.(float64)
  1431. return strconv.FormatFloat(ss, 'E', -1, 32)
  1432. break
  1433. }
  1434. return ""
  1435. }
  1436. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1437. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1438. tempstrb := strings.IndexAny(valuestring, "@")
  1439. tempstre := strings.IndexAny(valuestring, ".")
  1440. if tempstrb > -1 && tempstre > -1 {
  1441. for _, ParamMapList := range ParamMap {
  1442. if v, ok := ParamMapList["resultname"]; ok {
  1443. if v == valuestring[tempstrb+1:tempstre] {
  1444. if v1, ok := ParamMapList["resultmaps"]; ok {
  1445. if newA, ok := v1.([]map[string]interface{}); ok {
  1446. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1447. } else if newA, ok := v1.(map[string]interface{}); ok {
  1448. return interfacetostring(newA[valuestring[tempstre+1:]])
  1449. }
  1450. }
  1451. }
  1452. }
  1453. }
  1454. } else {
  1455. return valuestring
  1456. }
  1457. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1458. return strconv.FormatInt(int64(valuestring), 10)
  1459. }
  1460. return ""
  1461. }
  1462. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1463. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1464. tempstrb := strings.IndexAny(valuestring, "@")
  1465. tempstre := strings.IndexAny(valuestring, ".")
  1466. if tempstrb > -1 && tempstre > -1 {
  1467. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1468. if s, ok := v.(string); ok {
  1469. return s
  1470. } else if s, ok := v.(float64); ok {
  1471. return strconv.FormatFloat(s, 'f', -1, 64)
  1472. // return strconv.FormatInt(int64(s), 10)
  1473. }
  1474. }
  1475. }
  1476. }
  1477. return ""
  1478. }
  1479. 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) {
  1480. sqlname := fasion["name"].(string)
  1481. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1482. if v, ok := fasion["type"]; ok {
  1483. sqltype = v.(string)
  1484. }
  1485. sql := ""
  1486. p := ""
  1487. s_params := make([]interface{}, 0)
  1488. if sqltype != "" {
  1489. sql, p = restful.GetSqlByName(sqlname, tx)
  1490. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1491. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1492. paramslist := strings.Split(p, ",")
  1493. if len(paramslist) > 0 && p != "" {
  1494. for _, value := range paramslist {
  1495. ss := ""
  1496. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1497. ids, err := setting.SnowIds.NextId()
  1498. if err != nil {
  1499. ids = time.Now().UnixNano()
  1500. logging.Info("create SnowIds err", err)
  1501. }
  1502. s_params = append(s_params, ids)
  1503. } else {
  1504. if ss == "" && CommonParamMap != nil {
  1505. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1506. ss = valuestring
  1507. tempstrb := strings.IndexAny(valuestring, "@")
  1508. tempstre := strings.IndexAny(valuestring, ".")
  1509. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1510. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1511. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1512. }
  1513. } else {
  1514. ss = ""
  1515. }
  1516. }
  1517. }
  1518. if ss == "" && ParentParamMap != nil {
  1519. ss = getParamValue_(v, value, ParentParamMap)
  1520. }
  1521. if ss == "" && sameParamMap != nil {
  1522. ss = getParamValue(v, value, sameParamMap)
  1523. }
  1524. if ss == "" && ParamMap != nil {
  1525. ss = getParamValue(v, value, ParamMap)
  1526. }
  1527. s_params = append(s_params, ss)
  1528. }
  1529. }
  1530. }
  1531. }
  1532. }
  1533. if sql == "" {
  1534. sqltype = ""
  1535. }
  1536. if sqltype == "s1" {
  1537. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1538. if v, ok := tempValParam.(map[string]interface{}); ok {
  1539. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1540. }
  1541. if err != nil {
  1542. return nil, err
  1543. }
  1544. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1545. if err != nil {
  1546. return nil, err
  1547. }
  1548. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1549. } else if sqltype == "sm" {
  1550. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1551. if v, ok := tempValParam.(map[string]interface{}); ok {
  1552. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1553. } else {
  1554. }
  1555. if err != nil {
  1556. return nil, err
  1557. }
  1558. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1559. if err != nil {
  1560. return nil, err
  1561. }
  1562. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1563. } else if sqltype == "v" {
  1564. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1565. if v, ok := tempValParam.(map[string]interface{}); ok {
  1566. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1567. } else {
  1568. }
  1569. if err != nil {
  1570. return nil, err
  1571. }
  1572. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1573. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1574. }
  1575. } else if sqltype == "e" {
  1576. tempVal_arrary := make([]map[string]interface{}, 0)
  1577. tempVal_map := make(map[string]interface{})
  1578. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1579. if err == nil {
  1580. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1581. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1582. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1583. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1584. return tempVal_arrary, err
  1585. }
  1586. return nil, err
  1587. } else {
  1588. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1589. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1590. if err != nil {
  1591. return nil, err
  1592. }
  1593. return nil, err
  1594. }
  1595. }
  1596. return nil, nil
  1597. }
  1598. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1599. var err error
  1600. subarray, ok := fasion["children"]
  1601. if ok {
  1602. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1603. tempVal_arrary := make([]map[string]interface{}, 0)
  1604. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1605. tempVal_ := make(map[string]interface{})
  1606. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1607. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1608. } else {
  1609. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1610. }
  1611. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1612. if err != nil {
  1613. return err
  1614. }
  1615. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1616. }
  1617. v.(map[string]interface{})["children"] = tempVal_arrary
  1618. }
  1619. }
  1620. return nil
  1621. }
  1622. // @Summary 删除图片
  1623. // @Tags RemovePicByName
  1624. // @Accept json
  1625. // @Produce json
  1626. // @Param sqlname query string true "sqlname"
  1627. // @Param offset query int true "offset"
  1628. // @Param pagecount query int true "pagecount"
  1629. // @Param returntype query string true "returntype"
  1630. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1631. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1632. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1633. // @Router /data/PostDataByName [POST]
  1634. func RemovePicByName(c *gin.Context) {
  1635. logging.Info("RemovePicByName ", c.Keys)
  1636. appG := app.Gin{C: c}
  1637. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1638. fsion := gofasion.NewFasion(string(dataByte))
  1639. sqlnamestr := fsion.Get("name").ValueStr()
  1640. picname := fsion.Get("picname").ValueStr()
  1641. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1642. params := fsion.Get("params").Array()
  1643. s_params := make([]interface{}, 0)
  1644. for _, v_params := range params {
  1645. s_params = append(s_params, v_params.ValueStr())
  1646. }
  1647. if sql != "" {
  1648. queryData, err := execDataBySql(sql, s_params)
  1649. if picname != "" {
  1650. // Destination
  1651. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1652. err := os.Remove(distPath) //删除文件test.txt
  1653. if err != nil {
  1654. //如果删除失败则输出 file remove Error!
  1655. fmt.Println("file remove Error!")
  1656. //输出错误详细信息
  1657. fmt.Printf("%s", err)
  1658. } else {
  1659. //如果删除成功则输出 file remove OK!
  1660. fmt.Print("file remove OK!")
  1661. }
  1662. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1663. err = os.Remove(distPath) //删除文件test.txt
  1664. if err != nil {
  1665. //如果删除失败则输出 file remove Error!
  1666. fmt.Println("file remove Error!")
  1667. //输出错误详细信息
  1668. fmt.Printf("%s", err)
  1669. } else {
  1670. //如果删除成功则输出 file remove OK!
  1671. fmt.Print("file remove OK!")
  1672. }
  1673. }
  1674. if err != nil {
  1675. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1676. } else {
  1677. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1678. }
  1679. } else {
  1680. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1681. }
  1682. }
  1683. // @Summary 删除文件
  1684. // @Tags RemoveFileByName
  1685. // @Accept json
  1686. // @Produce json
  1687. // @Param sqlname query string true "sqlname"
  1688. // @Param offset query int true "offset"
  1689. // @Param pagecount query int true "pagecount"
  1690. // @Param returntype query string true "returntype"
  1691. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1692. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1693. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1694. // @Router /data/PostDataByName [POST]
  1695. func RemoveFileByName(c *gin.Context) {
  1696. appG := app.Gin{C: c}
  1697. id := c.Param("id")
  1698. logging.Info("DownloadFile ", c.Keys, id)
  1699. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1700. if eqdoc == nil {
  1701. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1702. return
  1703. }
  1704. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1705. err = os.Remove(distPath) //删除文件test.txt
  1706. if err != nil {
  1707. //如果删除失败则输出 file remove Error!
  1708. fmt.Println("file remove Error!")
  1709. //输出错误详细信息
  1710. fmt.Printf("%s", err)
  1711. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1712. return
  1713. }
  1714. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1715. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1716. }
  1717. // @Summary 根据APISQL表中SQL执行得到数据集
  1718. // @Tags PostDataByName
  1719. // @Accept json
  1720. // @Produce json
  1721. // @Param sqlname query string true "sqlname"
  1722. // @Param offset query int true "offset"
  1723. // @Param pagecount query int true "pagecount"
  1724. // @Param returntype query string true "returntype"
  1725. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1726. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1727. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1728. // @Router /data/PostDataByName [POST]
  1729. func UpdateDataRelation(c *gin.Context) {
  1730. appG := app.Gin{C: c}
  1731. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1732. fsion := gofasion.NewFasion(string(dataByte))
  1733. tablename := fsion.Get("name").ValueStr()
  1734. dataname := fsion.Get("dataname").ValueStr()
  1735. datavalue := fsion.Get("datavalue").ValueStr()
  1736. valuename := fsion.Get("valuename").ValueStr()
  1737. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1738. values := fsion.Get("values").Array()
  1739. tx := restful.Engine.NewSession()
  1740. err := tx.Begin()
  1741. defer func() {
  1742. switch {
  1743. case err != nil:
  1744. if tx != nil {
  1745. tx.Rollback()
  1746. }
  1747. default:
  1748. if tx != nil {
  1749. err = tx.Commit()
  1750. }
  1751. }
  1752. if tx != nil {
  1753. tx.Close()
  1754. }
  1755. }()
  1756. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1757. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1758. d_params := make([]interface{}, 4)
  1759. d_params[0] = datavalue
  1760. s_params := ""
  1761. for _, v_values := range values {
  1762. d_params[1] = v_values.ValueStr()
  1763. if s_params == "" {
  1764. s_params = v_values.ValueStr()
  1765. } else {
  1766. s_params = s_params + "," + v_values.ValueStr()
  1767. }
  1768. d_params[2] = d_params[1]
  1769. d_params[3] = d_params[0]
  1770. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1771. if err != nil {
  1772. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1773. break
  1774. }
  1775. }
  1776. if s_params != "" {
  1777. deleteSqlstr := "delete from " + tablename + " " +
  1778. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1779. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1780. if err != nil {
  1781. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1782. } else if err == nil {
  1783. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1784. }
  1785. } else {
  1786. deleteSqlstr := "delete from " + tablename + " " +
  1787. " where " + dataname + " = " + datavalue
  1788. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1789. if err != nil {
  1790. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1791. } else if err == nil {
  1792. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1793. }
  1794. }
  1795. }
  1796. // @Summary 根据APISQL表中SQL执行得到数据集
  1797. // @Tags PostDatasByName
  1798. // @Accept json
  1799. // @Produce json
  1800. // @Param sqlname query string true "sqlname"
  1801. // @Param offset query int true "offset"
  1802. // @Param pagecount query int true "pagecount"
  1803. // @Param returntype query string true "returntype"
  1804. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1805. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1806. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1807. // @Router /data/PostDatasByName [POST]
  1808. func PostDataByNames(c *gin.Context) {
  1809. appG := app.Gin{C: c}
  1810. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1811. fsion := gofasion.NewFasion(string(dataByte))
  1812. sqlParams := fsion.Get("array").Array()
  1813. queryData := make(map[string]interface{})
  1814. for _, v := range sqlParams {
  1815. fsion2 := gofasion.NewFasion(v.Json())
  1816. ss := fsion2.Get("name")
  1817. aa := fsion2.Get("params")
  1818. fmt.Println(ss, aa)
  1819. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1820. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1821. if sql == "" {
  1822. errorm := make(map[string]interface{})
  1823. errorm["code"] = e.ERROR
  1824. errorm["message"] = "sql没有找到"
  1825. errorm["param"] = ""
  1826. queryData[fsion2.Get("name").ValueStr()] = errorm
  1827. continue
  1828. } else if sql != "" {
  1829. s_params := make([]interface{}, 0)
  1830. if fsion2.HasKey("parammaps") {
  1831. parammaps := fsion2.Get("parammaps")
  1832. paramslist := strings.Split(p, ",")
  1833. if len(paramslist) > 0 && p != "" {
  1834. for _, value := range paramslist {
  1835. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1836. if tempv, exists := c.Get("jwt_username"); exists {
  1837. s_params = append(s_params, tempv.(string))
  1838. } else {
  1839. s_params = append(s_params, "")
  1840. }
  1841. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1842. ids, err := setting.SnowIds.NextId()
  1843. if err != nil {
  1844. ids = time.Now().UnixNano()
  1845. logging.Info("create SnowIds err", err)
  1846. }
  1847. s_params = append(s_params, ids)
  1848. } else {
  1849. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1850. }
  1851. }
  1852. }
  1853. } else if fsion2.HasKey("params") {
  1854. params := fsion2.Get("params").Array()
  1855. //ids,err := setting.SnowIds.NextId()
  1856. //if err !=nil{
  1857. // ids = time.Now().UnixNano()
  1858. // logging.Info("create SnowIds err",err)
  1859. //}
  1860. //s_params = append(s_params, ids)
  1861. for _, v_params := range params {
  1862. s_params = append(s_params, v_params.ValueStr())
  1863. }
  1864. }
  1865. _, err := execDataBySql(sql, s_params)
  1866. if err != nil {
  1867. logging.Error("PostDataByName err: ", err)
  1868. errorm := make(map[string]interface{})
  1869. errorm["code"] = e.ERROR
  1870. errorm["message"] = err.Error()
  1871. errorm["param"] = s_params
  1872. queryData[fsion2.Get("name").ValueStr()] = errorm
  1873. continue
  1874. } else {
  1875. errorm := make(map[string]interface{})
  1876. errorm["code"] = e.SUCCESS
  1877. errorm["message"] = "success"
  1878. queryData[fsion2.Get("name").ValueStr()] = errorm
  1879. continue
  1880. }
  1881. } else {
  1882. errorm := make(map[string]interface{})
  1883. errorm["code"] = e.ERROR
  1884. errorm["message"] = "NO SQL"
  1885. errorm["param"] = ""
  1886. queryData[fsion2.Get("name").ValueStr()] = errorm
  1887. }
  1888. }
  1889. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1890. }
  1891. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1892. if offset > 0 {
  1893. offset = offset - 1
  1894. }
  1895. //if pagecount == 0 {
  1896. // pagecount = setting.AppSetting.PageSize
  1897. //}else if pagecount>setting.AppSetting.PageSize{
  1898. // pagecount = setting.AppSetting.PageSize
  1899. //}
  1900. if returntype == "list" {
  1901. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1902. return queryData, err
  1903. } else if returntype == "listlist" {
  1904. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1905. return queryData, err
  1906. } else {
  1907. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1908. return queryData, err
  1909. }
  1910. }
  1911. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1912. if offset > 0 {
  1913. offset = offset - 1
  1914. }
  1915. //if pagecount == 0 {
  1916. // pagecount = setting.AppSetting.PageSize
  1917. //}else if pagecount>setting.AppSetting.PageSize{
  1918. // pagecount = setting.AppSetting.PageSize
  1919. //}
  1920. if returntype == "list" {
  1921. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1922. return queryData, err
  1923. } else if returntype == "listlist" {
  1924. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1925. return queryData, err
  1926. } else {
  1927. fmt.Println(params)
  1928. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1929. return queryData, err
  1930. }
  1931. }
  1932. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1933. paramslist := strings.Split(Params, ",")
  1934. s_params := make([]interface{}, 0)
  1935. if isList {
  1936. for _, v_params := range thisParams["params"].([]interface{}) {
  1937. s_params = append(s_params, v_params)
  1938. }
  1939. } else {
  1940. paramslist := strings.Split(Params, ",")
  1941. if len(paramslist) > 0 && Params != "" {
  1942. for _, value := range paramslist {
  1943. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1944. }
  1945. }
  1946. }
  1947. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  1948. for _, queryData_ := range queryData {
  1949. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  1950. if isList {
  1951. if queryData_[idname] != nil {
  1952. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  1953. }
  1954. } else {
  1955. if queryData_[idname] != nil {
  1956. thisParams[idname] = queryData_[idname].(interface{})
  1957. }
  1958. if len(paramslist) > 0 && Params != "" {
  1959. s_params = make([]interface{}, 0)
  1960. for _, value := range paramslist {
  1961. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1962. }
  1963. }
  1964. }
  1965. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  1966. } else {
  1967. }
  1968. }
  1969. return queryData, err
  1970. }
  1971. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1972. queryData, err := restful.ExecQuery(sqlstr, params)
  1973. return queryData, err
  1974. }
  1975. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1976. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  1977. return queryData, err
  1978. }
  1979. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1980. queryData, err := restful.ExecQuery(sqlstr, params)
  1981. return queryData, err
  1982. }
  1983. // @Summary 导入excel文件到数据库,excel第一行作为参数
  1984. // @Tags ImportExcel
  1985. // @Accept json
  1986. // @Produce json
  1987. // @Param file query string true "文件名"
  1988. // @Param name header string true "执行sql的名字"
  1989. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1990. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1991. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1992. // @Router /data/ImportExcel [POST]
  1993. func ImportExcel(c *gin.Context) {
  1994. appG := app.Gin{C: c}
  1995. inputdata := ""
  1996. c.Request.ParseForm()
  1997. params := c.Request.Form
  1998. file, _, err := c.Request.FormFile("file")
  1999. if err != nil {
  2000. appG.Response(http.StatusOK, e.ERROR, err)
  2001. return
  2002. }
  2003. sqlnamestrs := params.Get("name")
  2004. sheetname := params.Get("sheetname")
  2005. pastureid := params.Get("pastureid")
  2006. //importParams := params.Get("importParams")
  2007. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2008. // 必输项参数 (字符串格式 "field1,field2,field3")
  2009. requiredParams := params.Get("requiredParams")
  2010. // 日期参数
  2011. dateParams := params.Get("dateParams")
  2012. // 数字参数
  2013. numParams := params.Get("numParams")
  2014. //将字符串分割开
  2015. dateParamslist := strings.Split(dateParams, ",")
  2016. requiredParamslist := strings.Split(requiredParams, ",")
  2017. numParamslist := strings.Split(numParams, ",")
  2018. queryData := make([]interface{}, 0)
  2019. sqlslist := strings.Split(sqlnamestrs, ",")
  2020. xlsx1, err := excelize.OpenReader(file)
  2021. if err != nil {
  2022. fmt.Println(err)
  2023. return
  2024. }
  2025. ok := 0
  2026. error := 0
  2027. isdone := true
  2028. rows, _ := xlsx1.GetRows(sheetname)
  2029. // 限制10000条,多余的截取掉
  2030. if len(rows) > 10000 {
  2031. rows = rows[:10000]
  2032. }
  2033. for i, row := range rows {
  2034. if i > 0 {
  2035. entry := make(map[string]interface{})
  2036. outentry := make(map[string]interface{})
  2037. for j, colCell := range rows[0] {
  2038. for k, colCell1 := range row {
  2039. if j == k {
  2040. outentry[colCell] = colCell1
  2041. entry[colCell] = colCell1
  2042. }
  2043. }
  2044. }
  2045. inputdata = ""
  2046. a := ""
  2047. fmt.Println(outentry, entry)
  2048. //校验日期格式
  2049. for _, v := range dateParamslist {
  2050. if v == "" {
  2051. continue
  2052. }
  2053. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2054. dtime, err := TransfTime(d.(string))
  2055. if err != nil {
  2056. a = strings.Trim(v, " ")
  2057. break
  2058. }
  2059. outentry[strings.Trim(v, " ")] = dtime
  2060. }
  2061. }
  2062. if a != "" {
  2063. outentry["error_msg"] = a + " 格式错误"
  2064. error++
  2065. queryData = append(queryData, outentry)
  2066. continue
  2067. }
  2068. a = ""
  2069. //校验必填格式
  2070. for _, v := range requiredParamslist {
  2071. if v == "" {
  2072. continue
  2073. }
  2074. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2075. a = strings.Trim(v, " ")
  2076. break
  2077. }
  2078. }
  2079. if a != "" {
  2080. outentry["error_msg"] = a + " 未填或格式错误"
  2081. error++
  2082. queryData = append(queryData, outentry)
  2083. continue
  2084. }
  2085. a = ""
  2086. //校验数字格式
  2087. for _, v := range numParamslist {
  2088. if v == "" {
  2089. continue
  2090. }
  2091. d, ok := outentry[strings.Trim(v, " ")]
  2092. if !ok || d == "" {
  2093. outentry[strings.Trim(v, " ")] = 0
  2094. } else {
  2095. var fl float64
  2096. switch d.(type) {
  2097. case string:
  2098. fl, err = strconv.ParseFloat(d.(string), 64)
  2099. }
  2100. if err != nil || fl < 0 {
  2101. a = strings.Trim(v, " ")
  2102. break
  2103. }
  2104. }
  2105. }
  2106. if a != "" {
  2107. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2108. error++
  2109. queryData = append(queryData, outentry)
  2110. continue
  2111. }
  2112. tx := restful.Engine.NewSession()
  2113. err := tx.Begin()
  2114. for _, sqlnamestr := range sqlslist {
  2115. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2116. paramslist := strings.Split(paramslists, ",")
  2117. if len(paramslist) > 0 {
  2118. s_params := make([]interface{}, 0)
  2119. for _, value := range paramslist {
  2120. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2121. if tempv, exists := c.Get("jwt_username"); exists {
  2122. s_params = append(s_params, tempv.(string))
  2123. } else {
  2124. s_params = append(s_params, "")
  2125. }
  2126. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2127. s_params = append(s_params, pastureid)
  2128. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2129. ids, err := setting.SnowIds.NextId()
  2130. if err != nil {
  2131. ids = time.Now().UnixNano()
  2132. logging.Info("create SnowIds err", err)
  2133. }
  2134. s_params = append(s_params, ids)
  2135. } else {
  2136. if outentry[strings.Trim(value, " ")] == nil {
  2137. s_params = append(s_params, "")
  2138. } else {
  2139. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2140. }
  2141. }
  2142. }
  2143. outentry["input"] = inputdata
  2144. fmt.Println(sql, s_params)
  2145. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2146. if err != nil {
  2147. if tx != nil {
  2148. tx.Rollback()
  2149. }
  2150. if tx != nil {
  2151. tx.Close()
  2152. }
  2153. msg := geterrmsg(err.Error())
  2154. outentry["error_msg"] = msg
  2155. error++
  2156. queryData = append(queryData, outentry)
  2157. isdone = true
  2158. break
  2159. } else {
  2160. if len(returnmsgmap1) > 0 {
  2161. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2162. if tx != nil {
  2163. tx.Rollback()
  2164. }
  2165. if tx != nil {
  2166. tx.Close()
  2167. }
  2168. msg := geterrmsg(va.(string))
  2169. outentry["error_msg"] = msg
  2170. error++
  2171. queryData = append(queryData, outentry)
  2172. isdone = true
  2173. break
  2174. }
  2175. }
  2176. isdone = false
  2177. }
  2178. }
  2179. }
  2180. switch {
  2181. case err != nil:
  2182. if tx != nil {
  2183. tx.Rollback()
  2184. }
  2185. default:
  2186. if tx != nil {
  2187. err = tx.Commit()
  2188. }
  2189. }
  2190. if tx != nil {
  2191. tx.Close()
  2192. }
  2193. }
  2194. if !isdone {
  2195. ok++
  2196. isdone = true
  2197. }
  2198. }
  2199. data := make(map[string]interface{})
  2200. data["result"] = queryData
  2201. data["success"] = ok
  2202. data["err_count"] = error
  2203. appG.Response(http.StatusOK, e.SUCCESS, data)
  2204. }
  2205. func TransfTime(timestr string) (string, error) {
  2206. if timestr == "" {
  2207. return time.Now().Format("2006-01-02"), nil
  2208. }
  2209. days, err := strconv.Atoi(timestr)
  2210. if err != nil {
  2211. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2212. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2213. }
  2214. _, err := time.Parse("2006-01-02", timestr)
  2215. if err != nil {
  2216. t, err := time.Parse("2006/01/02", timestr)
  2217. if err != nil {
  2218. t, err := time.Parse("2006.01.02", timestr)
  2219. if err != nil {
  2220. return "", err
  2221. } else {
  2222. return t.Format("2006-01-02"), nil
  2223. }
  2224. } else {
  2225. return t.Format("2006-01-02"), nil
  2226. }
  2227. } else {
  2228. return timestr, nil
  2229. }
  2230. }
  2231. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2232. times = times.AddDate(0, 0, days)
  2233. return times.Format("2006-01-02"), nil
  2234. }
  2235. func Createchart(c *gin.Context) {
  2236. appG := app.Gin{C: c}
  2237. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2238. fsion := gofasion.NewFasion(string(dataByte))
  2239. chart_name := fsion.Get("chart_name").ValueStr()
  2240. desc := fsion.Get("desc").ValueStr()
  2241. pastureid := fsion.Get("pastureid").ValueStr()
  2242. source_id := fsion.Get("source_id").ValueStr()
  2243. emp := fsion.Get("emp").ValueStr()
  2244. content := fsion.Get("content").Json()
  2245. var mapResult map[string]interface{}
  2246. err1 := json.Unmarshal([]byte(content), &mapResult)
  2247. if err1 != nil {
  2248. fmt.Println("JsonToMapDemo err: ", err1)
  2249. }
  2250. tx := restful.Engine.NewSession()
  2251. err := tx.Begin()
  2252. defer func() {
  2253. switch {
  2254. case err != nil:
  2255. logging.Error("tx.Begin 事务启动失败__error:", err)
  2256. if tx != nil {
  2257. tx.Rollback()
  2258. }
  2259. default:
  2260. if tx != nil {
  2261. err = tx.Commit()
  2262. }
  2263. }
  2264. if tx != nil {
  2265. tx.Close()
  2266. }
  2267. }()
  2268. ids, err := setting.SnowIds.NextId()
  2269. if err != nil {
  2270. ids = time.Now().UnixNano()
  2271. logging.Info("create SnowIds err", err)
  2272. }
  2273. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2274. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2275. if err != nil {
  2276. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2277. } else {
  2278. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2279. }
  2280. }
  2281. func Updatedashboard(c *gin.Context) {
  2282. appG := app.Gin{C: c}
  2283. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2284. fsion := gofasion.NewFasion(string(dataByte))
  2285. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2286. pastureid := fsion.Get("pastureid").ValueStr()
  2287. content := fsion.Get("content").Json()
  2288. var mapResult map[string]interface{}
  2289. err1 := json.Unmarshal([]byte(content), &mapResult)
  2290. if err1 != nil {
  2291. fmt.Println("JsonToMapDemo err: ", err1)
  2292. }
  2293. layout := mapResult["layout"]
  2294. tx := restful.Engine.NewSession()
  2295. err := tx.Begin()
  2296. defer func() {
  2297. switch {
  2298. case err != nil:
  2299. logging.Error("tx.Begin 事务启动失败__error:", err)
  2300. if tx != nil {
  2301. tx.Rollback()
  2302. }
  2303. default:
  2304. if tx != nil {
  2305. err = tx.Commit()
  2306. }
  2307. }
  2308. if tx != nil {
  2309. tx.Close()
  2310. }
  2311. }()
  2312. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2313. if err != nil {
  2314. println("2", err.Error())
  2315. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2316. } else {
  2317. if exec != nil {
  2318. if exec[0]["content"] == nil {
  2319. mapR := make(map[string]interface{})
  2320. mapR["layout"] = layout
  2321. mjson, _ := json.Marshal(mapR)
  2322. mString := string(mjson)
  2323. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2324. if err3 != nil {
  2325. println("3", err3.Error())
  2326. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2327. } else {
  2328. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2329. }
  2330. } else {
  2331. var mapR map[string]interface{}
  2332. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2333. if err1 != nil {
  2334. fmt.Println("JsonToMapDemo err: ", err2)
  2335. }
  2336. mapR["layout"] = layout
  2337. mjson, _ := json.Marshal(mapR)
  2338. mString := string(mjson)
  2339. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2340. if err3 != nil {
  2341. println("3", err3.Error())
  2342. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2343. } else {
  2344. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2345. }
  2346. }
  2347. } else {
  2348. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2349. }
  2350. }
  2351. }
  2352. func ExecSQL(c *gin.Context) {
  2353. appG := app.Gin{C: c}
  2354. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2355. fsion := gofasion.NewFasion(string(dataByte))
  2356. content := fsion.Get("content").Json()
  2357. pastureid := fsion.Get("pastureid").ValueStr()
  2358. var mapResult map[string]interface{}
  2359. err1 := json.Unmarshal([]byte(content), &mapResult)
  2360. if err1 != nil {
  2361. fmt.Println("JsonToMapDemo err: ", err1)
  2362. }
  2363. sqlstr := "select "
  2364. groupstr := " GROUP BY "
  2365. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2366. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2367. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2368. }
  2369. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2370. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2371. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2372. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2373. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2374. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2375. sqlstr = sqlstr + tem + ","
  2376. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2377. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2378. sqlstr = sqlstr + tem + ","
  2379. } else {
  2380. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2381. sqlstr = sqlstr + tem + ","
  2382. }
  2383. }
  2384. if _, ok := mapResult["selectedCalcul2"]; ok {
  2385. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2386. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2387. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2388. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2389. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2390. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2391. sqlstr = sqlstr + tem + ","
  2392. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2393. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2394. sqlstr = sqlstr + tem + ","
  2395. } else {
  2396. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2397. sqlstr = sqlstr + tem + ","
  2398. }
  2399. }
  2400. }
  2401. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2402. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2403. sqlstr = sqlstr + " where pastureid=" + pastureid
  2404. if len(mapResult["filters"].([]interface{})) > 0 {
  2405. sqlstr = sqlstr + " and "
  2406. }
  2407. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2408. for _, value := range mapResult["filters"].([]interface{}) {
  2409. switch value.(map[string]interface{})["filterOperator"].(string) {
  2410. case ">", "=", "<", ">=", "<=", "!=", "like":
  2411. 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 "
  2412. case "IN":
  2413. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2414. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2415. sqlstr = sqlstr + value1.(string) + ","
  2416. }
  2417. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2418. sqlstr = sqlstr + ")" + " AND "
  2419. case "BETWEEN":
  2420. 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 "
  2421. }
  2422. }
  2423. if len(mapResult["filters"].([]interface{})) > 0 {
  2424. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2425. }
  2426. //
  2427. groupstr = groupstr[0 : len(groupstr)-1]
  2428. sqlstr = sqlstr + groupstr + " "
  2429. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2430. sqlstr = sqlstr + " order by "
  2431. }
  2432. //
  2433. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2434. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2435. sqlstr = sqlstr + value.(string) + " "
  2436. } else {
  2437. sqlstr = sqlstr + value.(string) + ","
  2438. }
  2439. }
  2440. //
  2441. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2442. tx := restful.Engine.NewSession()
  2443. err := tx.Begin()
  2444. defer func() {
  2445. switch {
  2446. case err != nil:
  2447. logging.Error("tx.Begin 事务启动失败__error:", err)
  2448. if tx != nil {
  2449. tx.Rollback()
  2450. }
  2451. default:
  2452. if tx != nil {
  2453. err = tx.Commit()
  2454. }
  2455. }
  2456. if tx != nil {
  2457. tx.Close()
  2458. }
  2459. }()
  2460. exec, err := tx.SQL(sqlstr).Query().List()
  2461. if err != nil {
  2462. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2463. } else {
  2464. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2465. }
  2466. }
  2467. func Dashboards(c *gin.Context) {
  2468. appG := app.Gin{C: c}
  2469. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2470. fsion := gofasion.NewFasion(string(dataByte))
  2471. sqlnamestr := fsion.Get("name").ValueStr()
  2472. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2473. offset := fsion.Get("offset").ValueDefaultInt(0)
  2474. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2475. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2476. month := fsion.Get("month").ValueDefaultStr("map")
  2477. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2478. tx := restful.Engine.NewSession()
  2479. err := tx.Begin()
  2480. defer func() {
  2481. switch {
  2482. case err != nil:
  2483. if tx != nil {
  2484. tx.Rollback()
  2485. }
  2486. default:
  2487. if tx != nil {
  2488. err = tx.Commit()
  2489. }
  2490. }
  2491. if tx != nil {
  2492. tx.Close()
  2493. }
  2494. }()
  2495. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2496. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2497. if sql != "" {
  2498. s_params := make([]interface{}, 0)
  2499. if fsion.HasKey("parammaps") {
  2500. parammaps := fsion.Get("parammaps")
  2501. paramslist := strings.Split(p, ",")
  2502. if len(paramslist) > 0 && p != "" {
  2503. for _, value := range paramslist {
  2504. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2505. if tempv, exists := c.Get("jwt_username"); exists {
  2506. s_params = append(s_params, tempv.(string))
  2507. } else {
  2508. s_params = append(s_params, "")
  2509. }
  2510. } else {
  2511. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2512. }
  2513. }
  2514. }
  2515. }
  2516. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2517. if err != nil {
  2518. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2519. } else {
  2520. //paramslist1 := strings.Split(p1, ",")
  2521. dids := make([]interface{}, 0)
  2522. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2523. var mapResult map[string]interface{}
  2524. dids = append(dids, value["dashboard_id"])
  2525. if value["content"] != nil {
  2526. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2527. if err1 != nil {
  2528. println("JsonToMapDemo1 err: ", err1)
  2529. }
  2530. temap := make(map[string]interface{})
  2531. tem := mapResult["layout"].([]interface{})
  2532. if v, ok := value["chartids"]; ok {
  2533. chartids := strings.Split(v.(string), ",")
  2534. for _, va := range chartids {
  2535. a := false
  2536. for _, v2 := range tem {
  2537. if v2.(map[string]interface{})["id"].(string) == va {
  2538. a = true
  2539. //println("va1======",va)
  2540. }
  2541. }
  2542. if !a {
  2543. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2544. va + "\",\"id\":\"" + va +
  2545. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2546. var mapTem map[string]interface{}
  2547. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2548. if err1 != nil {
  2549. println("JsonToMapDemo err: ", err1)
  2550. }
  2551. tem = append(tem, mapTem)
  2552. }
  2553. }
  2554. temap["layout"] = tem
  2555. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2556. }
  2557. } else {
  2558. temap := make(map[string]interface{})
  2559. tem := make([]interface{}, 0)
  2560. if v, ok := value["chartids"]; ok {
  2561. chartids := strings.Split(v.(string), ",")
  2562. for _, va := range chartids {
  2563. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2564. va + "\",\"id\":\"" + va +
  2565. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2566. var mapTem map[string]interface{}
  2567. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2568. if err1 != nil {
  2569. println("JsonToMapDemo err: ", err1)
  2570. }
  2571. tem = append(tem, mapTem)
  2572. }
  2573. temap["layout"] = tem
  2574. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2575. }
  2576. }
  2577. }
  2578. queryData.(map[string]interface{})["order"] = dids
  2579. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2580. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2581. }
  2582. } else {
  2583. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2584. }
  2585. }
  2586. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2587. fsion := gofasion.NewFasion(parammaps)
  2588. sqlnamestr := fsion.Get("name").ValueStr()
  2589. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2590. offset := fsion.Get("offset").ValueDefaultInt(0)
  2591. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2592. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2593. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2594. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2595. body := []byte("")
  2596. if sql != "" {
  2597. s_params := make([]interface{}, 0)
  2598. if fsion.HasKey("parammaps") {
  2599. parammaps := fsion.Get("parammaps")
  2600. paramslist := strings.Split(p, ",")
  2601. if len(paramslist) > 0 && p != "" {
  2602. for _, value := range paramslist {
  2603. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2604. }
  2605. }
  2606. }
  2607. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2608. if err != nil {
  2609. } else {
  2610. paramslist1 := strings.Split(p1, ",")
  2611. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2612. s_params1 := make([]interface{}, 0)
  2613. if len(paramslist1) > 0 && p1 != "" {
  2614. for _, v := range paramslist1 {
  2615. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2616. }
  2617. }
  2618. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2619. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2620. body, _ = json.Marshal(queryData)
  2621. }
  2622. }
  2623. }
  2624. bs := bytes.NewBuffer(body)
  2625. client := &http.Client{}
  2626. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2627. req, err := http.NewRequest(RequestMethod,
  2628. url,
  2629. bs,
  2630. )
  2631. if err != nil {
  2632. }
  2633. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2634. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2635. if err != nil {
  2636. // handle error
  2637. }
  2638. resp, err := client.Do(req)
  2639. if err != nil {
  2640. return ""
  2641. }
  2642. defer resp.Body.Close()
  2643. result_body, err := ioutil.ReadAll(resp.Body)
  2644. if err != nil {
  2645. return ""
  2646. }
  2647. fmt.Println(string(result_body))
  2648. return ""
  2649. }
  2650. func GetSummary(c *gin.Context) {
  2651. appG := app.Gin{C: c}
  2652. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2653. fsion := gofasion.NewFasion(string(dataByte))
  2654. offset := fsion.Get("offset").ValueDefaultInt(0)
  2655. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2656. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2657. parammaps := fsion.Get("parammaps")
  2658. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2659. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2660. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2661. tx := restful.Engine.NewSession()
  2662. defer tx.Close()
  2663. sqlnamestr := ""
  2664. if genre == "0" {
  2665. if status == "0" {
  2666. sqlnamestr = "getAccuracyJSY"
  2667. } else if status == "1" {
  2668. sqlnamestr = "getAccuracyHFT"
  2669. } else if status == "2" {
  2670. sqlnamestr = "getAccuracyHNS"
  2671. } else if status == "3" {
  2672. sqlnamestr = "getAccuracyHSC"
  2673. } else if status == "4" {
  2674. sqlnamestr = "getAccuracyHCC"
  2675. } else if status == "5" {
  2676. sqlnamestr = "getAccuracyMC"
  2677. }
  2678. } else {
  2679. if status == "0" {
  2680. sqlnamestr = "getAccuracySCCJSY"
  2681. } else if status == "1" {
  2682. sqlnamestr = "getAccuracySFT"
  2683. } else if status == "2" {
  2684. sqlnamestr = "getAccuracySNS"
  2685. } else if status == "3" {
  2686. sqlnamestr = "getAccuracySSC"
  2687. } else if status == "4" {
  2688. sqlnamestr = "getAccuracySCC"
  2689. } else if status == "5" {
  2690. sqlnamestr = "getAccuracySLCL"
  2691. }
  2692. }
  2693. if isDate == "1" {
  2694. sqlnamestr += "Date"
  2695. }
  2696. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2697. // fmt.Println(sqlnamestr, sql)
  2698. if sql != "" {
  2699. s_params := make([]interface{}, 0)
  2700. // if fsion.HasKey("parammaps") {
  2701. fmt.Println(s_params, "222", p)
  2702. paramslist := strings.Split(p, ",")
  2703. if len(paramslist) > 0 && p != "" {
  2704. for _, value := range paramslist {
  2705. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2706. if tempv, exists := c.Get("jwt_username"); exists {
  2707. s_params = append(s_params, tempv.(string))
  2708. } else {
  2709. s_params = append(s_params, "")
  2710. }
  2711. } else {
  2712. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2713. }
  2714. }
  2715. }
  2716. fmt.Println(s_params, "111")
  2717. if returntype == "xlsx" {
  2718. var xlsxfile *xlsx.File
  2719. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2720. //c.File("c:/dd.xlsx")
  2721. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2722. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2723. c.Header("Content-Transfer-Encoding", "binary")
  2724. _ = xlsxfile.Write(c.Writer)
  2725. } else {
  2726. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2727. if err != nil {
  2728. logging.Error("GetDataByName err: ", err)
  2729. msg := geterrmsg(err.Error())
  2730. appG.Response(http.StatusOK, e.ERROR, msg)
  2731. } else {
  2732. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2733. }
  2734. }
  2735. } else {
  2736. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2737. }
  2738. }
  2739. // type lpplanStruct struct {
  2740. // Id int64 `xorm:"id"`
  2741. // Tmrname string `xorm:"tmrname"`
  2742. // Tmrid int64 `xorm:"tmrid"`
  2743. // Sort int64 `xorm:"sort"`
  2744. // Sel int64 `xorm:"sel"`
  2745. // Times int64 `xorm:"times"`
  2746. // Ftname string `xorm:"ftname"`
  2747. // Ftid int64 `xorm:"ftid"`
  2748. // Maxweight float64 `xorm:"maxweight"`
  2749. // Sumweight float64 `xorm:"sumweight"`
  2750. // Sumcowcount int64 `xorm:"sumcowcount"`
  2751. // Pastureid string `xorm:"pastureid"`
  2752. // Display string `xorm:"display"`
  2753. // Issplit int64 `xorm:"issplit"`
  2754. // BeginTime string `xorm:"begintime"`
  2755. // }
  2756. func UpdateFTdetail(c *gin.Context) {
  2757. fmt.Println(time.Now())
  2758. appG := app.Gin{C: c}
  2759. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2760. tempval_ := make(map[string]interface{})
  2761. tempCommon := make(map[string]interface{})
  2762. tempval := make([]map[string]interface{}, 0)
  2763. fTChange := make(map[string]interface{}, 0)
  2764. fpdOldDataList := make([]map[string]interface{}, 0)
  2765. fpdDataList := make([]map[string]interface{}, 0)
  2766. err := json.Unmarshal(dataByte, &tempval_)
  2767. if err != nil {
  2768. appG.Response(http.StatusOK, e.ERROR, false)
  2769. return
  2770. }
  2771. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2772. tx := restful.Engine.NewSession()
  2773. err = tx.Begin()
  2774. if err != nil {
  2775. logging.Error("tx.Begin 事务启动失败__error:", err)
  2776. }
  2777. defer func() {
  2778. if err != nil {
  2779. if tx != nil {
  2780. tx.Rollback()
  2781. }
  2782. }
  2783. if tx != nil {
  2784. tx.Close()
  2785. }
  2786. }()
  2787. if err != nil {
  2788. } else {
  2789. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2790. tempCommon = v
  2791. }
  2792. if v, ok := tempval_["data"].([]interface{}); ok {
  2793. for _, Tvalue := range v {
  2794. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2795. if v1["name"] == "updateFPbyFTChange" {
  2796. fTChange = v1
  2797. continue
  2798. }
  2799. tempval = append(tempval, v1)
  2800. }
  2801. }
  2802. }
  2803. parammaps := fTChange["parammaps"].(map[string]interface{})
  2804. 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 ,
  2805. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2806. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2807. UNION
  2808. 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 ,
  2809. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2810. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2811. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2812. if err == nil {
  2813. if tempv, exists := c.Get("jwt_username"); exists {
  2814. tempCommon["jwt_username"] = tempv.(string)
  2815. }
  2816. for _, paramvalue := range tempval {
  2817. if _, ok := paramvalue["resultname"]; !ok {
  2818. paramvalue["resultname"] = paramvalue["name"]
  2819. }
  2820. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2821. if err != nil {
  2822. logging.Error("ExecDataParam error:", err)
  2823. break
  2824. }
  2825. }
  2826. if err != nil {
  2827. msg := geterrmsg(err.Error())
  2828. appG.Response(http.StatusOK, e.ERROR, msg)
  2829. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2830. }
  2831. }
  2832. }
  2833. tx.Commit()
  2834. // go func() {
  2835. if fTChange != nil {
  2836. parammaps := fTChange["parammaps"].(map[string]interface{})
  2837. if parammaps["type"].(float64) == 1 {
  2838. _, err = tx.SQL(`UPDATE feedp fp
  2839. set
  2840. fp.ftweight= IFNULL(IF(
  2841. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2842. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2843. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2844. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2845. ),0),fp.feedweight = IFNULL(IF(
  2846. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2847. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2848. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2849. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2850. ),0) +ifnull(fp.supplyweight,0)
  2851. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2852. _, err = tx.SQL(`UPDATE fpdetail fpd
  2853. INNER JOIN feedp fp
  2854. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2855. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2856. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2857. } else {
  2858. _, err = tx.SQL(`UPDATE feedp fp
  2859. SET
  2860. fp.supplyweight= IFNULL(IF(
  2861. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2862. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2863. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2864. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2865. ),0),fp.feedweight = IFNULL(IF(
  2866. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2867. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2868. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2869. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2870. ),0) +ifnull(fp.supplyweight,0)
  2871. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2872. _, err = tx.SQL(`UPDATE fpdetail fpd
  2873. INNER JOIN feedp fp
  2874. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2875. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2876. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2877. }
  2878. 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 ,
  2879. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2880. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2881. UNION
  2882. 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 ,
  2883. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2884. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2885. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2886. lpplanList := make([]*lpplanStruct, 0)
  2887. err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2888. if err != nil {
  2889. logs.Error(err, 1)
  2890. return
  2891. }
  2892. lppidlist := []string{}
  2893. for _, lpp := range lpplanList {
  2894. lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2895. }
  2896. lpplandtl1AllList := make([]*lpplandtl1, 0)
  2897. err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  2898. order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  2899. if err != nil {
  2900. // tx.Rollback()
  2901. logs.Error(err, 2, parammaps["pastureid"])
  2902. return
  2903. }
  2904. var wg sync.WaitGroup
  2905. for _, old := range fpdOldDataList {
  2906. for _, fpd := range fpdDataList {
  2907. wg.Add(1)
  2908. go func(old, fpd map[string]interface{}) {
  2909. updateLppandList := make([]*lpplandtl1, 0)
  2910. defer wg.Done()
  2911. // fmt.Println(old, i)
  2912. // fmt.Println(fpd, i)
  2913. if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  2914. fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  2915. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  2916. oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  2917. var w float64
  2918. var status int
  2919. if weight < oldweight {
  2920. if weight >= 0 {
  2921. return
  2922. }
  2923. w = weight
  2924. status = 0
  2925. } else {
  2926. if oldweight > 0 {
  2927. return
  2928. }
  2929. w = weight
  2930. status = 1
  2931. }
  2932. // fweight = w
  2933. for _, lpp := range lpplanList {
  2934. var fweight float64
  2935. var lweight float64
  2936. lpplandtl1List := make([]*lpplandtl1, 0)
  2937. for _, lppland := range lpplandtl1AllList {
  2938. if lppland.Lppid == lpp.Id {
  2939. lpplandtl1List = append(lpplandtl1List, lppland)
  2940. }
  2941. }
  2942. // err = tx.SQL(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid = ?
  2943. // order by sort desc`, parammaps["pastureid"], lpp.Id).Find(&lpplandtl1List)
  2944. // if err != nil {
  2945. // tx.Rollback()
  2946. // logs.Error(err, 2, parammaps["pastureid"], lpp.Id)
  2947. // return
  2948. // }
  2949. for _, lppland := range lpplandtl1List {
  2950. lweight += lppland.Lweight
  2951. }
  2952. if status == 0 {
  2953. if lweight <= 0 {
  2954. continue
  2955. }
  2956. } else {
  2957. if lpp.Maxweight <= lweight {
  2958. continue
  2959. }
  2960. }
  2961. for _, lppland := range lpplandtl1List {
  2962. fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  2963. if fpdid == lppland.Fpdid {
  2964. if status == 1 {
  2965. // if w <= lppland.Lweight {
  2966. if lpp.Maxweight <= lweight {
  2967. continue
  2968. }
  2969. if w+lweight <= lpp.Maxweight {
  2970. lppland.Lweight += w
  2971. lweight += w
  2972. fweight += w
  2973. w = 0
  2974. } else {
  2975. // if w < lpp.Maxweight-lppland.Lweight {
  2976. // // w = w - (lpp.Maxweight - lweight)
  2977. // lppland.Lweight = lppland.Lweight + w
  2978. // // lweight += (lpp.Maxweight - lweight)
  2979. // }
  2980. w = w - (lpp.Maxweight - lweight)
  2981. n := (lpp.Maxweight - lweight)
  2982. lppland.Lweight = lppland.Lweight + n
  2983. lweight += n
  2984. fweight += n
  2985. }
  2986. } else {
  2987. if lppland.Lweight == 0 {
  2988. continue
  2989. }
  2990. if w+lppland.Lweight >= 0 {
  2991. lppland.Lweight = lppland.Lweight + w
  2992. lweight = lweight + w
  2993. fweight = fweight + w
  2994. w = 0
  2995. } else {
  2996. w = w + lppland.Lweight
  2997. lweight = lweight - lppland.Lweight
  2998. fweight = fweight - lppland.Lweight
  2999. lppland.Lweight = 0
  3000. }
  3001. }
  3002. // go func(parammaps map[string]interface{}, lppland *lpplandtl1, status int) {
  3003. updateLppandList = append(updateLppandList, lppland)
  3004. // tx.Begin()
  3005. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3006. // _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3007. // if err != nil {
  3008. // fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3009. // // tx.Rollback()
  3010. // logs.Error(err, 3)
  3011. // return
  3012. // }
  3013. // // tx.Commit()
  3014. // }(parammaps, lppland, status)
  3015. break
  3016. }
  3017. }
  3018. // go func(parammaps map[string]interface{}, fweight float64, status int) {
  3019. // tx.Begin()
  3020. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3021. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3022. WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3023. if err != nil {
  3024. // tx.Rollback()
  3025. logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3026. return
  3027. }
  3028. // var wg sync.WaitGroup
  3029. // wg.Add(len(updateLppandList))
  3030. // go func(parammaps map[string]interface{}, updateLppandList []*lpplandtl1, status int) {
  3031. for _, lppland := range updateLppandList {
  3032. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3033. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3034. if err != nil {
  3035. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3036. // tx.Rollback()
  3037. logs.Error(err, 3)
  3038. return
  3039. }
  3040. // defer wg.Done()
  3041. }
  3042. updateLppandList = []*lpplandtl1{}
  3043. // }(parammaps, updateLppandList, status)
  3044. // wg.Wait()
  3045. // tx.Commit()
  3046. // }(parammaps, fweight, status)
  3047. if w == 0 {
  3048. break
  3049. }
  3050. }
  3051. // if weight < oldweight {
  3052. // fmt.Println("下调")
  3053. // } else {
  3054. // fmt.Println("上调")
  3055. // }
  3056. // break
  3057. }
  3058. }(old, fpd)
  3059. }
  3060. }
  3061. wg.Wait()
  3062. }
  3063. // }()
  3064. fmt.Println(time.Now())
  3065. appG.Response(http.StatusOK, e.SUCCESS, true)
  3066. }
  3067. type lpplandtlInfo struct {
  3068. Id int64 `xorm:"id"`
  3069. Pastureid int64 `xorm:"pastureid"`
  3070. Lppid int64 `xorm:"lppid"`
  3071. Barid int64 `xorm:"barid"`
  3072. Barname string `xorm:"barname"`
  3073. Fpdid int64 `xorm:"fpdid"`
  3074. Fttype int64 `xorm:"fttype"`
  3075. Lweight float64 `xorm:"lweight"`
  3076. Sort int64 `xorm:"sort"`
  3077. Tmrid int64 `xorm:"tmrid"`
  3078. Tmrname string `xorm:"tmrname"`
  3079. Cowcount int64 `xorm:"cowcount"`
  3080. Ccountradio float64 `xorm:"ccountradio"`
  3081. Background string `xorm:"background"`
  3082. Lweighthis float64 `xorm:"lweighthis"`
  3083. Maxweight float64 `xorm:"maxweight"`
  3084. }
  3085. func UpdateFpdetailBar(c *gin.Context) {
  3086. appG := app.Gin{C: c}
  3087. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3088. fsion := gofasion.NewFasion(string(dataByte))
  3089. pastureid := fsion.Get("pastureid").ValueStr()
  3090. id := fsion.Get("id").ValueStr()
  3091. tx := restful.Engine.NewSession()
  3092. tx.Begin()
  3093. for _, list := range fsion.Get("data").Array() {
  3094. ftmap := make(map[string]interface{})
  3095. ftmap["old"] = list.Get("old").ValueFloat64()
  3096. ftmap["new"] = list.Get("new").ValueFloat64()
  3097. ftmap["times"] = list.Get("times").ValueInt64()
  3098. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3099. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3100. // fmt.Println(ftmap)
  3101. 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 ,
  3102. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  3103. WHERE fpdetail.pastureid = ? and barid = ? and times = ?
  3104. UNION
  3105. 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 ,
  3106. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3107. WHERE fpdetail.pastureid = ? and barid = ? and times = ? ) t
  3108. order by t.barname,t.times`, pastureid, id, ftmap["times"], pastureid, id, ftmap["times"]).Query().List()
  3109. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3110. if err != nil {
  3111. tx.Rollback()
  3112. logs.Error(err)
  3113. }
  3114. for _, fpd := range fpdDataList {
  3115. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  3116. fttype := -1
  3117. if ftmap["ptid"].(string) != "-1" {
  3118. fttype = 1
  3119. }
  3120. var fweight float64
  3121. var lweight float64
  3122. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3123. err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  3124. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  3125. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3126. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3127. if err != nil {
  3128. tx.Rollback()
  3129. logs.Error(err)
  3130. }
  3131. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3132. var w float64
  3133. var status int
  3134. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  3135. if weight >= 0 {
  3136. continue
  3137. }
  3138. w = weight
  3139. status = 0
  3140. } else {
  3141. if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  3142. continue
  3143. }
  3144. w = weight
  3145. status = 1
  3146. }
  3147. for _, lppland := range lpplandtl1List {
  3148. lweight += lppland.Lweight
  3149. }
  3150. for _, lppland := range lpplandtl1List {
  3151. if status == 1 {
  3152. // if w <= lppland.Lweight {
  3153. if lppland.Maxweight <= lweight {
  3154. continue
  3155. }
  3156. if w+lweight <= lppland.Maxweight {
  3157. lppland.Lweight += w
  3158. lweight += w
  3159. fweight += w
  3160. w = 0
  3161. } else {
  3162. w = w - (lppland.Maxweight - lweight)
  3163. n := (lppland.Maxweight - lweight)
  3164. lppland.Lweight = lppland.Lweight + n
  3165. lweight += n
  3166. fweight += n
  3167. }
  3168. } else {
  3169. if lppland.Lweight == 0 {
  3170. continue
  3171. }
  3172. if w+lppland.Lweight >= 0 {
  3173. lppland.Lweight = lppland.Lweight + w
  3174. lweight = lweight + w
  3175. fweight = fweight + w
  3176. w = 0
  3177. } else {
  3178. w = w + lppland.Lweight
  3179. lweight = lweight - lppland.Lweight
  3180. fweight = fweight - lppland.Lweight
  3181. lppland.Lweight = 0
  3182. }
  3183. }
  3184. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3185. if err != nil {
  3186. tx.Rollback()
  3187. logs.Error(err)
  3188. return
  3189. }
  3190. break
  3191. }
  3192. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3193. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3194. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3195. if err != nil {
  3196. tx.Rollback()
  3197. logs.Error(err)
  3198. }
  3199. if w == 0 {
  3200. break
  3201. }
  3202. }
  3203. }
  3204. }
  3205. tx.Commit()
  3206. appG.Response(http.StatusOK, e.SUCCESS, true)
  3207. }
  3208. func GetProcessAnalysis(c *gin.Context) {
  3209. appG := app.Gin{C: c}
  3210. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3211. fsion := gofasion.NewFasion(string(dataByte))
  3212. sqlnamestr := fsion.Get("name").ValueStr()
  3213. offset := fsion.Get("offset").ValueDefaultInt(0)
  3214. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3215. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3216. parammaps := fsion.Get("parammaps")
  3217. tx := restful.Engine.NewSession()
  3218. err := tx.Begin()
  3219. defer func() {
  3220. switch {
  3221. case err != nil:
  3222. logging.Error("tx.Begin 事务启动失败__error:", err)
  3223. if tx != nil {
  3224. tx.Rollback()
  3225. }
  3226. default:
  3227. if tx != nil {
  3228. err = tx.Commit()
  3229. }
  3230. }
  3231. if tx != nil {
  3232. tx.Close()
  3233. }
  3234. }()
  3235. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3236. s_params := make([]interface{}, 0)
  3237. paramslist := strings.Split(p, ",")
  3238. if len(paramslist) > 0 && p != "" {
  3239. for _, value := range paramslist {
  3240. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3241. if tempv, exists := c.Get("jwt_username"); exists {
  3242. s_params = append(s_params, tempv.(string))
  3243. } else {
  3244. s_params = append(s_params, "")
  3245. }
  3246. } else {
  3247. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3248. }
  3249. }
  3250. }
  3251. tmrtnameStr := ""
  3252. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3253. if len(tmrtnameStr) == 0 {
  3254. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3255. } else {
  3256. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3257. }
  3258. }
  3259. if len(tmrtnameStr) > 0 {
  3260. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3261. }
  3262. sql += " ORDER BY d.intime"
  3263. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3264. if err != nil {
  3265. logging.Error("GetDataByName err: ", err)
  3266. msg := geterrmsg(err.Error())
  3267. appG.Response(http.StatusOK, e.ERROR, msg)
  3268. } else {
  3269. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3270. }
  3271. }
  3272. func UpdateFeedtempletStatus(c *gin.Context) {
  3273. appG := app.Gin{C: c}
  3274. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3275. fsion := gofasion.NewFasion(string(dataByte))
  3276. parammaps := fsion.Get("parammaps")
  3277. tx := restful.Engine.NewSession()
  3278. tx.Begin()
  3279. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3280. if err != nil {
  3281. tx.Rollback()
  3282. logs.Error(err)
  3283. appG.Response(http.StatusOK, e.ERROR, err)
  3284. return
  3285. }
  3286. tx.Commit()
  3287. appG.Response(http.StatusOK, e.SUCCESS, true)
  3288. }
  3289. func AddFtdry(c *gin.Context) {
  3290. appG := app.Gin{C: c}
  3291. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3292. fsion := gofasion.NewFasion(string(dataByte))
  3293. sqlnamestr := fsion.Get("name").ValueStr()
  3294. s_params := make([]interface{}, 0)
  3295. tx := restful.Engine.NewSession()
  3296. err := tx.Begin()
  3297. defer func() {
  3298. switch {
  3299. case err != nil:
  3300. if tx != nil {
  3301. tx.Rollback()
  3302. }
  3303. default:
  3304. if tx != nil {
  3305. err = tx.Commit()
  3306. }
  3307. }
  3308. if tx != nil {
  3309. tx.Close()
  3310. }
  3311. }()
  3312. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3313. if sql != "" {
  3314. parammaps := fsion.Get("parammaps")
  3315. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3316. paramslist := strings.Split(p, ",")
  3317. if len(paramslist) > 0 && p != "" {
  3318. for _, value := range paramslist {
  3319. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3320. if tempv, exists := c.Get("jwt_username"); exists {
  3321. s_params = append(s_params, tempv.(string))
  3322. } else {
  3323. s_params = append(s_params, "")
  3324. }
  3325. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3326. ids, err := setting.SnowIds.NextId()
  3327. if err != nil {
  3328. ids = time.Now().UnixNano()
  3329. logging.Info("create SnowIds err", err)
  3330. }
  3331. s_params = append(s_params, ids)
  3332. } else {
  3333. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3334. }
  3335. }
  3336. }
  3337. var actweight float64
  3338. actweightList, err := tx.SQL(`select ROUND(avg(actweight),2) as actweight from ftdry
  3339. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3340. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3341. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3342. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3343. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3344. 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()
  3345. if err != nil {
  3346. logging.Error("AddFtdry err: ", err)
  3347. msg := geterrmsg(err.Error())
  3348. appG.Response(http.StatusOK, e.ERROR, msg)
  3349. }
  3350. if len(actweightList) > 0 {
  3351. for _, item := range actweightList {
  3352. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3353. if err != nil {
  3354. logging.Error("AddFtdry err: ", err)
  3355. msg := geterrmsg(err.Error())
  3356. appG.Response(http.StatusOK, e.ERROR, msg)
  3357. }
  3358. actweight = fl
  3359. }
  3360. } else {
  3361. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3362. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3363. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3364. if err != nil {
  3365. logging.Error("AddFtdry err: ", err)
  3366. msg := geterrmsg(err.Error())
  3367. appG.Response(http.StatusOK, e.ERROR, msg)
  3368. }
  3369. for _, item := range dryList {
  3370. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3371. if err != nil {
  3372. logging.Error("AddFtdry err: ", err)
  3373. msg := geterrmsg(err.Error())
  3374. appG.Response(http.StatusOK, e.ERROR, msg)
  3375. }
  3376. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3377. }
  3378. }
  3379. if sqlnamestr == "insertFtdry" {
  3380. s_params = append(s_params, actweight)
  3381. } else if sqlnamestr == "updateFtdry" {
  3382. sql = fmt.Sprintf(sql, actweight)
  3383. }
  3384. queryData, err := execDataBySqlT(sql, s_params, tx)
  3385. if err != nil {
  3386. logging.Error("AddFtdry err: ", err)
  3387. msg := geterrmsg(err.Error())
  3388. appG.Response(http.StatusOK, e.ERROR, msg)
  3389. } else {
  3390. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3391. }
  3392. } else {
  3393. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3394. }
  3395. }
  3396. func CheckDates(c *gin.Context) {
  3397. tx := restful.Engine.NewSession()
  3398. defer tx.Close()
  3399. appG := app.Gin{C: c}
  3400. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3401. tempval_ := make(map[string]interface{})
  3402. tempCommon := make(map[string]interface{})
  3403. tempval := make([]map[string]interface{}, 0)
  3404. err := json.Unmarshal(dataByte, &tempval_)
  3405. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3406. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3407. if err != nil {
  3408. } else {
  3409. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3410. tempCommon = v
  3411. }
  3412. if v, ok := tempval_["data"].([]interface{}); ok {
  3413. for _, Tvalue := range v {
  3414. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3415. tempval = append(tempval, v1)
  3416. }
  3417. }
  3418. }
  3419. if err == nil {
  3420. if tempv, exists := c.Get("jwt_username"); exists {
  3421. tempCommon["jwt_username"] = tempv.(string)
  3422. }
  3423. for _, paramvalue := range tempval {
  3424. if _, ok := paramvalue["resultname"]; !ok {
  3425. paramvalue["resultname"] = paramvalue["name"]
  3426. }
  3427. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3428. if err != nil {
  3429. logging.Error("ExecDataParam error:", err)
  3430. }
  3431. }
  3432. if err == nil {
  3433. vmsg := ""
  3434. for _, item := range tempval {
  3435. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3436. for _, childrenList := range list.([]interface{}) {
  3437. for k, children := range childrenList.(map[string]interface{}) {
  3438. if k != "children" {
  3439. continue
  3440. }
  3441. for _, v := range children.([]map[string]interface{}) {
  3442. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3443. if k1 == "list" {
  3444. for _, v2 := range v1.([]map[string]interface{}) {
  3445. if v2["vmsg"].(string) != "1" {
  3446. if len(vmsg) == 0 {
  3447. vmsg = v2["vmsg"].(string)
  3448. } else {
  3449. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3450. }
  3451. }
  3452. }
  3453. }
  3454. }
  3455. }
  3456. }
  3457. }
  3458. }
  3459. }
  3460. if len(vmsg) > 0 {
  3461. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3462. } else {
  3463. appG.Response(http.StatusOK, e.SUCCESS, true)
  3464. }
  3465. } else {
  3466. msg := geterrmsg(err.Error())
  3467. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3468. }
  3469. }
  3470. }
  3471. if err != nil {
  3472. msg := geterrmsg(err.Error())
  3473. appG.Response(http.StatusOK, e.ERROR, msg)
  3474. }
  3475. }
  3476. 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) {
  3477. sqlname := fasion["name"].(string)
  3478. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3479. if v, ok := fasion["type"]; ok {
  3480. sqltype = v.(string)
  3481. }
  3482. sql := ""
  3483. p := ""
  3484. s_params := make([]interface{}, 0)
  3485. if sqltype != "" {
  3486. sql, p = restful.GetSqlByName(sqlname, tx)
  3487. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3488. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3489. paramslist := strings.Split(p, ",")
  3490. if len(paramslist) > 0 && p != "" {
  3491. for _, value := range paramslist {
  3492. ss := ""
  3493. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3494. ids, err := setting.SnowIds.NextId()
  3495. if err != nil {
  3496. ids = time.Now().UnixNano()
  3497. logging.Info("create SnowIds err", err)
  3498. }
  3499. s_params = append(s_params, ids)
  3500. } else {
  3501. if ss == "" && CommonParamMap != nil {
  3502. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3503. ss = valuestring
  3504. tempstrb := strings.IndexAny(valuestring, "@")
  3505. tempstre := strings.IndexAny(valuestring, ".")
  3506. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3507. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3508. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3509. }
  3510. } else {
  3511. ss = ""
  3512. }
  3513. }
  3514. }
  3515. if ss == "" && ParentParamMap != nil {
  3516. ss = getParamValue_(v, value, ParentParamMap)
  3517. }
  3518. if ss == "" && sameParamMap != nil {
  3519. ss = getParamValue(v, value, sameParamMap)
  3520. }
  3521. if ss == "" && ParamMap != nil {
  3522. ss = getParamValue(v, value, ParamMap)
  3523. }
  3524. s_params = append(s_params, ss)
  3525. }
  3526. }
  3527. }
  3528. }
  3529. }
  3530. if sql == "" {
  3531. sqltype = ""
  3532. }
  3533. if sql != "" {
  3534. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3535. if err != nil {
  3536. return nil, err
  3537. }
  3538. // fmt.Println(tempValParam)
  3539. return tempValParam.(map[string]interface{}), nil
  3540. } else {
  3541. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3542. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3543. if err != nil {
  3544. return nil, err
  3545. }
  3546. return nil, err
  3547. }
  3548. }
  3549. return nil, nil
  3550. }
  3551. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3552. var err error
  3553. subarray, ok := fasion["children"]
  3554. if ok {
  3555. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3556. tempVal_arrary := make([]map[string]interface{}, 0)
  3557. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3558. tempVal_ := make(map[string]interface{})
  3559. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3560. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3561. } else {
  3562. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3563. }
  3564. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3565. if err != nil {
  3566. return err
  3567. }
  3568. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3569. }
  3570. v.(map[string]interface{})["children"] = tempVal_arrary
  3571. }
  3572. }
  3573. return nil
  3574. }
  3575. func FpdImportExcel(c *gin.Context) {
  3576. appG := app.Gin{C: c}
  3577. inputdata := ""
  3578. c.Request.ParseForm()
  3579. params := c.Request.Form
  3580. file, _, err := c.Request.FormFile("file")
  3581. if err != nil {
  3582. appG.Response(http.StatusOK, e.ERROR, err)
  3583. return
  3584. }
  3585. sqlnamestrs := params.Get("name")
  3586. sheetname := params.Get("sheetname")
  3587. pastureid := params.Get("pastureid")
  3588. // importParams := params.Get("importParams")
  3589. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3590. // 必输项参数 (字符串格式 "field1,field2,field3")
  3591. requiredParams := params.Get("requiredParams")
  3592. // 日期参数
  3593. dateParams := params.Get("dateParams")
  3594. // 数字参数
  3595. numParams := params.Get("numParams")
  3596. //将字符串分割开
  3597. dateParamslist := strings.Split(dateParams, ",")
  3598. requiredParamslist := strings.Split(requiredParams, ",")
  3599. numParamslist := strings.Split(numParams, ",")
  3600. queryData := make([]interface{}, 0)
  3601. sqlslist := strings.Split(sqlnamestrs, ",")
  3602. xlsx1, err := excelize.OpenReader(file)
  3603. if err != nil {
  3604. fmt.Println(err)
  3605. return
  3606. }
  3607. ok := 0
  3608. error := 0
  3609. isdone := true
  3610. tx := restful.Engine.NewSession()
  3611. defer tx.Close()
  3612. 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
  3613. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3614. if err != nil {
  3615. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3616. return
  3617. }
  3618. for _, item := range oldFpdList {
  3619. fmt.Println(item)
  3620. }
  3621. rows, _ := xlsx1.GetRows(sheetname)
  3622. // 限制10000条,多余的截取掉
  3623. if len(rows) > 10000 {
  3624. rows = rows[:10000]
  3625. }
  3626. for i, row := range rows {
  3627. if i > 0 {
  3628. entry := make(map[string]interface{})
  3629. outentry := make(map[string]interface{})
  3630. for j, colCell := range rows[0] {
  3631. for k, colCell1 := range row {
  3632. if j == k {
  3633. outentry[colCell] = colCell1
  3634. entry[colCell] = colCell1
  3635. }
  3636. }
  3637. }
  3638. inputdata = ""
  3639. a := ""
  3640. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3641. //校验日期格式
  3642. for _, v := range dateParamslist {
  3643. if v == "" {
  3644. continue
  3645. }
  3646. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3647. dtime, err := TransfTime(d.(string))
  3648. if err != nil {
  3649. a = strings.Trim(v, " ")
  3650. break
  3651. }
  3652. outentry[strings.Trim(v, " ")] = dtime
  3653. }
  3654. }
  3655. if a != "" {
  3656. outentry["error_msg"] = a + " 格式错误"
  3657. error++
  3658. queryData = append(queryData, outentry)
  3659. continue
  3660. }
  3661. a = ""
  3662. //校验必填格式
  3663. for _, v := range requiredParamslist {
  3664. if v == "" {
  3665. continue
  3666. }
  3667. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3668. a = strings.Trim(v, " ")
  3669. break
  3670. }
  3671. }
  3672. if a != "" {
  3673. outentry["error_msg"] = a + " 未填或格式错误"
  3674. error++
  3675. queryData = append(queryData, outentry)
  3676. continue
  3677. }
  3678. a = ""
  3679. //校验数字格式
  3680. for _, v := range numParamslist {
  3681. if v == "" {
  3682. continue
  3683. }
  3684. d, ok := outentry[strings.Trim(v, " ")]
  3685. if !ok || d == "" {
  3686. outentry[strings.Trim(v, " ")] = 0
  3687. } else {
  3688. var fl float64
  3689. switch d.(type) {
  3690. case string:
  3691. fl, err = strconv.ParseFloat(d.(string), 64)
  3692. }
  3693. if err != nil || fl < 0 {
  3694. a = strings.Trim(v, " ")
  3695. break
  3696. }
  3697. }
  3698. }
  3699. if a != "" {
  3700. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3701. error++
  3702. queryData = append(queryData, outentry)
  3703. continue
  3704. }
  3705. errExist := false
  3706. for _, sqlnamestr := range sqlslist {
  3707. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3708. paramslist := strings.Split(paramslists, ",")
  3709. if len(paramslist) > 0 {
  3710. s_params := make([]interface{}, 0)
  3711. for _, value := range paramslist {
  3712. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3713. if tempv, exists := c.Get("jwt_username"); exists {
  3714. s_params = append(s_params, tempv.(string))
  3715. } else {
  3716. s_params = append(s_params, "")
  3717. }
  3718. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3719. s_params = append(s_params, pastureid)
  3720. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3721. ids, err := setting.SnowIds.NextId()
  3722. if err != nil {
  3723. ids = time.Now().UnixNano()
  3724. logging.Info("create SnowIds err", err)
  3725. }
  3726. s_params = append(s_params, ids)
  3727. } else {
  3728. if outentry[strings.Trim(value, " ")] == nil {
  3729. s_params = append(s_params, "")
  3730. } else {
  3731. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3732. }
  3733. }
  3734. }
  3735. outentry["input"] = inputdata
  3736. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3737. if err != nil {
  3738. errExist = true
  3739. // if tx != nil {
  3740. // tx.Rollback()
  3741. // }
  3742. // if tx != nil {
  3743. // tx.Close()
  3744. // }
  3745. msg := geterrmsg(err.Error())
  3746. outentry["error_msg"] = msg
  3747. error++
  3748. queryData = append(queryData, outentry)
  3749. isdone = true
  3750. break
  3751. } else {
  3752. if len(returnmsgmap1) > 0 {
  3753. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3754. // if tx != nil {
  3755. // tx.Rollback()
  3756. // }
  3757. // if tx != nil {
  3758. // tx.Close()
  3759. // }
  3760. msg := geterrmsg(va.(string))
  3761. outentry["error_msg"] = msg
  3762. error++
  3763. queryData = append(queryData, outentry)
  3764. isdone = true
  3765. break
  3766. }
  3767. }
  3768. isdone = false
  3769. }
  3770. }
  3771. }
  3772. if !errExist {
  3773. dataexcel := make(map[string]interface{}, 0)
  3774. if _, ok := outentry["栏舍名称"]; ok {
  3775. dataexcel["barname"] = outentry["栏舍名称"]
  3776. }
  3777. if _, ok := outentry["实际牛头数"]; ok {
  3778. dataexcel["ccount"] = outentry["实际牛头数"]
  3779. }
  3780. if _, ok := outentry["系数(%)"]; ok {
  3781. dataexcel["ratio"] = outentry["系数(%)"]
  3782. }
  3783. if _, ok := outentry["配方模板"]; ok {
  3784. dataexcel["ftname"] = outentry["配方模板"]
  3785. }
  3786. if _, ok := outentry["补料配方"]; ok {
  3787. dataexcel["ptsfname"] = outentry["补料配方"]
  3788. }
  3789. if _, ok := outentry["第一班比例(%)"]; ok {
  3790. dataexcel["1"] = outentry["第一班比例(%)"]
  3791. }
  3792. if _, ok := outentry["第二班比例(%)"]; ok {
  3793. dataexcel["2"] = outentry["第二班比例(%)"]
  3794. }
  3795. if _, ok := outentry["第三班比例(%)"]; ok {
  3796. dataexcel["3"] = outentry["第三班比例(%)"]
  3797. }
  3798. if _, ok := outentry["第四班比例(%)"]; ok {
  3799. dataexcel["4"] = outentry["第四班比例(%)"]
  3800. }
  3801. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3802. if err != nil {
  3803. logs.Error(err)
  3804. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3805. return
  3806. }
  3807. if !exist {
  3808. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  3809. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  3810. if err != nil {
  3811. logs.Error(err)
  3812. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3813. return
  3814. }
  3815. }
  3816. var feedpargs []interface{}
  3817. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  3818. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  3819. if _, ok := dataexcel["ftname"]; ok {
  3820. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  3821. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  3822. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  3823. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  3824. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  3825. } else {
  3826. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  3827. }
  3828. if _, ok := dataexcel["ptsfname"]; ok {
  3829. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  3830. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  3831. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  3832. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  3833. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  3834. } else {
  3835. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  3836. }
  3837. upFeedpSql += " where barname = ? and pastureid = ? "
  3838. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  3839. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  3840. if err != nil {
  3841. logs.Error(err)
  3842. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3843. return
  3844. }
  3845. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3846. if err != nil {
  3847. logs.Error(err)
  3848. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3849. return
  3850. }
  3851. if !exist1 {
  3852. _, 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) `,
  3853. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  3854. if err != nil {
  3855. logs.Error(err)
  3856. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3857. return
  3858. }
  3859. _, 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) `,
  3860. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  3861. if err != nil {
  3862. logs.Error(err)
  3863. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3864. return
  3865. }
  3866. _, 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) `,
  3867. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  3868. if err != nil {
  3869. logs.Error(err)
  3870. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3871. return
  3872. }
  3873. _, 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) `,
  3874. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  3875. if err != nil {
  3876. logs.Error(err)
  3877. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3878. return
  3879. }
  3880. }
  3881. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  3882. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  3883. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  3884. and pastureid = ? and times = ?`
  3885. var fpdargs1 []interface{}
  3886. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  3887. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  3888. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  3889. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  3890. if err != nil {
  3891. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3892. return
  3893. }
  3894. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  3895. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  3896. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  3897. // and pastureid = ? and times = ?`
  3898. var fpdargs2 []interface{}
  3899. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  3900. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  3901. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  3902. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  3903. if err != nil {
  3904. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3905. return
  3906. }
  3907. var fpdargs3 []interface{}
  3908. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  3909. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  3910. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  3911. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  3912. if err != nil {
  3913. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3914. return
  3915. }
  3916. var fpdargs4 []interface{}
  3917. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  3918. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  3919. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  3920. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  3921. if err != nil {
  3922. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3923. return
  3924. }
  3925. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  3926. 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()
  3927. if err != nil {
  3928. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3929. return
  3930. }
  3931. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  3932. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3933. upFpdetailList := make([]*upFpdetail, 0)
  3934. for _, newfpd := range newList {
  3935. for _, oldfpd := range oldFpdList {
  3936. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  3937. var oldweight, newweight float64
  3938. if oldfpd["weight"] != nil {
  3939. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  3940. }
  3941. if newfpd["weight"] != nil {
  3942. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  3943. }
  3944. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  3945. upFpdetailList = append(upFpdetailList, &upFpdetail{
  3946. Old: oldweight,
  3947. New: newweight,
  3948. Times: newfpd["times"].(int64),
  3949. Ptid: newfpd["ptid"].(int64),
  3950. Fweight: fweight,
  3951. Id: oldfpd["id"].(int64),
  3952. })
  3953. break
  3954. }
  3955. }
  3956. }
  3957. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  3958. }
  3959. }
  3960. if !isdone {
  3961. ok++
  3962. isdone = true
  3963. }
  3964. }
  3965. data := make(map[string]interface{})
  3966. data["result"] = queryData
  3967. data["success"] = ok
  3968. data["err_count"] = error
  3969. appG.Response(http.StatusOK, e.SUCCESS, data)
  3970. }
  3971. type upFpdetail struct {
  3972. Old float64
  3973. New float64
  3974. Times int64
  3975. Ptid int64
  3976. Fweight float64
  3977. Id int64
  3978. // Ptsid string
  3979. }
  3980. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  3981. tx := restful.Engine.NewSession()
  3982. defer tx.Close()
  3983. tx.Begin()
  3984. for _, data := range dataList {
  3985. // 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 ,
  3986. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  3987. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  3988. // UNION
  3989. // fpdDataList, err := tx.SQL(` select * from (
  3990. // 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 ,
  3991. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3992. // WHERE fpdetail.pastureid = ? and barname = ? and times = ? ) t
  3993. // order by t.barname,t.times`, pastureid, barname, data.Times).Query().List()
  3994. // if err != nil {
  3995. // tx.Rollback()
  3996. // logs.Error(err)
  3997. // }
  3998. // for _, fpd := range fpdDataList {
  3999. // ptid, err := strconv.ParseInt(fpd["ptid"].(string), 10, 64)
  4000. // if fpd["times"].(int64) == data.Times && (ptid == data.Ptid) {
  4001. fttype := -1
  4002. if data.Ptid != -1 {
  4003. fttype = 1
  4004. }
  4005. var fweight float64
  4006. var lweight float64
  4007. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4008. err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4009. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4010. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4011. data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  4012. if err != nil {
  4013. tx.Rollback()
  4014. logs.Error(err)
  4015. return err
  4016. }
  4017. weight := data.Fweight
  4018. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4019. var w float64
  4020. var status int
  4021. if data.New < data.Old {
  4022. if weight >= 0 {
  4023. continue
  4024. }
  4025. w = weight
  4026. status = 0
  4027. } else {
  4028. // if weight-(data.New-data.Old) > 0 {
  4029. // continue
  4030. // }
  4031. w = data.New - data.Old
  4032. status = 1
  4033. }
  4034. // if weight < oldweight {
  4035. // if weight >= 0 {
  4036. // return
  4037. // }
  4038. // w = weight
  4039. // status = 0
  4040. // } else {
  4041. // if oldweight > 0 {
  4042. // return
  4043. // }
  4044. // w = weight
  4045. // status = 1
  4046. // }
  4047. // for _, lppland := range lpplandtl1List {
  4048. // lweight += lppland.Lweight
  4049. // }
  4050. for _, lppland := range lpplandtl1List {
  4051. var lppdata lpplandtlInfo
  4052. tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  4053. lppland.Lppid, pastureid).GetFirst(&lppdata)
  4054. if err != nil {
  4055. tx.Rollback()
  4056. logs.Error(err)
  4057. return err
  4058. }
  4059. lweight = lppdata.Lweight
  4060. if status == 1 {
  4061. // if w <= lppland.Lweight {
  4062. if lppland.Maxweight <= lweight {
  4063. continue
  4064. }
  4065. if w+lweight <= lppland.Maxweight {
  4066. lppland.Lweight += w
  4067. lweight += w
  4068. fweight += w
  4069. w = 0
  4070. } else {
  4071. w = w - (lppland.Maxweight - lweight)
  4072. n := (lppland.Maxweight - lweight)
  4073. lppland.Lweight = lppland.Lweight + n
  4074. lweight += n
  4075. fweight += n
  4076. }
  4077. } else {
  4078. if lppland.Lweight == 0 {
  4079. continue
  4080. }
  4081. if w+lppland.Lweight >= 0 {
  4082. lppland.Lweight = lppland.Lweight + w
  4083. lweight = lweight + w
  4084. fweight = fweight + w
  4085. w = 0
  4086. } else {
  4087. w = w + lppland.Lweight
  4088. lweight = lweight - lppland.Lweight
  4089. fweight = fweight - lppland.Lweight
  4090. lppland.Lweight = 0
  4091. }
  4092. }
  4093. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4094. if err != nil {
  4095. tx.Rollback()
  4096. logs.Error(err)
  4097. return err
  4098. }
  4099. break
  4100. }
  4101. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4102. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4103. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  4104. if err != nil {
  4105. tx.Rollback()
  4106. logs.Error(err)
  4107. return err
  4108. }
  4109. // if w == 0 {
  4110. // break
  4111. // }
  4112. // }
  4113. }
  4114. err := tx.Commit()
  4115. if err != nil {
  4116. logs.Error(err)
  4117. tx.Rollback()
  4118. return err
  4119. }
  4120. return nil
  4121. }
  4122. func DeleteFTdetail(c *gin.Context) {
  4123. appG := app.Gin{C: c}
  4124. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4125. fsion := gofasion.NewFasion(string(dataByte))
  4126. parammaps := fsion.Get("parammaps")
  4127. pastureid := parammaps.Get("pastureid").ValueStr()
  4128. ftid := parammaps.Get("ftid").ValueStr()
  4129. tx := restful.Engine.NewSession()
  4130. defer tx.Close()
  4131. tx.Begin()
  4132. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  4133. if err != nil {
  4134. tx.Rollback()
  4135. logs.Error(err)
  4136. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4137. return
  4138. }
  4139. if parammaps.Get("type").ValueStr() == "1" {
  4140. _, err := tx.SQL(`UPDATE feedp fp
  4141. set
  4142. fp.ftweight= IFNULL(IF(
  4143. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4144. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4145. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4146. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4147. ),0),fp.feedweight = IFNULL(IF(
  4148. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4149. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4150. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4151. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4152. ),0) +ifnull(fp.supplyweight,0)
  4153. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4154. if err != nil {
  4155. tx.Rollback()
  4156. logs.Error(err)
  4157. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4158. return
  4159. }
  4160. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  4161. _, err = tx.SQL(`
  4162. UPDATE fpdetail fpd
  4163. INNER JOIN feedp fp
  4164. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4165. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4166. ptuse= 0
  4167. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4168. if err != nil {
  4169. tx.Rollback()
  4170. logs.Error(err)
  4171. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4172. return
  4173. }
  4174. } else {
  4175. _, err := tx.SQL(`UPDATE feedp fp
  4176. SET
  4177. fp.supplyweight= IFNULL(IF(
  4178. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4179. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4180. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4181. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4182. ),0),fp.feedweight = IFNULL(IF(
  4183. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4184. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4185. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4186. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4187. ),0) + ifnull(fp.supplyweight,0)
  4188. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4189. if err != nil {
  4190. tx.Rollback()
  4191. logs.Error(err)
  4192. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4193. return
  4194. }
  4195. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4196. _, err = tx.SQL(`
  4197. UPDATE fpdetail fpd
  4198. INNER JOIN feedp fp
  4199. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4200. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4201. ptsrate = 0
  4202. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4203. if err != nil {
  4204. tx.Rollback()
  4205. logs.Error(err)
  4206. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4207. return
  4208. }
  4209. }
  4210. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  4211. if err != nil {
  4212. tx.Rollback()
  4213. logs.Error(err)
  4214. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4215. return
  4216. }
  4217. err = tx.Commit()
  4218. if err != nil {
  4219. tx.Rollback()
  4220. logs.Error(err)
  4221. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4222. return
  4223. }
  4224. appG.Response(http.StatusOK, e.SUCCESS, true)
  4225. }