e8376e37ea1c93cf051ccffa291b8a20719542b9.svn-base 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459
  1. package api
  2. import (
  3. "../../pkg/app"
  4. "../../pkg/e"
  5. "../../pkg/logging"
  6. "../../pkg/setting"
  7. "../../routers/restful"
  8. "database/sql"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "github.com/360EntSecGroup-Skylar/excelize"
  13. "github.com/Anderson-Lu/gofasion/gofasion"
  14. "github.com/Knetic/govaluate"
  15. "github.com/gin-gonic/gin"
  16. "github.com/tealeg/xlsx"
  17. "github.com/xormplus/xorm"
  18. "io/ioutil"
  19. "math"
  20. "net/http"
  21. "os"
  22. "path"
  23. "regexp"
  24. "sort"
  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. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  300. if err != nil {
  301. msgstr = errstr
  302. return
  303. }
  304. if msg == nil {
  305. var param []interface{}
  306. param = append(param, errstr, errstr)
  307. go func() {
  308. tx := restful.Engine.NewSession()
  309. err := tx.Begin()
  310. defer func() {
  311. switch {
  312. case err != nil:
  313. logging.Error("tx.Begin 事务启动失败__error:", err)
  314. if tx != nil {
  315. tx.Rollback()
  316. }
  317. default:
  318. if tx != nil {
  319. err = tx.Commit()
  320. }
  321. }
  322. if tx != nil {
  323. tx.Close()
  324. }
  325. }()
  326. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE msg=msg", param, tx)
  327. if err != nil {
  328. logging.Error("insert into err_msg(err,msg) err", err)
  329. }
  330. }()
  331. msgstr = errstr
  332. } else {
  333. msgstr = msg[0]["msg"]
  334. }
  335. return
  336. }
  337. // @Summary 根据APISQL表中SQL执行得到数据集
  338. // @Tags GetDataByNameForm
  339. // @Accept json
  340. // @Produce json
  341. // @Param sqlname body json true "sqlname"
  342. // @Param offset query int true "offset"
  343. // @Param pagecount query int true "pagecount"
  344. // @Param returntype query string true "returntype"
  345. // @Param s formData json true "ss"
  346. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  347. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  348. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  349. // @Router /data/GetDataByNameForm [POST]
  350. func GetDataByNameForm(c *gin.Context) {
  351. appG := app.Gin{C: c}
  352. //sqlnamestr := c.PostForm("measureNumber")
  353. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  354. //fsion := gofasion.NewFasion(string(dataByte))
  355. //sqlnamestr := fsion.Get("name").ValueStr()
  356. //offset := fsion.Get("offset").ValueInt()
  357. //pagecount := fsion.Get("pagecount").ValueInt()
  358. //returntype := fsion.Get("returntype").ValueStr()
  359. //params := fsion.Get("params").Array()
  360. c.Request.ParseForm()
  361. params := c.Request.Form
  362. offset := 0
  363. pageSize_ := 0
  364. returntype := params.Get("page")
  365. if returntype == "" {
  366. returntype = "0"
  367. }
  368. if tempv, exists := c.Get("jwt_username"); exists {
  369. params.Set("JwtUserName", tempv.(string))
  370. } else {
  371. params.Set("JwtUserName", "")
  372. }
  373. sqlnamestr := params.Get("name")
  374. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  375. s_params := make([]interface{}, 0)
  376. if returntype == "1" {
  377. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  378. if error != nil {
  379. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  380. }
  381. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  382. if error != nil {
  383. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  384. }
  385. pageSize_ = pageSize
  386. offset = pageNum
  387. }
  388. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  389. paramslist := strings.Split(p, ",")
  390. if len(paramslist) > 0 && p != "" {
  391. for _, value := range paramslist {
  392. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  393. }
  394. }
  395. if sql != "" {
  396. if returntype == "xlsx" {
  397. var xlsxfile *xlsx.File
  398. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  399. c.Header("Content-Type", "application/octet-stream")
  400. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  401. c.Header("Content-Transfer-Encoding", "binary")
  402. _ = xlsxfile.Write(c.Writer)
  403. } else {
  404. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  405. if err != nil {
  406. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  407. } else {
  408. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  409. }
  410. }
  411. } else {
  412. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  413. }
  414. }
  415. // @Summary 递归获取所有
  416. // @Tags menu
  417. // @Accept json
  418. // @Produce json
  419. // @Param Ton query string true "Ton"
  420. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  421. // @Router /authdata/GetRoleMenus [GET]
  422. func GetRecuDataByName(c *gin.Context) {
  423. appG := app.Gin{C: c}
  424. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  425. fsion := gofasion.NewFasion(string(dataByte))
  426. sqlnamestr := fsion.Get("name").ValueStr()
  427. parentidname := fsion.Get("idname").ValueStr()
  428. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  429. params := make(map[string]interface{})
  430. s_params := make([]interface{}, 0)
  431. if fsion.HasKey("params") {
  432. for _, v_params := range fsion.Get("params").Array() {
  433. s_params = append(s_params, v_params.ValueStr())
  434. }
  435. params["params"] = s_params
  436. } else {
  437. jparams := fsion.Get("parammaps")
  438. paramslist := strings.Split(p, ",")
  439. if len(paramslist) > 0 && p != "" {
  440. for _, value := range paramslist {
  441. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  442. if tempv, exists := c.Get("jwt_username"); exists {
  443. params[value] = tempv.(string)
  444. } else {
  445. params[value] = ""
  446. }
  447. } else {
  448. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  449. }
  450. }
  451. }
  452. }
  453. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  454. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  455. if err != nil {
  456. appG.Response(http.StatusOK, e.ERROR, err.Error())
  457. }
  458. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  459. }
  460. // @Summary 根据APISQL表中SQL执行得到数据集
  461. // @Tags GetDataByNames
  462. // @Accept json
  463. // @Produce json
  464. // @RequestBody sqlname query string true "sqlname"
  465. // @Param offset query int true "offset"
  466. // @Param pagecount query int true "pagecount"
  467. // @Param returntype query string true "returntype"
  468. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  469. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  470. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  471. // @Router /data/GetDataByNames [POST]
  472. func GetDataByNames(c *gin.Context) {
  473. appG := app.Gin{C: c}
  474. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  475. fsion := gofasion.NewFasion(string(dataByte))
  476. sqlParams := fsion.Array()
  477. queryData := make(map[string]interface{})
  478. for _, v := range sqlParams {
  479. fsion2 := gofasion.NewFasion(v.Json())
  480. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  481. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  482. if sql == "" {
  483. errorm := make(map[string]interface{})
  484. errorm["code"] = e.ERROR
  485. errorm["message"] = "sql没找到"
  486. queryData[fsion2.Get("name").ValueStr()] = errorm
  487. continue
  488. } else if sql != "" {
  489. offset := fsion2.Get("offset").ValueInt()
  490. pagecount := fsion2.Get("pagecount").ValueInt()
  491. returntype := fsion2.Get("returntype").ValueStr()
  492. s_params := make([]interface{}, 0)
  493. if fsion2.HasKey("parammaps") {
  494. parammaps := fsion2.Get("parammaps")
  495. paramslist := strings.Split(p, ",")
  496. if len(paramslist) > 0 && p != "" {
  497. for _, value := range paramslist {
  498. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  499. if tempv, exists := c.Get("jwt_username"); exists {
  500. s_params = append(s_params, tempv.(string))
  501. } else {
  502. s_params = append(s_params, "")
  503. }
  504. } else {
  505. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  506. }
  507. }
  508. }
  509. } else if fsion2.HasKey("params") {
  510. params := fsion2.Get("params").Array()
  511. for _, v_params := range params {
  512. s_params = append(s_params, v_params.ValueStr())
  513. }
  514. }
  515. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  516. if err != nil {
  517. errorm := make(map[string]interface{})
  518. errorm["code"] = e.ERROR
  519. errorm["message"] = err.Error()
  520. queryData[fsion2.Get("name").ValueStr()] = errorm
  521. logging.Error("GetDataByNames err: ", err)
  522. continue
  523. } else {
  524. queryData[fsion2.Get("name").ValueStr()] = queryData1
  525. }
  526. }
  527. }
  528. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  529. }
  530. // @Summary 根据APISQL表中SQL执行得到数据集
  531. // @Tags PostDataByNameForm
  532. // @Accept json
  533. // @Produce json
  534. // @Param sqlname query string true "sqlname"
  535. // @Param offset query int true "offset"
  536. // @Param pagecount query int true "pagecount"
  537. // @Param returntype query string true "returntype"
  538. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  539. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  540. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  541. // @Router /data/PostDataByNameForm [POST]
  542. func PostDataByNameForm(c *gin.Context) {
  543. appG := app.Gin{C: c}
  544. c.Request.ParseForm()
  545. params := c.Request.Form
  546. sqlnamestr := params.Get("name")
  547. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  548. s_params := make([]interface{}, 0)
  549. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  550. paramslist := strings.Split(p, ",")
  551. if len(paramslist) > 0 {
  552. for _, value := range paramslist {
  553. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  554. }
  555. }
  556. if sql != "" {
  557. queryData, err := execDataBySql(sql, s_params)
  558. if err != nil {
  559. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  560. } else {
  561. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  562. }
  563. } else {
  564. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  565. }
  566. }
  567. func GetReportform(c *gin.Context) {
  568. appG := app.Gin{C: c}
  569. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  570. fsion := gofasion.NewFasion(string(dataByte))
  571. sqlnamestr := fsion.Get("name").ValueStr()
  572. parammaps := fsion.Get("parammaps")
  573. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  574. tx := restful.Engine.NewSession()
  575. err := tx.Begin()
  576. defer func() {
  577. switch {
  578. case err != nil:
  579. fmt.Println("__error:", err)
  580. if tx != nil {
  581. tx.Rollback()
  582. }
  583. default:
  584. if tx != nil {
  585. err = tx.Commit()
  586. }
  587. }
  588. if tx != nil {
  589. tx.Close()
  590. }
  591. }()
  592. queryData, _ := praseReportform(sqlnamestr, parammaps, tx)
  593. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  594. }
  595. func praseReportform(sqlnamestr string, parammaps *gofasion.Fasion, tx *xorm.Session) (queryData map[string]interface{}, err error) {
  596. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  597. s_params := make([]interface{}, 0)
  598. if sql != "" {
  599. paramslist := strings.Split(p, ",")
  600. if len(paramslist) > 0 && p != "" {
  601. for _, value := range paramslist {
  602. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  603. }
  604. }
  605. }
  606. queryList, _ := tx.SQL(sql, s_params...).Query().List()
  607. temstr := ""
  608. switch sqlnamestr {
  609. case "getAccuracyAllHL", "getAccuracyAllQX", "getAccuracyAllJH", "getFeedEffMR", "getFeedEffHL", "getHomepageCB", "getAccuraa":
  610. temstr = sqlnamestr
  611. default:
  612. temstr = sqlnamestr[:10]
  613. }
  614. switch temstr {
  615. case "getAccurac", "getFeedEff":
  616. queryData, err = getAccuracy(queryList) // 不定参数
  617. case "getprocess", "getHomepro":
  618. queryData, err = getAccuracyV3(queryList)
  619. case "getAccuracyAllHL", "getAccuracyAllQX", "getAccuracyAllJH", "getFeedEffMR", "getFeedEffHL", "getHomepageCB", "getAccuraa":
  620. queryData, err = getAccuracyV2(queryList) //固定维度 日期
  621. case "getMateria":
  622. queryData, err = getAccuracyV4(queryList)
  623. case "getPriceAn":
  624. queryData, err = getAccuracyV5(queryList)
  625. case "getJT1Accu":
  626. queryData, err = getAccuracyV6(queryList)//固定维度 牧场
  627. default:
  628. queryData, err = nil, nil
  629. }
  630. return
  631. //switch sqlnamestr {
  632. //case "getAccuracyAllFT", "getAccuracyAllNQ", "getAccuracyAllCC", "getAccuracyAllLS","getFeedEffSL","getFeedEffZH","getFeedEffCB","getFeedEffCBLS","getFeedEffCBFT":
  633. // queryData, err = getAccuracy(queryList)
  634. //case "getprocessAnalysisTB","getHomeprocessAnalysis":
  635. // queryData, err = getAccuracyV3(queryList)
  636. //case "getAccuracyAllHL", "getAccuracyAllQX","getAccuracyAllJH","getFeedEffMR","getFeedEffHL","getHomepageCB":
  637. // queryData, err = getAccuracyV2(queryList)
  638. //default:
  639. // queryData, err = nil, nil
  640. //}
  641. //return
  642. }
  643. func getAccuracyV6(queryList []map[string]interface{}) (map[string]interface{}, error) {
  644. queryData := make(map[string]interface{})
  645. chartData := make(map[string]interface{})
  646. data := []interface{}{}
  647. data1 := []interface{}{}
  648. data2 := []interface{}{}
  649. data3 := []interface{}{}
  650. data4 := []interface{}{}
  651. for i := 0; i < len(queryList); i++ {
  652. data = append(data, queryList[i]["牧场"])
  653. data1 = append(data1, queryList[i]["field1"])
  654. data2 = append(data2, queryList[i]["field2"])
  655. data3 = append(data3, queryList[i]["field3"])
  656. data4 = append(data4, queryList[i]["field4"])
  657. }
  658. chartData["data1"] = data
  659. chartData["data2"] = data1
  660. chartData["data3"] = data2
  661. chartData["data4"] = data3
  662. chartData["data5"] = data4
  663. queryData["list"] = chartData
  664. queryData["code"] = 0
  665. queryData["message"] = "ok"
  666. queryData["data"] = queryList
  667. return queryData, nil
  668. }
  669. func getAccuracyV5(queryList []map[string]interface{}) (map[string]interface{}, error) {
  670. queryData := make(map[string]interface{})
  671. chartData := make(map[string]interface{})
  672. datamap1 := make(map[string]interface{})
  673. datamap2 := make(map[string]interface{})
  674. mapc := make(map[interface{}]interface{})
  675. data3 := []interface{}{}
  676. datamap2child := make(map[string]interface{})
  677. data2 := []interface{}{}
  678. data1 := []interface{}{}
  679. a := 0
  680. var dtem interface{}
  681. count := 0
  682. maxi := 0
  683. var max interface{}
  684. for i := 0; i < len(queryList); i++ {
  685. if max != queryList[i]["fname"] {
  686. mapc[count] = max
  687. max = queryList[i]["fname"]
  688. if maxi < count {
  689. maxi = count
  690. }
  691. count = 0
  692. }
  693. count++
  694. }
  695. mapc[count] = max
  696. if maxi < count {
  697. maxi = count
  698. }
  699. for i := 0; i < len(queryList); i++ {
  700. if i == 0 {
  701. datamap2["label"] = "饲料名称"
  702. switch queryList[i]["typestr"].(type) {
  703. case string:
  704. datamap2child["label"] = queryList[i]["typestr"].(string) + "/饲料参数"
  705. default:
  706. datamap2child["label"] = "/饲料参数"
  707. }
  708. datamap2child["prop"] = "A"
  709. data3 = append(data3, datamap2child)
  710. datamap2["children"] = data3
  711. data2 = append(data2, datamap2)
  712. data3 = []interface{}{}
  713. datamap2child = make(map[string]interface{})
  714. datamap2 = make(map[string]interface{})
  715. dtem = queryList[i]["fname"]
  716. }
  717. if dtem != queryList[i]["fname"] && i != 0 {
  718. data1 = append(data1, datamap1)
  719. dtem = queryList[i]["fname"]
  720. datamap1 = make(map[string]interface{})
  721. a = 0
  722. }
  723. if mapc[maxi] == queryList[i]["fname"] {
  724. datamap2["label"] = queryList[i]["feedname"]
  725. datamap2child["label"] = "理论"
  726. datamap2child["prop"] = "a" + strconv.Itoa(a)
  727. data3 = append(data3, datamap2child)
  728. datamap2child = make(map[string]interface{})
  729. datamap2child["label"] = "实际"
  730. datamap2child["prop"] = "a" + strconv.Itoa(a+1)
  731. data3 = append(data3, datamap2child)
  732. datamap2child = make(map[string]interface{})
  733. datamap2["children"] = data3
  734. data2 = append(data2, datamap2)
  735. data3 = []interface{}{}
  736. datamap2 = make(map[string]interface{})
  737. datamap2child = make(map[string]interface{})
  738. }
  739. datamap1["A"] = queryList[i]["fname"]
  740. datamap1["a"+strconv.Itoa(a)] = queryList[i]["lweight"]
  741. datamap1["a"+strconv.Itoa(a+1)] = queryList[i]["actualweightminus"]
  742. datamap2["label"] = queryList[i]["饲料名称"]
  743. a = a + 2
  744. }
  745. data1 = append(data1, datamap1)
  746. chartData["data1"] = data1
  747. chartData["data2"] = data2
  748. queryData["list"] = chartData
  749. queryData["code"] = 0
  750. queryData["message"] = "ok"
  751. queryData["data"] = queryList
  752. return queryData, nil
  753. }
  754. func getAccuracyV4(queryList []map[string]interface{}) (map[string]interface{}, error) {
  755. queryData := make(map[string]interface{})
  756. chartData := make(map[string]interface{})
  757. datamap1 := make(map[string]interface{})
  758. datamap2 := make(map[string]interface{})
  759. mapc := make(map[interface{}]interface{})
  760. data3 := []interface{}{}
  761. datamap2child := make(map[string]interface{})
  762. data2 := []interface{}{}
  763. data1 := []interface{}{}
  764. a := 0
  765. var dtem interface{}
  766. count := 0
  767. maxi := 0
  768. var max interface{}
  769. for i := 0; i < len(queryList); i++ {
  770. if max != queryList[i]["fname"] {
  771. mapc[count] = max
  772. max = queryList[i]["fname"]
  773. if maxi < count {
  774. maxi = count
  775. }
  776. count = 0
  777. }
  778. count++
  779. }
  780. mapc[count] = max
  781. if maxi < count {
  782. maxi = count
  783. }
  784. for i := 0; i < len(queryList); i++ {
  785. if i == 0 {
  786. datamap2["label"] = "饲料名称"
  787. switch queryList[i]["typestr"].(type) {
  788. case string:
  789. datamap2child["label"] = queryList[i]["typestr"].(string) + "/饲料参数"
  790. default:
  791. datamap2child["label"] = "/饲料参数"
  792. }
  793. datamap2child["prop"] = "A"
  794. data3 = append(data3, datamap2child)
  795. datamap2["children"] = data3
  796. data2 = append(data2, datamap2)
  797. data3 = []interface{}{}
  798. datamap2child = make(map[string]interface{})
  799. datamap2 = make(map[string]interface{})
  800. dtem = queryList[i]["fname"]
  801. }
  802. if dtem != queryList[i]["fname"] && i != 0 {
  803. data1 = append(data1, datamap1)
  804. dtem = queryList[i]["fname"]
  805. datamap1 = make(map[string]interface{})
  806. a = 0
  807. }
  808. if mapc[maxi] == queryList[i]["fname"] {
  809. datamap2["label"] = queryList[i]["feedname"]
  810. datamap2child["label"] = "理论"
  811. datamap2child["prop"] = "a" + strconv.Itoa(a)
  812. data3 = append(data3, datamap2child)
  813. datamap2child = make(map[string]interface{})
  814. datamap2child["label"] = "实际"
  815. datamap2child["prop"] = "a" + strconv.Itoa(a+1)
  816. data3 = append(data3, datamap2child)
  817. datamap2child = make(map[string]interface{})
  818. datamap2child["label"] = "误差值"
  819. datamap2child["prop"] = "a" + strconv.Itoa(a+2)
  820. data3 = append(data3, datamap2child)
  821. datamap2child = make(map[string]interface{})
  822. datamap2child["label"] = "误差率"
  823. datamap2child["prop"] = "a" + strconv.Itoa(a+3)
  824. data3 = append(data3, datamap2child)
  825. datamap2["children"] = data3
  826. data2 = append(data2, datamap2)
  827. data3 = []interface{}{}
  828. datamap2 = make(map[string]interface{})
  829. datamap2child = make(map[string]interface{})
  830. }
  831. datamap1["A"] = queryList[i]["fname"]
  832. datamap1["a"+strconv.Itoa(a)] = queryList[i]["lweight"]
  833. datamap1["a"+strconv.Itoa(a+1)] = queryList[i]["actualweightminus"]
  834. datamap1["a"+strconv.Itoa(a+2)] = queryList[i]["diff"]
  835. datamap1["a"+strconv.Itoa(a+3)] = queryList[i]["diffrate"]
  836. datamap2["label"] = queryList[i]["饲料名称"]
  837. a = a + 4
  838. }
  839. data1 = append(data1, datamap1)
  840. chartData["data1"] = data1
  841. chartData["data2"] = data2
  842. queryData["list"] = chartData
  843. queryData["code"] = 0
  844. queryData["message"] = "ok"
  845. queryData["data"] = queryList
  846. return queryData, nil
  847. }
  848. func getAccuracyV3(queryList []map[string]interface{}) (map[string]interface{}, error) {
  849. queryData := make(map[string]interface{})
  850. chartData := make(map[string]interface{})
  851. data := []interface{}{}
  852. data1 := []interface{}{}
  853. data2 := []interface{}{}
  854. data3 := []interface{}{}
  855. data4 := []interface{}{}
  856. datatem := []interface{}{}
  857. t1 := make(map[interface{}]string, 0)
  858. for i := 0; i < len(queryList); i++ {
  859. data = append(data, queryList[i]["mtime"])
  860. data1 = append(data1, queryList[i]["lweight"])
  861. data2 = append(data2, queryList[i]["weight"])
  862. //data3 = append(data3, queryList[i]["field3"])
  863. //data4 = append(data4, queryList[i]["field4"])
  864. if _, ok := t1[queryList[i]["id"]]; !ok {
  865. datatem = append(datatem, queryList[i]["startstime"], queryList[i]["lastactualweight"])
  866. data3 = append(data3, datatem)
  867. datatem = []interface{}{}
  868. datatem = append(datatem, queryList[i]["intime"], queryList[i]["actualweight"])
  869. data3 = append(data3, datatem)
  870. datatem = []interface{}{}
  871. }
  872. t1[queryList[i]["id"]] = "1"
  873. }
  874. chartData["data1"] = data
  875. chartData["data2"] = data1
  876. chartData["data3"] = data2
  877. chartData["data4"] = data3
  878. chartData["data5"] = data4
  879. queryData["list"] = chartData
  880. queryData["code"] = 0
  881. queryData["message"] = "ok"
  882. queryData["data"] = queryList
  883. return queryData, nil
  884. }
  885. func getAccuracyV2(queryList []map[string]interface{}) (map[string]interface{}, error) {
  886. queryData := make(map[string]interface{})
  887. chartData := make(map[string]interface{})
  888. data := []interface{}{}
  889. data1 := []interface{}{}
  890. data2 := []interface{}{}
  891. data3 := []interface{}{}
  892. data4 := []interface{}{}
  893. for i := 0; i < len(queryList); i++ {
  894. data = append(data, queryList[i]["日期"])
  895. data1 = append(data1, queryList[i]["field1"])
  896. data2 = append(data2, queryList[i]["field2"])
  897. data3 = append(data3, queryList[i]["field3"])
  898. data4 = append(data4, queryList[i]["field4"])
  899. }
  900. chartData["data1"] = data
  901. chartData["data2"] = data1
  902. chartData["data3"] = data2
  903. chartData["data4"] = data3
  904. chartData["data5"] = data4
  905. queryData["list"] = chartData
  906. queryData["code"] = 0
  907. queryData["message"] = "ok"
  908. queryData["data"] = queryList
  909. return queryData, nil
  910. }
  911. func getAccuracy(queryList []map[string]interface{}) (map[string]interface{}, error) {
  912. queryData := make(map[string]interface{})
  913. chartData := make(map[string]interface{})
  914. t1 := make(map[interface{}]interface{}, 0)
  915. t2 := make(map[interface{}]interface{}, 0)
  916. data := make(map[string][]interface{}, 0)
  917. t := make([]map[string][]interface{}, 0)
  918. e1 := []interface{}{}
  919. //e2 := []interface{}{}
  920. e2 := []string{}
  921. for _, value := range queryList {
  922. if _, ok := t1[value["名称"]]; !ok {
  923. e1 = append(e1, value["名称"])
  924. }
  925. if _, ok := t2[value["日期"]]; !ok {
  926. e2 = append(e2, value["日期"].(string))
  927. }
  928. t1[value["名称"]] = value["名称"]
  929. t2[value["日期"]] = value["日期"]
  930. }
  931. sort.Strings(e2)
  932. var b interface{}
  933. a := 0
  934. for i := 0; i < len(queryList); i++ {
  935. if i == 0 {
  936. b = queryList[i]["名称"]
  937. }
  938. if b != queryList[i]["名称"] {
  939. if a < len(e2)-1 {
  940. for k := 0; k < len(e2)-a; k++ {
  941. data["data"] = append(data["data"], "")
  942. }
  943. }
  944. t = append(t, data)
  945. data = make(map[string][]interface{}, 0)
  946. b = queryList[i]["名称"]
  947. a = 0
  948. }
  949. switch queryList[i]["日期"].(type) {
  950. case string:
  951. dates, _ := time.Parse("2006-01-02", queryList[i]["日期"].(string))
  952. if a < len(e2)-1 {
  953. if e2[a] != queryList[i]["日期"].(string) {
  954. for ; dates.Format("2006-01-02") < e2[a]; dates = dates.Add(24 * time.Hour) {
  955. println("======", dates.Format("2006-01-02"), e2[a])
  956. data["data"] = append(data["data"], "")
  957. }
  958. }
  959. }
  960. }
  961. data["data"] = append(data["data"], queryList[i]["准确率"])
  962. a++
  963. }
  964. if a < len(e2)-1 {
  965. for k := 0; k < len(e2)-a; k++ {
  966. data["data"] = append(data["data"], "")
  967. println(k)
  968. }
  969. }
  970. t = append(t, data)
  971. chartData["data1"] = e1
  972. chartData["data2"] = e2
  973. chartData["data3"] = t
  974. queryData["list"] = chartData
  975. queryData["code"] = 0
  976. queryData["message"] = "ok"
  977. queryData["data"] = queryList
  978. return queryData, nil
  979. }
  980. func GetUpkeepPlan(c *gin.Context) {
  981. appG := app.Gin{C: c}
  982. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  983. fsion := gofasion.NewFasion(string(dataByte))
  984. sqlnamestr := fsion.Get("name").ValueStr()
  985. offset := fsion.Get("offset").ValueDefaultInt(0)
  986. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  987. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  988. month := fsion.Get("month").ValueDefaultStr("map")
  989. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  990. tx := restful.Engine.NewSession()
  991. err := tx.Begin()
  992. defer func() {
  993. switch {
  994. case err != nil:
  995. fmt.Println("__error:", err)
  996. if tx != nil {
  997. tx.Rollback()
  998. }
  999. default:
  1000. if tx != nil {
  1001. err = tx.Commit()
  1002. }
  1003. }
  1004. if tx != nil {
  1005. tx.Close()
  1006. }
  1007. }()
  1008. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1009. if sql != "" {
  1010. s_params := make([]interface{}, 0)
  1011. if fsion.HasKey("parammaps") {
  1012. parammaps := fsion.Get("parammaps")
  1013. paramslist := strings.Split(p, ",")
  1014. if len(paramslist) > 0 && p != "" {
  1015. for _, value := range paramslist {
  1016. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1017. if tempv, exists := c.Get("jwt_username"); exists {
  1018. s_params = append(s_params, tempv.(string))
  1019. } else {
  1020. s_params = append(s_params, "")
  1021. }
  1022. } else {
  1023. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1024. }
  1025. }
  1026. }
  1027. } else if fsion.HasKey("params") {
  1028. params := fsion.Get("params").Array()
  1029. for _, v_params := range params {
  1030. s_params = append(s_params, v_params.ValueStr())
  1031. }
  1032. }
  1033. if returntype == "xlsx" {
  1034. var xlsxfile *xlsx.File
  1035. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  1036. //c.File("c:/dd.xlsx")
  1037. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1038. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  1039. c.Header("Content-Transfer-Encoding", "binary")
  1040. _ = xlsxfile.Write(c.Writer)
  1041. } else {
  1042. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1043. if err != nil {
  1044. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1045. } else {
  1046. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1047. if v, ok := value["id"]; ok {
  1048. //month = "2020-03"
  1049. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  1050. if seviceplans != nil {
  1051. for _, va := range seviceplans { //根据保养计划获取保养单
  1052. //day,_ :=strconv.Atoi(va["day"])
  1053. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  1054. //buk := make(map[string]map[string]string)
  1055. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  1056. jstr := ""
  1057. if bu["plantime"][8:9] == "0" {
  1058. jstr = "m" + bu["plantime"][9:]
  1059. } else {
  1060. jstr = "m" + bu["plantime"][8:]
  1061. }
  1062. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  1063. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  1064. } else {
  1065. if bu["flowCompeleted"] >= "2" {
  1066. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  1067. } else {
  1068. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  1069. }
  1070. }
  1071. }
  1072. }
  1073. }
  1074. }
  1075. }
  1076. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1077. }
  1078. }
  1079. } else {
  1080. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1081. }
  1082. }
  1083. func GetArrList(c *gin.Context) {
  1084. appG := app.Gin{C: c}
  1085. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1086. fsion := gofasion.NewFasion(string(dataByte))
  1087. sqlnamestr := fsion.Get("name").ValueStr()
  1088. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1089. offset := fsion.Get("offset").ValueDefaultInt(0)
  1090. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  1091. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1092. month := fsion.Get("month").ValueDefaultStr("map")
  1093. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1094. tx := restful.Engine.NewSession()
  1095. err := tx.Begin()
  1096. defer func() {
  1097. switch {
  1098. case err != nil:
  1099. fmt.Println("__error:", err)
  1100. if tx != nil {
  1101. tx.Rollback()
  1102. }
  1103. default:
  1104. if tx != nil {
  1105. err = tx.Commit()
  1106. }
  1107. }
  1108. if tx != nil {
  1109. tx.Close()
  1110. }
  1111. }()
  1112. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1113. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1114. if sql != "" {
  1115. s_params := make([]interface{}, 0)
  1116. if fsion.HasKey("parammaps") {
  1117. parammaps := fsion.Get("parammaps")
  1118. paramslist := strings.Split(p, ",")
  1119. if len(paramslist) > 0 && p != "" {
  1120. for _, value := range paramslist {
  1121. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1122. if tempv, exists := c.Get("jwt_username"); exists {
  1123. s_params = append(s_params, tempv.(string))
  1124. } else {
  1125. s_params = append(s_params, "")
  1126. }
  1127. } else {
  1128. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1129. }
  1130. }
  1131. }
  1132. }
  1133. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1134. if err != nil {
  1135. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1136. } else {
  1137. paramslist1 := strings.Split(p1, ",")
  1138. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1139. s_params1 := make([]interface{}, 0)
  1140. if len(paramslist1) > 0 && p != "" {
  1141. for _, v := range paramslist1 {
  1142. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1143. }
  1144. }
  1145. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1146. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1147. }
  1148. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1149. }
  1150. } else {
  1151. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1152. }
  1153. }
  1154. func GetAccount(c *gin.Context) {
  1155. appG := app.Gin{C: c}
  1156. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1157. fsion := gofasion.NewFasion(string(dataByte))
  1158. sqlnamestr := fsion.Get("name").ValueStr()
  1159. offset := fsion.Get("offset").ValueDefaultInt(0)
  1160. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  1161. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1162. tx := restful.Engine.NewSession()
  1163. err := tx.Begin()
  1164. defer func() {
  1165. switch {
  1166. case err != nil:
  1167. logging.Error("tx.Begin 事务启动失败__error:", err)
  1168. if tx != nil {
  1169. tx.Rollback()
  1170. }
  1171. default:
  1172. if tx != nil {
  1173. err = tx.Commit()
  1174. }
  1175. }
  1176. if tx != nil {
  1177. tx.Close()
  1178. }
  1179. }()
  1180. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1181. //fmt.Println("sql========\n",sqlnamestr,sql)
  1182. if sql != "" {
  1183. s_params := make([]interface{}, 0)
  1184. if fsion.HasKey("parammaps") {
  1185. parammaps := fsion.Get("parammaps")
  1186. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  1187. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  1188. }
  1189. paramslist := strings.Split(p, ",")
  1190. if len(paramslist) > 0 && p != "" {
  1191. for _, value := range paramslist {
  1192. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1193. if tempv, exists := c.Get("jwt_username"); exists {
  1194. s_params = append(s_params, tempv.(string))
  1195. } else {
  1196. s_params = append(s_params, "")
  1197. }
  1198. } else {
  1199. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1200. }
  1201. }
  1202. }
  1203. } else if fsion.HasKey("params") {
  1204. params := fsion.Get("params").Array()
  1205. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  1206. for _, v_params := range params {
  1207. s_params = append(s_params, v_params.ValueStr())
  1208. }
  1209. }
  1210. if returntype == "xlsx" {
  1211. var xlsxfile *xlsx.File
  1212. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  1213. //c.File("c:/dd.xlsx")
  1214. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1215. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  1216. c.Header("Content-Transfer-Encoding", "binary")
  1217. _ = xlsxfile.Write(c.Writer)
  1218. } else {
  1219. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1220. if err != nil {
  1221. logging.Error("GetDataByName err: ", err)
  1222. msg := geterrmsg(err.Error())
  1223. appG.Response(http.StatusOK, e.ERROR, msg)
  1224. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1225. } else {
  1226. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1227. }
  1228. }
  1229. } else {
  1230. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1231. }
  1232. }
  1233. // @Summary 根据APISQL表中SQL执行得到数据集
  1234. // @Tags PostDataByName
  1235. // @Accept json
  1236. // @Produce json
  1237. // @Param sqlname query string true "sqlname"
  1238. // @Param offset query int true "offset"
  1239. // @Param pagecount query int true "pagecount"
  1240. // @Param returntype query string true "returntype"
  1241. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1242. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1243. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1244. // @Router /data/PostDataByName [POST]
  1245. func PostDataByName(c *gin.Context) {
  1246. appG := app.Gin{C: c}
  1247. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1248. fsion := gofasion.NewFasion(string(dataByte))
  1249. sqlnamestr := fsion.Get("name").ValueStr()
  1250. s_params := make([]interface{}, 0)
  1251. tx := restful.Engine.NewSession()
  1252. err := tx.Begin()
  1253. defer func() {
  1254. switch {
  1255. case err != nil:
  1256. fmt.Println("__error:", err)
  1257. if tx != nil {
  1258. tx.Rollback()
  1259. }
  1260. default:
  1261. if tx != nil {
  1262. err = tx.Commit()
  1263. }
  1264. }
  1265. if tx != nil {
  1266. tx.Close()
  1267. }
  1268. }()
  1269. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1270. if sql != "" {
  1271. if fsion.HasKey("parammaps") {
  1272. parammaps := fsion.Get("parammaps")
  1273. logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  1274. paramslist := strings.Split(p, ",")
  1275. if len(paramslist) > 0 && p != "" {
  1276. for _, value := range paramslist {
  1277. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1278. if tempv, exists := c.Get("jwt_username"); exists {
  1279. s_params = append(s_params, tempv.(string))
  1280. } else {
  1281. s_params = append(s_params, "")
  1282. }
  1283. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1284. ids, err := setting.SnowIds.NextId()
  1285. if err != nil {
  1286. ids = time.Now().UnixNano()
  1287. logging.Info("create SnowIds err", err)
  1288. }
  1289. s_params = append(s_params, ids)
  1290. } else {
  1291. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1292. }
  1293. }
  1294. }
  1295. } else if fsion.HasKey("params") {
  1296. params := fsion.Get("params").Array()
  1297. logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  1298. //ids,err := setting.SnowIds.NextId()
  1299. //if err !=nil{
  1300. // ids = time.Now().UnixNano()
  1301. // logging.Info("create SnowIds err",err)
  1302. //}
  1303. //s_params = append(s_params, ids)
  1304. for _, v_params := range params {
  1305. s_params = append(s_params, v_params.ValueStr())
  1306. }
  1307. }
  1308. queryData, err := execDataBySqlT(sql, s_params, tx)
  1309. if err != nil {
  1310. logging.Error("PostDataByName err: ", err)
  1311. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1312. msg := geterrmsg(err.Error())
  1313. appG.Response(http.StatusOK, e.ERROR, msg)
  1314. } else {
  1315. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1316. }
  1317. } else {
  1318. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1319. }
  1320. }
  1321. // @Summary 根据APISQL表中SQL执行得到数据集
  1322. // @Tags ExecDataByConfig
  1323. // @Accept json
  1324. // @Produce json
  1325. // @Param sqlname query string true "sqlname"
  1326. // @Param offset query int true "offset"
  1327. // @Param pagecount query int true "pagecount"
  1328. // @Param returntype query string true "returntype"
  1329. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1330. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1331. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1332. // @Router /data/PostDataByName [POST]
  1333. func ExecDataByConfig(c *gin.Context) {
  1334. appG := app.Gin{C: c}
  1335. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1336. tempval_ := make(map[string]interface{})
  1337. tempCommon := make(map[string]interface{})
  1338. tempval := make([]map[string]interface{}, 0)
  1339. err := json.Unmarshal(dataByte, &tempval_)
  1340. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1341. if err != nil {
  1342. fmt.Println("error:", err)
  1343. } else {
  1344. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1345. tempCommon = v
  1346. }
  1347. if v, ok := tempval_["data"].([]interface{}); ok {
  1348. for _, Tvalue := range v {
  1349. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1350. tempval = append(tempval, v1)
  1351. }
  1352. }
  1353. }
  1354. tx := restful.Engine.NewSession()
  1355. err := tx.Begin()
  1356. if err != nil {
  1357. logging.Error("tx.Begin 事务启动失败__error:", err)
  1358. }
  1359. defer func() {
  1360. switch {
  1361. case err != nil:
  1362. fmt.Println("__error:", err)
  1363. if tx != nil {
  1364. tx.Rollback()
  1365. }
  1366. default:
  1367. if tx != nil {
  1368. err = tx.Commit()
  1369. }
  1370. }
  1371. if tx != nil {
  1372. tx.Close()
  1373. }
  1374. }()
  1375. if err == nil {
  1376. if tempv, exists := c.Get("jwt_username"); exists {
  1377. tempCommon["jwt_username"] = tempv.(string)
  1378. }
  1379. for _, paramvalue := range tempval {
  1380. if _, ok := paramvalue["resultname"]; !ok {
  1381. paramvalue["resultname"] = paramvalue["name"]
  1382. }
  1383. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1384. if err != nil {
  1385. logging.Error("ExecDataParam error:", err)
  1386. break
  1387. }
  1388. }
  1389. if err == nil {
  1390. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1391. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1392. } else {
  1393. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1394. }
  1395. } else {
  1396. msg := geterrmsg(err.Error())
  1397. appG.Response(http.StatusOK, e.ERROR, msg)
  1398. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1399. }
  1400. }
  1401. }
  1402. if err != nil {
  1403. msg := geterrmsg(err.Error())
  1404. appG.Response(http.StatusOK, e.ERROR, msg)
  1405. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1406. }
  1407. }
  1408. func interfacetostring(val interface{}) string {
  1409. switch val.(type) {
  1410. case string:
  1411. ss := val.(string)
  1412. return ss
  1413. break
  1414. case int:
  1415. ss := val.(int)
  1416. return strconv.Itoa(ss)
  1417. break
  1418. case int64:
  1419. ss := val.(int64)
  1420. return strconv.FormatInt(ss, 10)
  1421. break
  1422. case float64:
  1423. ss := val.(float64)
  1424. return strconv.FormatFloat(ss, 'E', -1, 32)
  1425. break
  1426. }
  1427. return ""
  1428. }
  1429. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1430. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1431. tempstrb := strings.IndexAny(valuestring, "@")
  1432. tempstre := strings.IndexAny(valuestring, ".")
  1433. if tempstrb > -1 && tempstre > -1 {
  1434. for _, ParamMapList := range ParamMap {
  1435. if v, ok := ParamMapList["resultname"]; ok {
  1436. if v == valuestring[tempstrb+1:tempstre] {
  1437. if v1, ok := ParamMapList["resultmaps"]; ok {
  1438. if newA, ok := v1.([]map[string]interface{}); ok {
  1439. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1440. } else if newA, ok := v1.(map[string]interface{}); ok {
  1441. return interfacetostring(newA[valuestring[tempstre+1:]])
  1442. }
  1443. }
  1444. }
  1445. }
  1446. }
  1447. } else {
  1448. return valuestring
  1449. }
  1450. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1451. return strconv.FormatInt(int64(valuestring), 10)
  1452. }
  1453. return ""
  1454. }
  1455. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1456. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1457. tempstrb := strings.IndexAny(valuestring, "@")
  1458. tempstre := strings.IndexAny(valuestring, ".")
  1459. if tempstrb > -1 && tempstre > -1 {
  1460. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1461. if s, ok := v.(string); ok {
  1462. return s
  1463. } else if s, ok := v.(float64); ok {
  1464. return strconv.FormatInt(int64(s), 10)
  1465. }
  1466. }
  1467. }
  1468. }
  1469. return ""
  1470. }
  1471. 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) {
  1472. sqlname := fasion["name"].(string)
  1473. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1474. if v, ok := fasion["type"]; ok {
  1475. sqltype = v.(string)
  1476. }
  1477. sql := ""
  1478. p := ""
  1479. s_params := make([]interface{}, 0)
  1480. if sqltype != "" {
  1481. sql, p = restful.GetSqlByName(sqlname, tx)
  1482. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1483. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1484. paramslist := strings.Split(p, ",")
  1485. if len(paramslist) > 0 && p != "" {
  1486. for _, value := range paramslist {
  1487. ss := ""
  1488. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1489. ids, err := setting.SnowIds.NextId()
  1490. if err != nil {
  1491. ids = time.Now().UnixNano()
  1492. logging.Info("create SnowIds err", err)
  1493. }
  1494. s_params = append(s_params, ids)
  1495. } else {
  1496. if ss == "" && CommonParamMap != nil {
  1497. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1498. ss = valuestring
  1499. tempstrb := strings.IndexAny(valuestring, "@")
  1500. tempstre := strings.IndexAny(valuestring, ".")
  1501. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1502. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1503. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1504. }
  1505. } else {
  1506. ss = ""
  1507. }
  1508. }
  1509. }
  1510. if ss == "" && ParentParamMap != nil {
  1511. ss = getParamValue_(v, value, ParentParamMap)
  1512. }
  1513. if ss == "" && sameParamMap != nil {
  1514. ss = getParamValue(v, value, sameParamMap)
  1515. }
  1516. if ss == "" && ParamMap != nil {
  1517. ss = getParamValue(v, value, ParamMap)
  1518. }
  1519. s_params = append(s_params, ss)
  1520. }
  1521. }
  1522. }
  1523. }
  1524. }
  1525. if sql == "" {
  1526. sqltype = ""
  1527. }
  1528. fmt.Printf("%v+ \n", s_params, sqlname)
  1529. if sqltype == "s1" {
  1530. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1531. if v, ok := tempValParam.(map[string]interface{}); ok {
  1532. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1533. }
  1534. if err != nil {
  1535. return nil, err
  1536. }
  1537. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1538. if err != nil {
  1539. return nil, err
  1540. }
  1541. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1542. } else if sqltype == "sm" {
  1543. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1544. if v, ok := tempValParam.(map[string]interface{}); ok {
  1545. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1546. } else {
  1547. fmt.Println("sm", tempValParam)
  1548. }
  1549. if err != nil {
  1550. return nil, err
  1551. }
  1552. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1553. if err != nil {
  1554. return nil, err
  1555. }
  1556. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1557. } else if sqltype == "v" {
  1558. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1559. if v, ok := tempValParam.(map[string]interface{}); ok {
  1560. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1561. } else {
  1562. fmt.Println("v", tempValParam)
  1563. }
  1564. if err != nil {
  1565. return nil, err
  1566. }
  1567. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1568. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1569. }
  1570. } else if sqltype == "e" {
  1571. tempVal_arrary := make([]map[string]interface{}, 0)
  1572. tempVal_map := make(map[string]interface{})
  1573. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1574. if err == nil {
  1575. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1576. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1577. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1578. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1579. return tempVal_arrary, err
  1580. }
  1581. return nil, err
  1582. } else {
  1583. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1584. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1585. if err != nil {
  1586. return nil, err
  1587. }
  1588. return nil, err
  1589. }
  1590. }
  1591. return nil, nil
  1592. }
  1593. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1594. var err error
  1595. subarray, ok := fasion["children"]
  1596. if ok {
  1597. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1598. tempVal_arrary := make([]map[string]interface{}, 0)
  1599. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1600. tempVal_ := make(map[string]interface{})
  1601. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1602. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1603. } else {
  1604. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1605. }
  1606. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1607. if err != nil {
  1608. return err
  1609. }
  1610. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1611. }
  1612. v.(map[string]interface{})["children"] = tempVal_arrary
  1613. }
  1614. }
  1615. return nil
  1616. }
  1617. // @Summary 删除图片
  1618. // @Tags RemovePicByName
  1619. // @Accept json
  1620. // @Produce json
  1621. // @Param sqlname query string true "sqlname"
  1622. // @Param offset query int true "offset"
  1623. // @Param pagecount query int true "pagecount"
  1624. // @Param returntype query string true "returntype"
  1625. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1626. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1627. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1628. // @Router /data/PostDataByName [POST]
  1629. func RemovePicByName(c *gin.Context) {
  1630. logging.Info("RemovePicByName ", c.Keys)
  1631. appG := app.Gin{C: c}
  1632. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1633. fsion := gofasion.NewFasion(string(dataByte))
  1634. sqlnamestr := fsion.Get("name").ValueStr()
  1635. picname := fsion.Get("picname").ValueStr()
  1636. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1637. params := fsion.Get("params").Array()
  1638. s_params := make([]interface{}, 0)
  1639. for _, v_params := range params {
  1640. s_params = append(s_params, v_params.ValueStr())
  1641. }
  1642. if sql != "" {
  1643. queryData, err := execDataBySql(sql, s_params)
  1644. if picname != "" {
  1645. // Destination
  1646. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1647. err := os.Remove(distPath) //删除文件test.txt
  1648. if err != nil {
  1649. //如果删除失败则输出 file remove Error!
  1650. fmt.Println("file remove Error!")
  1651. //输出错误详细信息
  1652. fmt.Printf("%s", err)
  1653. } else {
  1654. //如果删除成功则输出 file remove OK!
  1655. fmt.Print("file remove OK!")
  1656. }
  1657. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1658. err = os.Remove(distPath) //删除文件test.txt
  1659. if err != nil {
  1660. //如果删除失败则输出 file remove Error!
  1661. fmt.Println("file remove Error!")
  1662. //输出错误详细信息
  1663. fmt.Printf("%s", err)
  1664. } else {
  1665. //如果删除成功则输出 file remove OK!
  1666. fmt.Print("file remove OK!")
  1667. }
  1668. }
  1669. if err != nil {
  1670. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1671. } else {
  1672. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1673. }
  1674. } else {
  1675. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1676. }
  1677. }
  1678. // @Summary 删除文件
  1679. // @Tags RemoveFileByName
  1680. // @Accept json
  1681. // @Produce json
  1682. // @Param sqlname query string true "sqlname"
  1683. // @Param offset query int true "offset"
  1684. // @Param pagecount query int true "pagecount"
  1685. // @Param returntype query string true "returntype"
  1686. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1687. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1688. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1689. // @Router /data/PostDataByName [POST]
  1690. func RemoveFileByName(c *gin.Context) {
  1691. appG := app.Gin{C: c}
  1692. id := c.Param("id")
  1693. logging.Info("DownloadFile ", c.Keys, id)
  1694. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1695. if eqdoc == nil {
  1696. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1697. return
  1698. }
  1699. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1700. err = os.Remove(distPath) //删除文件test.txt
  1701. if err != nil {
  1702. //如果删除失败则输出 file remove Error!
  1703. fmt.Println("file remove Error!")
  1704. //输出错误详细信息
  1705. fmt.Printf("%s", err)
  1706. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1707. return
  1708. }
  1709. fmt.Print("file remove OK!")
  1710. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1711. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1712. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1713. //fsion := gofasion.NewFasion(string(dataByte))
  1714. //sqlnamestr := fsion.Get("name").ValueStr()
  1715. //filename := fsion.Get("filename").ValueStr()
  1716. //sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1717. //params := fsion.Get("params").Array()
  1718. //s_params := make([]interface{}, 0)
  1719. //for _, v_params := range params {
  1720. // s_params = append(s_params, v_params.ValueStr())
  1721. //}
  1722. //if sql != "" {
  1723. // queryData, err := execDataBySql(sql, s_params)
  1724. //
  1725. // if filename != "" {
  1726. // // Destination
  1727. // distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, filename)
  1728. //
  1729. // err := os.Remove(distPath) //删除文件test.txt
  1730. // if err != nil {
  1731. // //如果删除失败则输出 file remove Error!
  1732. // fmt.Println("file remove Error!")
  1733. // //输出错误详细信息
  1734. // fmt.Printf("%s", err)
  1735. // } else {
  1736. // //如果删除成功则输出 file remove OK!
  1737. // fmt.Print("file remove OK!")
  1738. // }
  1739. // }
  1740. // if err != nil {
  1741. // appG.Response(http.StatusOK, e.ERROR, err.Error())
  1742. // } else {
  1743. // appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1744. // }
  1745. //} else {
  1746. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  1747. //}
  1748. }
  1749. // @Summary 根据APISQL表中SQL执行得到数据集
  1750. // @Tags PostDataByName
  1751. // @Accept json
  1752. // @Produce json
  1753. // @Param sqlname query string true "sqlname"
  1754. // @Param offset query int true "offset"
  1755. // @Param pagecount query int true "pagecount"
  1756. // @Param returntype query string true "returntype"
  1757. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1758. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1759. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1760. // @Router /data/PostDataByName [POST]
  1761. func UpdateDataRelation(c *gin.Context) {
  1762. appG := app.Gin{C: c}
  1763. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1764. fsion := gofasion.NewFasion(string(dataByte))
  1765. tablename := fsion.Get("name").ValueStr()
  1766. dataname := fsion.Get("dataname").ValueStr()
  1767. datavalue := fsion.Get("datavalue").ValueStr()
  1768. valuename := fsion.Get("valuename").ValueStr()
  1769. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1770. values := fsion.Get("values").Array()
  1771. tx := restful.Engine.NewSession()
  1772. err := tx.Begin()
  1773. defer func() {
  1774. switch {
  1775. case err != nil:
  1776. fmt.Println("__error:", err)
  1777. if tx != nil {
  1778. tx.Rollback()
  1779. }
  1780. default:
  1781. if tx != nil {
  1782. err = tx.Commit()
  1783. }
  1784. }
  1785. if tx != nil {
  1786. tx.Close()
  1787. }
  1788. }()
  1789. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1790. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1791. d_params := make([]interface{}, 4)
  1792. d_params[0] = datavalue
  1793. s_params := ""
  1794. for _, v_values := range values {
  1795. d_params[1] = v_values.ValueStr()
  1796. if s_params == "" {
  1797. s_params = v_values.ValueStr()
  1798. } else {
  1799. s_params = s_params + "," + v_values.ValueStr()
  1800. }
  1801. d_params[2] = d_params[1]
  1802. d_params[3] = d_params[0]
  1803. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1804. if err != nil {
  1805. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1806. break
  1807. }
  1808. }
  1809. if s_params != "" {
  1810. deleteSqlstr := "delete from " + tablename + " " +
  1811. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1812. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1813. if err != nil {
  1814. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1815. } else if err == nil {
  1816. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1817. }
  1818. } else {
  1819. deleteSqlstr := "delete from " + tablename + " " +
  1820. " where " + dataname + " = " + datavalue
  1821. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1822. if err != nil {
  1823. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1824. } else if err == nil {
  1825. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1826. }
  1827. }
  1828. }
  1829. // @Summary 根据APISQL表中SQL执行得到数据集
  1830. // @Tags PostDatasByName
  1831. // @Accept json
  1832. // @Produce json
  1833. // @Param sqlname query string true "sqlname"
  1834. // @Param offset query int true "offset"
  1835. // @Param pagecount query int true "pagecount"
  1836. // @Param returntype query string true "returntype"
  1837. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1838. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1839. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1840. // @Router /data/PostDatasByName [POST]
  1841. func PostDataByNames(c *gin.Context) {
  1842. appG := app.Gin{C: c}
  1843. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1844. fsion := gofasion.NewFasion(string(dataByte))
  1845. sqlParams := fsion.Array()
  1846. queryData := make(map[string]interface{})
  1847. for _, v := range sqlParams {
  1848. fsion2 := gofasion.NewFasion(v.Json())
  1849. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1850. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1851. if sql == "" {
  1852. errorm := make(map[string]interface{})
  1853. errorm["code"] = e.ERROR
  1854. errorm["message"] = "sql没有找到"
  1855. errorm["param"] = ""
  1856. queryData[fsion2.Get("name").ValueStr()] = errorm
  1857. continue
  1858. } else if sql != "" {
  1859. s_params := make([]interface{}, 0)
  1860. if fsion2.HasKey("parammaps") {
  1861. parammaps := fsion2.Get("parammaps")
  1862. paramslist := strings.Split(p, ",")
  1863. if len(paramslist) > 0 && p != "" {
  1864. for _, value := range paramslist {
  1865. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1866. if tempv, exists := c.Get("jwt_username"); exists {
  1867. s_params = append(s_params, tempv.(string))
  1868. } else {
  1869. s_params = append(s_params, "")
  1870. }
  1871. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1872. ids, err := setting.SnowIds.NextId()
  1873. if err != nil {
  1874. ids = time.Now().UnixNano()
  1875. logging.Info("create SnowIds err", err)
  1876. }
  1877. s_params = append(s_params, ids)
  1878. } else {
  1879. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1880. }
  1881. }
  1882. }
  1883. } else if fsion2.HasKey("params") {
  1884. params := fsion2.Get("params").Array()
  1885. //ids,err := setting.SnowIds.NextId()
  1886. //if err !=nil{
  1887. // ids = time.Now().UnixNano()
  1888. // logging.Info("create SnowIds err",err)
  1889. //}
  1890. //s_params = append(s_params, ids)
  1891. for _, v_params := range params {
  1892. s_params = append(s_params, v_params.ValueStr())
  1893. }
  1894. }
  1895. _, err := execDataBySql(sql, s_params)
  1896. if err != nil {
  1897. logging.Error("PostDataByName err: ", err)
  1898. errorm := make(map[string]interface{})
  1899. errorm["code"] = e.ERROR
  1900. errorm["message"] = err.Error()
  1901. errorm["param"] = s_params
  1902. queryData[fsion2.Get("name").ValueStr()] = errorm
  1903. continue
  1904. } else {
  1905. errorm := make(map[string]interface{})
  1906. errorm["code"] = e.SUCCESS
  1907. errorm["message"] = "success"
  1908. queryData[fsion2.Get("name").ValueStr()] = errorm
  1909. continue
  1910. }
  1911. } else {
  1912. errorm := make(map[string]interface{})
  1913. errorm["code"] = e.ERROR
  1914. errorm["message"] = "NO SQL"
  1915. errorm["param"] = ""
  1916. queryData[fsion2.Get("name").ValueStr()] = errorm
  1917. }
  1918. }
  1919. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1920. }
  1921. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1922. if offset > 0 {
  1923. offset = offset - 1
  1924. }
  1925. //if pagecount == 0 {
  1926. // pagecount = setting.AppSetting.PageSize
  1927. //}else if pagecount>setting.AppSetting.PageSize{
  1928. // pagecount = setting.AppSetting.PageSize
  1929. //}
  1930. if returntype == "list" {
  1931. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1932. return queryData, err
  1933. } else if returntype == "listlist" {
  1934. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1935. return queryData, err
  1936. } else {
  1937. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1938. return queryData, err
  1939. }
  1940. }
  1941. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1942. if offset > 0 {
  1943. offset = offset - 1
  1944. }
  1945. //if pagecount == 0 {
  1946. // pagecount = setting.AppSetting.PageSize
  1947. //}else if pagecount>setting.AppSetting.PageSize{
  1948. // pagecount = setting.AppSetting.PageSize
  1949. //}
  1950. if returntype == "list" {
  1951. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1952. return queryData, err
  1953. } else if returntype == "listlist" {
  1954. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1955. return queryData, err
  1956. } else {
  1957. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1958. return queryData, err
  1959. }
  1960. }
  1961. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1962. paramslist := strings.Split(Params, ",")
  1963. s_params := make([]interface{}, 0)
  1964. if isList {
  1965. for _, v_params := range thisParams["params"].([]interface{}) {
  1966. s_params = append(s_params, v_params)
  1967. }
  1968. } else {
  1969. paramslist := strings.Split(Params, ",")
  1970. if len(paramslist) > 0 && Params != "" {
  1971. for _, value := range paramslist {
  1972. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1973. }
  1974. }
  1975. }
  1976. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  1977. for _, queryData_ := range queryData {
  1978. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  1979. if isList {
  1980. //fmt.Println(idname, "-------------- -queryData_[idname]", queryData_)
  1981. if queryData_[idname] != nil {
  1982. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  1983. }
  1984. } else {
  1985. if queryData_[idname] != nil {
  1986. thisParams[idname] = queryData_[idname].(interface{})
  1987. }
  1988. if len(paramslist) > 0 && Params != "" {
  1989. s_params = make([]interface{}, 0)
  1990. for _, value := range paramslist {
  1991. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1992. }
  1993. }
  1994. }
  1995. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  1996. } else {
  1997. }
  1998. }
  1999. return queryData, err
  2000. }
  2001. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2002. queryData, err := restful.ExecQuery(sqlstr, params)
  2003. return queryData, err
  2004. }
  2005. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  2006. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  2007. return queryData, err
  2008. }
  2009. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  2010. queryData, err := restful.ExecQuery(sqlstr, params)
  2011. return queryData, err
  2012. }
  2013. // @Summary 导入excel文件到数据库,excel第一行作为参数
  2014. // @Tags ImportExcel
  2015. // @Accept json
  2016. // @Produce json
  2017. // @Param file query string true "文件名"
  2018. // @Param name header string true "执行sql的名字"
  2019. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  2020. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  2021. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  2022. // @Router /data/ImportExcel [POST]
  2023. func ImportExcel(c *gin.Context) {
  2024. appG := app.Gin{C: c}
  2025. inputdata := ""
  2026. c.Request.ParseForm()
  2027. //tempv1, _ := c.Get("jwt_username")
  2028. //fmt.Println("=======================",tempv1)
  2029. params := c.Request.Form
  2030. file, _, err := c.Request.FormFile("file")
  2031. if err != nil {
  2032. appG.Response(http.StatusOK, e.ERROR, err)
  2033. return
  2034. }
  2035. sqlnamestr := params.Get("name")
  2036. sheetname := params.Get("sheetname")
  2037. importParams := params.Get("importParams")
  2038. dateParams := params.Get("dateParams")
  2039. requiredParams := params.Get("requiredParams")
  2040. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestr)
  2041. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  2042. paramslist := strings.Split(importParams, ",")
  2043. dateParamslist := strings.Split(dateParams, ",")
  2044. requiredParamslist := strings.Split(requiredParams, ",")
  2045. paramslist = append(paramslist, "jwt_username")
  2046. queryData := make([]interface{}, 0)
  2047. xlsx1, err := excelize.OpenReader(file)
  2048. if err != nil {
  2049. fmt.Println(err)
  2050. return
  2051. }
  2052. ok := 0
  2053. error := 0
  2054. rows, _ := xlsx1.GetRows(sheetname)
  2055. if len(rows) > 1000 {
  2056. rows = rows[:1000]
  2057. }
  2058. //fmt.Println("============================",rows)
  2059. for i, row := range rows {
  2060. fmt.Println("============================", row)
  2061. if i > 0 {
  2062. if len(paramslist) > 0 {
  2063. s_params := make([]interface{}, 0)
  2064. entry := make(map[string]interface{})
  2065. outentry := make(map[string]interface{})
  2066. inputdata = ""
  2067. for _, value := range paramslist {
  2068. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2069. if tempv, exists := c.Get("jwt_username"); exists {
  2070. s_params = append(s_params, tempv.(string))
  2071. } else {
  2072. s_params = append(s_params, "")
  2073. }
  2074. } else {
  2075. for j, colCell := range rows[0] {
  2076. if strings.Trim(value, " ") == colCell {
  2077. for k, colCell1 := range row {
  2078. if j == k {
  2079. outentry[colCell] = colCell1
  2080. entry[colCell] = colCell1
  2081. //inputdata = inputdata + colCell + ":" + colCell1 + ";"
  2082. }
  2083. }
  2084. }
  2085. }
  2086. s_params = append(s_params, entry[strings.Trim(value, " ")])
  2087. }
  2088. }
  2089. for _, v := range dateParamslist {
  2090. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2091. outentry[strings.Trim(v, " ")] = TransfTime(d.(string))
  2092. }
  2093. println(outentry[strings.Trim(v, " ")].(string))
  2094. }
  2095. a := ""
  2096. for _, v := range requiredParamslist {
  2097. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d =="" {
  2098. a = strings.Trim(v, " ")
  2099. break
  2100. }
  2101. }
  2102. outentry["input"] = inputdata
  2103. if a != ""{
  2104. outentry["error_msg"] = a+" 未填或格式错误"
  2105. error++
  2106. queryData = append(queryData, outentry)
  2107. continue
  2108. }
  2109. // returnmsg, err := execDataBySql(sqlApi.Sqlstr, s_params)
  2110. returnmsg, err := getDataBySql(sql, 0, 0, "4", s_params)
  2111. returnmsgmap, _ := returnmsg.(map[string]interface{})
  2112. returnmsgmap1, _ := returnmsgmap["list"].([]map[string]interface{})
  2113. if err != nil {
  2114. outentry["error_msg"] = err.Error()
  2115. error++
  2116. queryData = append(queryData, outentry)
  2117. } else if (len(returnmsgmap1) > 0) && (returnmsgmap1[0]["msg"] == "success") {
  2118. ok++
  2119. } else {
  2120. msg := geterrmsg(returnmsgmap1[0]["msg"].(string))
  2121. //appG.Response(http.StatusOK, e.ERROR, msg)
  2122. outentry["error_msg"] = msg
  2123. error++
  2124. queryData = append(queryData, outentry)
  2125. }
  2126. }
  2127. }
  2128. }
  2129. data := make(map[string]interface{})
  2130. data["result"] = queryData
  2131. data["success"] = ok
  2132. data["err_count"] = error
  2133. appG.Response(http.StatusOK, e.SUCCESS, data)
  2134. }
  2135. func TransfTime(timestr string)string{
  2136. if timestr == ""{
  2137. return ""
  2138. }
  2139. days,err := strconv.Atoi(timestr)
  2140. if err != nil {
  2141. if len(timestr) == 8 && strings.Count(timestr,"-") == 2{
  2142. return "20"+timestr[6:]+"-"+ timestr[:5]
  2143. }
  2144. if len(timestr) == 10 && (strings.Count(timestr,"-") == 2 || strings.Count(timestr,"/") == 2){
  2145. return timestr
  2146. }
  2147. return ""
  2148. }
  2149. times , _ := time.Parse("2006-01-02","1899-12-30")
  2150. times = times.AddDate(0,0,days)
  2151. return times.Format("2006-01-02")
  2152. }
  2153. func Createchart(c *gin.Context) {
  2154. appG := app.Gin{C: c}
  2155. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2156. fsion := gofasion.NewFasion(string(dataByte))
  2157. chart_name := fsion.Get("chart_name").ValueStr()
  2158. desc := fsion.Get("desc").ValueStr()
  2159. pastureid := fsion.Get("pastureid").ValueStr()
  2160. source_id := fsion.Get("source_id").ValueStr()
  2161. emp := fsion.Get("emp").ValueStr()
  2162. content := fsion.Get("content").Json()
  2163. //fmt.Println("=============",parammaW.Json())
  2164. var mapResult map[string]interface{}
  2165. err1 := json.Unmarshal([]byte(content), &mapResult)
  2166. if err1 != nil {
  2167. fmt.Println("JsonToMapDemo err: ", err1)
  2168. }
  2169. //fmt.Println("---------",mapResult)
  2170. tx := restful.Engine.NewSession()
  2171. err := tx.Begin()
  2172. defer func() {
  2173. switch {
  2174. case err != nil:
  2175. logging.Error("tx.Begin 事务启动失败__error:", err)
  2176. if tx != nil {
  2177. tx.Rollback()
  2178. }
  2179. default:
  2180. if tx != nil {
  2181. err = tx.Commit()
  2182. }
  2183. }
  2184. if tx != nil {
  2185. tx.Close()
  2186. }
  2187. }()
  2188. //fmt.Println("sql========\n",sqlnamestr,sql)
  2189. ids, err := setting.SnowIds.NextId()
  2190. if err != nil {
  2191. ids = time.Now().UnixNano()
  2192. logging.Info("create SnowIds err", err)
  2193. }
  2194. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2195. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2196. if err != nil {
  2197. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2198. } else {
  2199. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2200. }
  2201. }
  2202. func Updatedashboard(c *gin.Context) {
  2203. appG := app.Gin{C: c}
  2204. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2205. fsion := gofasion.NewFasion(string(dataByte))
  2206. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2207. pastureid := fsion.Get("pastureid").ValueStr()
  2208. content := fsion.Get("content").Json()
  2209. //fmt.Println("=============",parammaW.Json())
  2210. var mapResult map[string]interface{}
  2211. err1 := json.Unmarshal([]byte(content), &mapResult)
  2212. if err1 != nil {
  2213. fmt.Println("JsonToMapDemo err: ", err1)
  2214. }
  2215. layout := mapResult["layout"]
  2216. fmt.Println("---------", layout)
  2217. tx := restful.Engine.NewSession()
  2218. err := tx.Begin()
  2219. defer func() {
  2220. switch {
  2221. case err != nil:
  2222. logging.Error("tx.Begin 事务启动失败__error:", err)
  2223. if tx != nil {
  2224. tx.Rollback()
  2225. }
  2226. default:
  2227. if tx != nil {
  2228. err = tx.Commit()
  2229. }
  2230. }
  2231. if tx != nil {
  2232. tx.Close()
  2233. }
  2234. }()
  2235. //fmt.Println("sql========\n",sqlnamestr,sql)
  2236. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2237. if err != nil {
  2238. println("2", err.Error())
  2239. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2240. } else {
  2241. if exec != nil {
  2242. if exec[0]["content"] == nil {
  2243. mapR := make(map[string]interface{})
  2244. mapR["layout"] = layout
  2245. mjson, _ := json.Marshal(mapR)
  2246. mString := string(mjson)
  2247. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2248. if err3 != nil {
  2249. println("3", err3.Error())
  2250. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2251. } else {
  2252. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2253. }
  2254. } else {
  2255. var mapR map[string]interface{}
  2256. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2257. if err1 != nil {
  2258. fmt.Println("JsonToMapDemo err: ", err2)
  2259. }
  2260. mapR["layout"] = layout
  2261. mjson, _ := json.Marshal(mapR)
  2262. mString := string(mjson)
  2263. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2264. if err3 != nil {
  2265. println("3", err3.Error())
  2266. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2267. } else {
  2268. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2269. }
  2270. }
  2271. } else {
  2272. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2273. }
  2274. }
  2275. }
  2276. func ExecSQL(c *gin.Context) {
  2277. appG := app.Gin{C: c}
  2278. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2279. fsion := gofasion.NewFasion(string(dataByte))
  2280. content := fsion.Get("content").Json()
  2281. pastureid := fsion.Get("pastureid").ValueStr()
  2282. //pastureid := fsion.Get("pastureid").ValueStr()
  2283. //println(pastureid,"==================")
  2284. //fmt.Println("=============",parammaW.Json())
  2285. var mapResult map[string]interface{}
  2286. err1 := json.Unmarshal([]byte(content), &mapResult)
  2287. if err1 != nil {
  2288. fmt.Println("JsonToMapDemo err: ", err1)
  2289. }
  2290. //fmt.Println("---------",mapResult)
  2291. sqlstr := "select "
  2292. groupstr := " GROUP BY "
  2293. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2294. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2295. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2296. }
  2297. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2298. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2299. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2300. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2301. } else {
  2302. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2303. sqlstr = sqlstr + tem + ","
  2304. }
  2305. }
  2306. if _, ok := mapResult["selectedCalcul2"]; ok {
  2307. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2308. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2309. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2310. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2311. } else {
  2312. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2313. sqlstr = sqlstr + tem + ","
  2314. }
  2315. }
  2316. }
  2317. //
  2318. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2319. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2320. //if len(mapResult["filters"].([]interface {}))>0{
  2321. sqlstr = sqlstr + " where pastureid=" + pastureid
  2322. //}
  2323. //
  2324. for _, value := range mapResult["filters"].([]interface{}) {
  2325. switch value.(map[string]interface{})["filterOperator"].(string) {
  2326. case ">", "=", "<", ">=", "<=", "!=", "like":
  2327. 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 "
  2328. case "IN":
  2329. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2330. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2331. sqlstr = sqlstr + value1.(string) + ","
  2332. }
  2333. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2334. sqlstr = sqlstr + ")" + " AND "
  2335. case "BETWEEN":
  2336. 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 "
  2337. }
  2338. }
  2339. if len(mapResult["filters"].([]interface{})) > 0 {
  2340. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2341. }
  2342. //
  2343. groupstr = groupstr[0 : len(groupstr)-1]
  2344. sqlstr = sqlstr + groupstr + " "
  2345. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2346. sqlstr = sqlstr + " order by "
  2347. }
  2348. //
  2349. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2350. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2351. sqlstr = sqlstr + value.(string) + " "
  2352. } else {
  2353. sqlstr = sqlstr + value.(string) + ","
  2354. }
  2355. }
  2356. //
  2357. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2358. //fmt.Println("====++---------",sqlstr)
  2359. tx := restful.Engine.NewSession()
  2360. err := tx.Begin()
  2361. defer func() {
  2362. switch {
  2363. case err != nil:
  2364. logging.Error("tx.Begin 事务启动失败__error:", err)
  2365. if tx != nil {
  2366. tx.Rollback()
  2367. }
  2368. default:
  2369. if tx != nil {
  2370. err = tx.Commit()
  2371. }
  2372. }
  2373. if tx != nil {
  2374. tx.Close()
  2375. }
  2376. }()
  2377. //fmt.Println("sql========\n",sqlnamestr,sql)
  2378. //ids,err := setting.SnowIds.NextId()
  2379. //if err !=nil{
  2380. // ids = time.Now().UnixNano()
  2381. // logging.Info("create SnowIds err",err)
  2382. //}
  2383. // exec,err :=tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2384. //ids,pastureid,chart_name,0,emp,desc,source_id)
  2385. exec, err := tx.SQL(sqlstr).Query().List()
  2386. if err != nil {
  2387. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2388. } else {
  2389. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2390. }
  2391. }
  2392. func Dashboards(c *gin.Context) {
  2393. appG := app.Gin{C: c}
  2394. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2395. fsion := gofasion.NewFasion(string(dataByte))
  2396. sqlnamestr := fsion.Get("name").ValueStr()
  2397. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2398. offset := fsion.Get("offset").ValueDefaultInt(0)
  2399. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2400. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2401. month := fsion.Get("month").ValueDefaultStr("map")
  2402. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2403. tx := restful.Engine.NewSession()
  2404. err := tx.Begin()
  2405. defer func() {
  2406. switch {
  2407. case err != nil:
  2408. fmt.Println("__error:", err)
  2409. if tx != nil {
  2410. tx.Rollback()
  2411. }
  2412. default:
  2413. if tx != nil {
  2414. err = tx.Commit()
  2415. }
  2416. }
  2417. if tx != nil {
  2418. tx.Close()
  2419. }
  2420. }()
  2421. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2422. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2423. if sql != "" {
  2424. s_params := make([]interface{}, 0)
  2425. if fsion.HasKey("parammaps") {
  2426. parammaps := fsion.Get("parammaps")
  2427. paramslist := strings.Split(p, ",")
  2428. if len(paramslist) > 0 && p != "" {
  2429. for _, value := range paramslist {
  2430. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2431. if tempv, exists := c.Get("jwt_username"); exists {
  2432. s_params = append(s_params, tempv.(string))
  2433. } else {
  2434. s_params = append(s_params, "")
  2435. }
  2436. } else {
  2437. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2438. }
  2439. }
  2440. }
  2441. }
  2442. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2443. if err != nil {
  2444. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2445. } else {
  2446. //paramslist1 := strings.Split(p1, ",")
  2447. dids := make([]interface{}, 0)
  2448. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2449. var mapResult map[string]interface{}
  2450. dids = append(dids, value["dashboard_id"])
  2451. if value["content"] != nil {
  2452. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2453. if err1 != nil {
  2454. println("JsonToMapDemo1 err: ", err1)
  2455. }
  2456. fmt.Printf("mapResult======%+v\n", mapResult)
  2457. //fmt.Printf("%v+\n",value["content"].(string))
  2458. temap := make(map[string]interface{})
  2459. tem := mapResult["layout"].([]interface{})
  2460. fmt.Printf("tem======%+v\n", tem)
  2461. if v, ok := value["chartids"]; ok {
  2462. chartids := strings.Split(v.(string), ",")
  2463. for _, va := range chartids {
  2464. a := false
  2465. for _, v2 := range tem {
  2466. if v2.(map[string]interface{})["id"].(string) == va {
  2467. a = true
  2468. //println("va1======",va)
  2469. }
  2470. }
  2471. if !a {
  2472. println("va2==-----------======", va)
  2473. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2474. va + "\",\"id\":\"" + va +
  2475. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2476. var mapTem map[string]interface{}
  2477. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2478. if err1 != nil {
  2479. println("JsonToMapDemo err: ", err1)
  2480. }
  2481. //println("mapTem========== ", mapTem)
  2482. tem = append(tem, mapTem)
  2483. }
  2484. }
  2485. temap["layout"] = tem
  2486. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2487. }
  2488. } else {
  2489. temap := make(map[string]interface{})
  2490. tem := make([]interface{}, 0)
  2491. if v, ok := value["chartids"]; ok {
  2492. chartids := strings.Split(v.(string), ",")
  2493. for _, va := range chartids {
  2494. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2495. va + "\",\"id\":\"" + va +
  2496. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2497. var mapTem map[string]interface{}
  2498. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2499. if err1 != nil {
  2500. println("JsonToMapDemo err: ", err1)
  2501. }
  2502. tem = append(tem, mapTem)
  2503. }
  2504. temap["layout"] = tem
  2505. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2506. }
  2507. }
  2508. }
  2509. queryData.(map[string]interface{})["order"] = dids
  2510. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2511. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2512. }
  2513. } else {
  2514. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2515. }
  2516. }
  2517. //type Nur struct {
  2518. // Avgmonthage float64 `json : "avgmonthage"` //月龄
  2519. // Bw float64 `json : "bw"` //体重
  2520. // Dayw float64 `json : "dayw"` //日增重
  2521. // Fetal float64 `json : "fetal"` //胎次
  2522. // Avgdim float64 `json : "avgdim"` //平均泌乳天数
  2523. // Dayspre float64 `json : "dayspre"` //怀孕天数
  2524. // Product float64 `json : "product"` //产奶量
  2525. // Fat float64 `json : "fat"` //乳脂率
  2526. // Pro float64 `json : "pro"` //乳蛋白率
  2527. // Lactose float64 `json : "lactose"` //乳糖率
  2528. // Source string `json : "source"` //来源
  2529. // Tem float64 `json : "tem"` //温度
  2530. // Cowsum float64 `json : "cowsum"` //牛头数
  2531. // Cowclass float64 `json : "cowclass"` //牲畜类别
  2532. // Cowclassid float64 `json : "cowclassid"` //牲畜类别id
  2533. // Bigcowclass string `json : "bigcowclass"` //牲畜大类
  2534. //}
  2535. type Nur struct {
  2536. Avgmonthage float64 //月龄
  2537. Bw float64 //体重
  2538. Dayw float64 //日增重
  2539. Fetal float64 //胎次
  2540. Avgdim float64 //平均泌乳天数
  2541. Dayspre float64 //怀孕天数
  2542. Product float64 //产奶量
  2543. Fat float64 //乳脂率
  2544. Pro float64 //乳蛋白率
  2545. Lactose float64 //乳糖率
  2546. Source string //来源
  2547. Tem float64 //温度
  2548. Cowsum float64 //牛头数
  2549. Cowclass string //牲畜类别
  2550. Cowclassid float64 //牲畜类别id
  2551. Bigcowclass string //牲畜大类
  2552. }
  2553. func GETNurJudge(c *gin.Context) {
  2554. appG := app.Gin{C: c}
  2555. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2556. fsion := gofasion.NewFasion(string(dataByte))
  2557. nurstr := fsion.Get("parammaps").Json()
  2558. parammaps := make(map[string]interface{})
  2559. nur := Nur{}
  2560. _ = json.Unmarshal([]byte(nurstr), &nur) //需要json 的类型相同
  2561. _ = json.Unmarshal([]byte(nurstr), &parammaps) //需要json 的类型相同
  2562. tx := restful.Engine.NewSession()
  2563. err := tx.Begin()
  2564. defer func() {
  2565. switch {
  2566. case err != nil:
  2567. fmt.Println("__error:", err)
  2568. if tx != nil {
  2569. tx.Rollback()
  2570. }
  2571. default:
  2572. if tx != nil {
  2573. err = tx.Commit()
  2574. }
  2575. }
  2576. if tx != nil {
  2577. tx.Close()
  2578. }
  2579. }()
  2580. formulas, _ := tx.SQL("select * from tb_formula_d where cowclass = ? " +
  2581. "and if (?='',''='', nutrition=? ) ORDER BY nutrition", nur.Bigcowclass, nur.Source, nur.Source).Query().List()
  2582. resnur, err := CalNUR(formulas, &nur)
  2583. if err != nil {
  2584. logging.Error("GETNurJudge err: ", err)
  2585. msg := geterrmsg(err.Error())
  2586. appG.Response(http.StatusOK, e.ERROR, msg)
  2587. }
  2588. resf ,err := FeedproviderV2(parammaps,tx)
  2589. reslist := make([]map[string]interface{},22)
  2590. if len(resf)>1{
  2591. for key, _ := range resf[0] {
  2592. println(key)
  2593. str,sort :=switchname(key)
  2594. res := make(map[string]interface{},0)
  2595. res["standard"] = str
  2596. res["cowneed"] = resnur[key] // 奶牛需要
  2597. res["ftpro"] = resf[0][key] // 配方提供
  2598. res["hprov"] = resf[1][key] // tmr料
  2599. res["sprov"] = resf[2][key] //采食量
  2600. reslist[sort] = res
  2601. }
  2602. }
  2603. if err != nil {
  2604. logging.Error("GETNurJudge err: ", err)
  2605. msg := geterrmsg(err.Error())
  2606. appG.Response(http.StatusOK, e.ERROR, msg)
  2607. } else {
  2608. appG.Response(http.StatusOK, e.SUCCESS, reslist)
  2609. }
  2610. }
  2611. func GETNurJudgeRport(c *gin.Context) {
  2612. appG := app.Gin{C: c}
  2613. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2614. fsion := gofasion.NewFasion(string(dataByte))
  2615. nurstr := fsion.Get("parammaps").Json()
  2616. parammaps := make(map[string]interface{})
  2617. _ = json.Unmarshal([]byte(nurstr), &parammaps)
  2618. startTime,err := time.Parse("2006-01-02",parammaps["startTime"].(string))
  2619. if err != nil{
  2620. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2621. return
  2622. }
  2623. stopTime,err := time.Parse("2006-01-02",parammaps["stopTime"].(string))
  2624. if err != nil{
  2625. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2626. return
  2627. }
  2628. if stopTime.Sub(startTime)> 7*24*time.Hour{
  2629. appG.Response(http.StatusOK, e.ERROR, errors.New("日期范围过大"))
  2630. return
  2631. }
  2632. tx := restful.Engine.NewSession()
  2633. err = tx.Begin()
  2634. defer func() {
  2635. switch {
  2636. case err != nil:
  2637. fmt.Println("__error:", err)
  2638. if tx != nil {
  2639. tx.Rollback()
  2640. }
  2641. default:
  2642. if tx != nil {
  2643. err = tx.Commit()
  2644. }
  2645. }
  2646. if tx != nil {
  2647. tx.Close()
  2648. }
  2649. }()
  2650. //CulNurReportCow("getbmdetaillist",parammaps,tx)
  2651. res,err :=CulNurReportFT(parammaps,tx)
  2652. if err != nil {
  2653. logging.Error("GETNurJudgeRport err: ", err)
  2654. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2655. msg := geterrmsg(err.Error())
  2656. appG.Response(http.StatusOK, e.ERROR, msg)
  2657. } else {
  2658. appG.Response(http.StatusOK, e.SUCCESS, res)
  2659. }
  2660. }
  2661. func CulNurReportCow( sqlname string,parammaps map[string]interface{} , tx *xorm.Session)(map[string]interface{},error) {
  2662. var nur Nur
  2663. sql, p := restful.GetSqlByNameDBT(sqlname, tx)
  2664. s_params := make([]interface{}, 0)
  2665. paramslist := strings.Split(p, ",")
  2666. if len(paramslist) > 0 && p != "" {
  2667. for _, value := range paramslist {
  2668. s_params = append(s_params,parammaps[strings.Trim(value, " ")])
  2669. }
  2670. }
  2671. res,err :=tx.SQL(sql,s_params...).Query().List()
  2672. if len(res)>0{
  2673. resstr,_ :=json.Marshal(res[0])
  2674. err =json.Unmarshal(resstr,&nur)
  2675. if err != nil {
  2676. return nil ,err
  2677. }
  2678. }
  2679. formulas, _ := tx.SQL("select * from tb_formula_d where cowclass = ? and if (?='',''='', nutrition=? ) ORDER BY nutrition", nur.Bigcowclass, nur.Source, nur.Source).Query().List()
  2680. println(len(formulas))
  2681. resnur, err := CalNUR(formulas, &nur)
  2682. if err != nil {
  2683. return nil ,err
  2684. }
  2685. return resnur ,err
  2686. }
  2687. func CulNurReportFT( parammaps map[string]interface{},tx *xorm.Session)(res []map[string]interface{},err error) {
  2688. 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",
  2689. parammaps["pastureid"],parammaps["startTime"] , parammaps["stopTime"],parammaps["ftid"]).Query().List()
  2690. println(parammaps["pastureid"].(string),parammaps["startTime"].(string) , parammaps["stopTime"].(string),parammaps["ftid"].(string))
  2691. if err != nil{
  2692. return nil ,err
  2693. }
  2694. bartem :=""
  2695. println("barids",len(barids))
  2696. dates := make([]string,0)
  2697. for key, value := range barids {
  2698. if key == 0{
  2699. bartem = value["barid"].(string)
  2700. parammaps["barid"] = value["barid"]
  2701. }
  2702. if bartem != value["barid"].(string)|| key==len(barids)-1 {
  2703. if key==len(barids)-1{
  2704. dates = append(dates,value["date"].(string))
  2705. }
  2706. parammaps["date"] = value["date"]
  2707. barres,err := FeedproviderV3(parammaps,dates,tx)
  2708. if err != nil{
  2709. return nil ,err
  2710. }
  2711. resnur,err := CulNurReportCow("getbmdetaillist",parammaps,tx)
  2712. if err != nil{
  2713. return nil ,err
  2714. }
  2715. restem := make(map[string]interface{},0)
  2716. for k, _ := range barres[0] {
  2717. println("wwwwwww",k)
  2718. restem["barid"] = value["barid"].(string)
  2719. restem["barname"] = value["barname"].(string)
  2720. restem["ccount"] = value["ccount"].(int64)
  2721. restem[k+"-nur"] = resnur[k]
  2722. restem[k+"-FT"] = barres[0][k]
  2723. restem[k+"-H"] = barres[1][k]
  2724. restem[k+"-S"] = barres[2][k]
  2725. }
  2726. res = append(res,restem)
  2727. if err != nil{
  2728. return nil ,err
  2729. }
  2730. bartem = value["barid"].(string)
  2731. dates = make([]string,0)
  2732. parammaps["barid"] = value["barid"]
  2733. }
  2734. dates = append(dates,value["date"].(string))
  2735. }
  2736. return res ,err
  2737. }
  2738. func switchname( str string) (string,int){
  2739. tstr := ""
  2740. sort := 0
  2741. switch str {
  2742. case "dry":
  2743. tstr = "干物质(kg)"
  2744. sort = 0
  2745. case "nm":
  2746. tstr = "产奶净能(MJ)"
  2747. sort = 1
  2748. case "nuint":
  2749. tstr = "奶牛能量单位(NND)"
  2750. sort = 2
  2751. case "cp":
  2752. tstr = "粗蛋白(g)"
  2753. sort = 3
  2754. case "ca":
  2755. tstr = " 钙(g)"
  2756. sort = 4
  2757. case "p":
  2758. tstr = "磷(g)"
  2759. sort = 5
  2760. case "nmd":
  2761. tstr = "产奶净能(MCal/DM)"
  2762. sort = 6
  2763. case "cpd":
  2764. tstr = "粗蛋白(%DM)"
  2765. sort = 7
  2766. case "fat":
  2767. tstr = "脂肪"
  2768. sort = 8
  2769. case "starch":
  2770. tstr = "淀粉"
  2771. sort = 9
  2772. case "ndf":
  2773. tstr = "NDF(%DM)"
  2774. sort = 10
  2775. case "cndf":
  2776. tstr = "粗料中的NDF(%DM)"
  2777. sort = 11
  2778. case "adf":
  2779. tstr = "ADF(%DM)"
  2780. sort = 12
  2781. case "cad":
  2782. tstr = " 钙(%DM)"
  2783. sort = 13
  2784. case "pd":
  2785. tstr = "磷(%DM)"
  2786. sort = 14
  2787. case "trans35f":
  2788. tstr = "(3.5)饲料转化效率(kg/DM)"
  2789. sort = 15
  2790. case "trans4f":
  2791. tstr = "(4.0)饲料转化效率(kg/DM)"
  2792. sort = 16
  2793. case "jcrate":
  2794. tstr = "精粗比"
  2795. sort = 17
  2796. case "uprice":
  2797. tstr = "日粮成本(元)"
  2798. sort = 18
  2799. case "upriced":
  2800. tstr = "干物质成本(元/公斤)"
  2801. sort = 19
  2802. case "kprice":
  2803. tstr = "公斤奶成本(元) "
  2804. sort = 20
  2805. default:
  2806. tstr = str
  2807. sort = 21
  2808. }
  2809. return tstr,sort
  2810. }
  2811. func FeedproviderV2(parammaps map[string]interface{}, tx *xorm.Session)([]map[string]float64,error){
  2812. startTime,err := time.Parse("2006-01-02",parammaps["startTime"].(string))
  2813. if err != nil{
  2814. return nil,err
  2815. }
  2816. stopTime,err := time.Parse("2006-01-02",parammaps["stopTime"].(string))
  2817. if err != nil{
  2818. return nil,err
  2819. }
  2820. if stopTime.Sub(startTime)> 7*24*time.Hour{
  2821. return nil,errors.New("日期范围过大")
  2822. }
  2823. dates :=make([]string,0)
  2824. for stopTime.Sub(startTime)>=0{
  2825. dates =append(dates,startTime.Format("2006-01-02"))
  2826. startTime = startTime.Add(24*time.Hour)
  2827. }
  2828. resall,err :=FeedproviderV3(parammaps,dates,tx)
  2829. return resall,err
  2830. }
  2831. func FeedproviderV3(parammaps map[string]interface{},dates []string, tx *xorm.Session)([]map[string]float64,error){
  2832. res := make(map[string]float64,0)
  2833. resH := make(map[string]float64,0)
  2834. resS := make(map[string]float64,0)
  2835. i :=0
  2836. for _, date := range dates {
  2837. i++
  2838. println(date)
  2839. parammaps["date"] = date
  2840. restem,err := Feedprovider(parammaps,tx)
  2841. if err != nil{
  2842. return nil,err
  2843. }
  2844. restemSH,err := SHprovider(parammaps,tx)
  2845. if err != nil{
  2846. return nil,err
  2847. }
  2848. var h,s float64
  2849. if len(restemSH) >1 {
  2850. h,_ =strconv.ParseFloat(restemSH[0]["actualweightminus"].(string),64)
  2851. s,_ =strconv.ParseFloat(restemSH[1]["actualweightminus"].(string),64)
  2852. }
  2853. if len(restem)>0{
  2854. b,_ :=strconv.ParseFloat(restem[0]["jcrate"].(string),64)
  2855. res["jcrate"] = res["jcrate"]+b
  2856. resH["jcrate"] = resH["jcrate"]+ h*b
  2857. resS["jcrate"] = resS["jcrate"]+ s*b
  2858. b,_ =strconv.ParseFloat(restem[0]["cpd"].(string),64)
  2859. res["cpd"] = res["cpd"]+b
  2860. resH["cpd"] = resH["cpd"]+ h*b
  2861. resS["cpd"] = resS["cpd"]+ s*b
  2862. b,_ =strconv.ParseFloat(restem[0]["adf"].(string),64)
  2863. res["adf"] = res["adf"]+b
  2864. resH["adf"] = resH["adf"]+ h*b
  2865. resS["adf"] = resS["adf"]+ s*b
  2866. b,_ =strconv.ParseFloat(restem[0]["ca"].(string),64)
  2867. res["ca"] = res["ca"]+b
  2868. resH["ca"] = resH["ca"]+ h*b
  2869. resS["ca"] = resS["ca"]+ s*b
  2870. b,_ =strconv.ParseFloat(restem[0]["cad"].(string),64)
  2871. res["cad"] = res["cad"]+b
  2872. resH["cad"] = resH["cad"]+ h*b
  2873. resS["cad"] = resS["cad"]+ s*b
  2874. b,_ =strconv.ParseFloat(restem[0]["cdry"].(string),64)
  2875. res["cdry"] = res["cdry"]+b
  2876. resH["cdry"] = resH["cdry"]+ h*b
  2877. resS["cdry"] = resS["cdry"]+ s*b
  2878. b,_ =strconv.ParseFloat(restem[0]["cndf"].(string),64)
  2879. res["cndf"] = res["cndf"]+b
  2880. resH["cndf"] = resH["cndf"]+ h*b
  2881. resS["cndf"] = resS["cndf"]+ s*b
  2882. b,_ =strconv.ParseFloat(restem[0]["cp"].(string),64)
  2883. res["cp"] = res["cp"]+b
  2884. resH["cp"] = resH["cp"]+ h*b
  2885. resS["cp"] = resS["cp"]+ s*b
  2886. b,_ =strconv.ParseFloat(restem[0]["dry"].(string),64)
  2887. res["dry"] = res["dry"]+b
  2888. resH["dry"] = resH["dry"]+ h*b
  2889. resS["dry"] = resS["dry"]+ s*b
  2890. b,_ =strconv.ParseFloat(restem[0]["fat"].(string),64)
  2891. res["fat"] = res["fat"]+b
  2892. resH["fat"] = resH["fat"]+ h*b
  2893. resS["fat"] = resS["fat"]+ s*b
  2894. b,_ =strconv.ParseFloat(restem[0]["kprice"].(string),64)
  2895. res["kprice"] = res["kprice"]+b
  2896. resH["kprice"] = resH["kprice"]+ h*b
  2897. resS["kprice"] = resS["kprice"]+ s*b
  2898. b,_ =strconv.ParseFloat(restem[0]["nm"].(string),64)
  2899. res["nm"] = res["nm"]+b
  2900. resH["nm"] = resH["nm"]+ h*b
  2901. resS["nm"] = resS["nm"]+ s*b
  2902. b,_ =strconv.ParseFloat(restem[0]["ndf"].(string),64)
  2903. res["ndf"] = res["ndf"]+b
  2904. resH["ndf"] = resH["ndf"]+ h*b
  2905. resS["ndf"] = resS["ndf"]+ s*b
  2906. b,_ =strconv.ParseFloat(restem[0]["nm"].(string),64)
  2907. res["nm"] = res["nm"]+b
  2908. resH["nm"] = resH["nm"]+ h*b
  2909. resS["nm"] = resS["nm"]+ s*b
  2910. b,_ =strconv.ParseFloat(restem[0]["nmd"].(string),64)
  2911. res["nmd"] = res["nmd"]+b
  2912. resH["nmd"] = resH["nmd"]+ h*b
  2913. resS["nmd"] = resS["nmd"]+ s*b
  2914. b,_ =strconv.ParseFloat(restem[0]["nuint"].(string),64)
  2915. res["nuint"] = res["nuint"]+b
  2916. resH["nuint"] = resH["nuint"]+ h*b
  2917. resS["nuint"] = resS["nuint"]+ s*b
  2918. b,_ =strconv.ParseFloat(restem[0]["p"].(string),64)
  2919. res["p"] = res["p"]+b
  2920. resH["p"] = resH["p"]+ h*b
  2921. resS["p"] = resS["p"]+ s*b
  2922. b,_ =strconv.ParseFloat(restem[0]["pd"].(string),64)
  2923. res["pd"] = res["pd"]+b
  2924. resH["pd"] = resH["pd"]+ h*b
  2925. resS["pd"] = resS["pd"]+ s*b
  2926. b,_ =strconv.ParseFloat(restem[0]["starch"].(string),64)
  2927. res["starch"] = res["starch"]+b
  2928. resH["starch"] = resH["starch"]+ h*b
  2929. resS["starch"] = resS["starch"]+ s*b
  2930. b,_ =strconv.ParseFloat(restem[0]["trans4f"].(string),64)
  2931. res["trans4f"] = res["trans4f"]+b
  2932. resH["trans4f"] = resH["trans4f"]+ h*b
  2933. resS["trans4f"] = resS["trans4f"]+ s*b
  2934. b,_ =strconv.ParseFloat(restem[0]["trans35f"].(string),64)
  2935. res["trans35f"] = res["trans35f"]+b
  2936. resH["trans35f"] = resH["trans35f"]+ h*b
  2937. resS["trans35f"] = resS["trans35f"]+ s*b
  2938. b,_ =strconv.ParseFloat(restem[0]["uprice"].(string),64)
  2939. res["uprice"] = res["uprice"]+b
  2940. resH["uprice"] = resH["uprice"]+ h*b
  2941. resS["uprice"] = resS["uprice"]+ s*b
  2942. b,_ =strconv.ParseFloat(restem[0]["upriced"].(string),64)
  2943. res["upriced"] = res["upriced"]+b
  2944. resH["upriced"] = resH["upriced"]+ h*b
  2945. resS["upriced"] = resS["upriced"]+ s*b
  2946. }
  2947. }
  2948. for key, _ := range res {
  2949. resf,_ := strconv.ParseFloat(fmt.Sprintf("%.3f", res[key]/float64(i)), 64)
  2950. resHf,_ := strconv.ParseFloat(fmt.Sprintf("%.3f", resH[key]/float64(i)), 64)
  2951. resSf,_ := strconv.ParseFloat(fmt.Sprintf("%.3f", resS[key]/float64(i)), 64)
  2952. res[key] = resf
  2953. resH[key] = resHf
  2954. resS[key] = resSf
  2955. }
  2956. resAll := make([]map[string]float64,0)
  2957. resAll = append(resAll,res,resH,resS)
  2958. return resAll ,nil
  2959. }
  2960. func Feedprovider(parammaps map[string]interface{}, tx *xorm.Session)([]map[string]interface{},error) {
  2961. sql, p := restful.GetSqlByNameDBT(parammaps["name"].(string), tx)
  2962. s_params := make([]interface{}, 0)
  2963. paramslist := strings.Split(p, ",")
  2964. if len(paramslist) > 0 && p != "" {
  2965. for _, value := range paramslist {
  2966. s_params = append(s_params, parammaps[strings.Trim(value, " ")])
  2967. }
  2968. }
  2969. res ,err :=tx.SQL(sql,s_params...).Query().List()
  2970. return res ,err
  2971. }
  2972. func SHprovider(parammaps map[string]interface{}, tx *xorm.Session)([]map[string]interface{},error) {
  2973. sql, p := restful.GetSqlByNameDBT(parammaps["name1"].(string), tx)
  2974. //println(parammaps["name1"].(string),sql)
  2975. s_params := make([]interface{}, 0)
  2976. paramslist := strings.Split(p, ",")
  2977. if len(paramslist) > 0 && p != "" {
  2978. for _, value := range paramslist {
  2979. s_params = append(s_params, parammaps[strings.Trim(value, " ")])
  2980. }
  2981. }
  2982. res ,err :=tx.SQL(sql,s_params...).Query().List()
  2983. return res ,err
  2984. }
  2985. func CalNUR(formulas []map[string]interface{}, nur *Nur) (map[string]interface{}, error) {
  2986. //formulaADF := make([]map[string]interface{},1)//ADF
  2987. //formulaNDF := make([]map[string]interface{},1)//NDF
  2988. //formulaNFC := make([]map[string]interface{},1)//NFC
  2989. //formulacprotedm := make([]map[string]interface{},1)//小肠可消化粗蛋白
  2990. //formuladry := make([]map[string]interface{},1) //干物质
  2991. //formulastarch := make([]map[string]interface{},1)//淀粉
  2992. //formulap := make([]map[string]interface{},1)//磷
  2993. //formulacNDF := make([]map[string]interface{},1)//粗料中的NDF %DM
  2994. //formulajcrate := make([]map[string]interface{},1)//粗料比例
  2995. //formulacprote := make([]map[string]interface{},1)//粗蛋白
  2996. //formulaenergy := make([]map[string]interface{},1)//能量
  2997. //formulafat := make([]map[string]interface{},1)//脂肪
  2998. //formulaga := make([]map[string]interface{},1)//钙
  2999. //formulafeedrate := make([]map[string]interface{},1)//饲料转化效率,标准乳/干物质4.0
  3000. //formulafeed35rate := make([]map[string]interface{},1)//饲料转化效率,标准乳/干物质3.5
  3001. resmap := make(map[string]float64)
  3002. resmapstr := make(map[string]string)
  3003. resAll := make(map[string]interface{})
  3004. for _, formula := range formulas {
  3005. if formula["type"].(int64) == 0 {
  3006. resmapstr[formula["note"].(string)] = formula["formula"].(string)
  3007. continue
  3008. }
  3009. res, err := PraseFormula(formula["formula"].(string), nur)
  3010. if err != nil {
  3011. logging.Error("PraseFormula err", err.Error(), formula["nutrition"].(string))
  3012. println("PraseFormula err", err.Error(), formula["nutrition"].(string))
  3013. }
  3014. switch res.(type) {
  3015. case string:
  3016. resmapstr[formula["note"].(string)] = res.(string)
  3017. case float64, int, float32, int64, int32, int16, int8:
  3018. var rest float64
  3019. switch res.(type) {
  3020. case float64:
  3021. rest = res.(float64)
  3022. case int:
  3023. rest = float64(res.(int))
  3024. case int64:
  3025. rest = float64(res.(int64))
  3026. case int32:
  3027. rest = float64(res.(int32))
  3028. case int16:
  3029. rest = float64(res.(int16))
  3030. case int8:
  3031. rest = float64(res.(int8))
  3032. }
  3033. //fmt.Printf("==============oo %+v %+v %+v\n", res,rest,formula["nutrition"].(string))
  3034. switch formula["nutrition"].(string) {
  3035. case "ADF %DM":
  3036. resmap["adf"] = resmap["adf"] + rest
  3037. case "NDF %DM":
  3038. resmap["ndf"] = resmap["ndf"] + rest
  3039. case "NFC %DM":
  3040. resmap["nfc"] = resmap["nfc"] + rest
  3041. //case "小肠可消化粗蛋白":
  3042. // resmap["cprotedm"] = resmap["cprotedm"] + rest
  3043. case "干物质":
  3044. resmap["dry"] = resmap["dry"] + rest
  3045. case "淀粉":
  3046. resmap["starch"] = resmap["starch"] + rest
  3047. case "磷":
  3048. resmap["p"] = resmap["p"] + rest
  3049. case "粗料中的NDF %DM":
  3050. resmap["cndf"] = resmap["cndf"] + rest
  3051. case "粗料比例":
  3052. resmap["jcrate"] = resmap["jcrate"] + rest
  3053. case "粗蛋白":
  3054. resmap["cp"] = resmap["cp"] + rest
  3055. case "能量":
  3056. resmap["nm"] = resmap["nm"] + rest
  3057. case "脂肪":
  3058. resmap["fat"] = resmap["fat"] + rest
  3059. case "钙":
  3060. resmap["ca"] = resmap["ca"] + rest
  3061. case "饲料转化效率,标准乳/干物质":
  3062. resmap["trans4f"] = resmap["trans4f"] + rest
  3063. case "饲料转化效率,标准乳/干物质3.5":
  3064. resmap["trans35f"] = resmap["trans35f"] + rest
  3065. }
  3066. default:
  3067. fmt.Printf("===============%T \n", res)
  3068. }
  3069. }
  3070. if resmap["dry"] == 0 { //粗蛋白%dm = 粗蛋白/干物质
  3071. resmap["cpd"] = 0
  3072. resmap["cad"] = 0
  3073. resmap["pd"] = 0
  3074. resmap["nuint"] = 0
  3075. resmap["nmd"] = 0
  3076. } else {
  3077. resmap["cpd"] = resmap["cp"] / resmap["dry"] / 10
  3078. resmap["cad"] = resmap["ca"] / resmap["dry"] / 10
  3079. resmap["pd"] = resmap["p"] / resmap["dry"] / 10
  3080. resmap["nuint"] = resmap["nm"]/3.138
  3081. resmap["nmd"] = resmap["nm"]*0.2389/resmap["dry"]
  3082. }
  3083. for key, value := range resmap {
  3084. va, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", value), 64)
  3085. resAll[key] = va
  3086. }
  3087. for key, value := range resmapstr {
  3088. //println(key, value)
  3089. resAll[key] = value
  3090. }
  3091. return resAll, nil
  3092. }
  3093. func PraseFormula(formula string, nur *Nur) (interface{}, error) {
  3094. str := formula
  3095. str = strings.ReplaceAll(str, "日增重", strconv.FormatFloat(nur.Dayw, 'f', -1, 64))
  3096. //str = strings.ReplaceAll(str, "体重", nur.Bw)
  3097. str = strings.ReplaceAll(str, "怀孕天数", strconv.FormatFloat(nur.Dayspre, 'f', -1, 64))
  3098. str = strings.ReplaceAll(str, "产量", strconv.FormatFloat(nur.Product, 'f', -1, 64))
  3099. str = strings.ReplaceAll(str, "乳脂率", strconv.FormatFloat(nur.Fat, 'f', -1, 64))
  3100. str = strings.ReplaceAll(str, "乳蛋白率", strconv.FormatFloat(nur.Pro, 'f', -1, 64))
  3101. str = strings.ReplaceAll(str, "乳糖率", strconv.FormatFloat(nur.Lactose, 'f', -1, 64))
  3102. str = strings.ReplaceAll(str, "标准乳", strconv.FormatFloat(0.35*nur.Product+15*nur.Fat/100*nur.Product, 'f', -1, 64)) // 3.5乳脂率
  3103. //str = strings.ReplaceAll(str, "标准乳", strconv.FormatFloat(0.35*nur.Product+18.57*nur.Fat/100*nur.Product, 'f', -1, 64))
  3104. //println("标准乳--",strconv.FormatFloat(0.4*nur.Product+15*nur.Fat/100*nur.Product, 'f', -1, 64))
  3105. str = strings.ReplaceAll(str, "泌乳天数", strconv.FormatFloat(nur.Avgdim, 'f', -1, 64))
  3106. str = strings.ReplaceAll(str, "月龄", strconv.FormatFloat(nur.Avgmonthage, 'f', -1, 64))
  3107. str = strings.ReplaceAll(str, "温度", strconv.FormatFloat(nur.Tem, 'f', -1, 64))
  3108. str = strings.ReplaceAll(str, "胎次", strconv.FormatFloat(nur.Fetal, 'f', -1, 64))
  3109. str = strings.ReplaceAll(str, "体重", strconv.FormatFloat(nur.Bw, 'f', -1, 64))
  3110. str = strings.ReplaceAll(str, "Math.pow", "Mathpow")
  3111. str = strings.ReplaceAll(str, "Math.round", "Mathround")
  3112. str = strings.ReplaceAll(str, "Math.log", "Mathlog")
  3113. str = strings.ReplaceAll(str, "Math.exp", "Mathexp")
  3114. //str := "(体重>200?4.2/0.55*Math.pow(体重,0.75):3.5/0.55*Math.pow(体重,0.75))"
  3115. functions := map[string]govaluate.ExpressionFunction{
  3116. "strlen": func(args ...interface{}) (interface{}, error) {
  3117. length := len(args[0].(string))
  3118. return (float64)(length), nil
  3119. },
  3120. "Mathpow": func(args ...interface{}) (interface{}, error) {
  3121. c := math.Pow(args[0].(float64), args[1].(float64))
  3122. return (float64)(c), nil
  3123. },
  3124. "Mathround": func(args ...interface{}) (interface{}, error) {
  3125. c := math.Round(args[0].(float64))
  3126. return (float64)(c), nil
  3127. },
  3128. "Mathlog": func(args ...interface{}) (interface{}, error) {
  3129. c := math.Log(args[0].(float64))
  3130. return (float64)(c), nil
  3131. },
  3132. "Mathexp": func(args ...interface{}) (interface{}, error) {
  3133. c := math.Exp(args[0].(float64))
  3134. return (float64)(c), nil
  3135. },
  3136. }
  3137. expression, err := govaluate.NewEvaluableExpressionWithFunctions(str, functions)
  3138. if err != nil {
  3139. return 0, err
  3140. }
  3141. //fmt.Printf("== %+v\n", str)
  3142. result, err := expression.Evaluate(nil)
  3143. //fmt.Printf("== %+v\n", result)
  3144. if err != nil || result == nil {
  3145. return 0, err
  3146. }
  3147. return result, err
  3148. }