4c30cf855b9f0ec77095adbdeb6a2f1df326074c.svn-base 127 KB

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