44e700a1301e77ea929f7137f8d7cb66d5e8b6ec.svn-base 124 KB

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