5ab44ae39599269b82642e6c460b12aa001ebd67.svn-base 129 KB

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