40d06b53e305043a1dc9c4b27c880b64542d1a00.svn-base 116 KB

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