0052e6c3d82c2d49d5500407db470ccedd6af556.svn-base 127 KB

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