2d667c7e0bc06c5b347db53f7ba79036ecf033f2.svn-base 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208
  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. entry := make(map[string]interface{})
  2540. outentry := make(map[string]interface{})
  2541. for j, colCell := range rows[0] {
  2542. for k, colCell1 := range row {
  2543. if j == k {
  2544. outentry[colCell] = colCell1
  2545. entry[colCell] = colCell1
  2546. }
  2547. }
  2548. }
  2549. inputdata = ""
  2550. a := ""
  2551. for _, v := range dateParamslist {
  2552. if v == ""{
  2553. continue
  2554. }
  2555. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2556. dtime,err := TransfTime(d.(string))
  2557. if err != nil {
  2558. a = strings.Trim(v, " ")
  2559. break
  2560. }
  2561. outentry[strings.Trim(v, " ")] = dtime
  2562. }
  2563. }
  2564. if a != "" {
  2565. outentry["error_msg"] = a + " 格式错误"
  2566. error++
  2567. queryData = append(queryData, outentry)
  2568. continue
  2569. }
  2570. a = ""
  2571. for _, v := range requiredParamslist {
  2572. if v == ""{
  2573. continue
  2574. }
  2575. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2576. a = strings.Trim(v, " ")
  2577. break
  2578. }
  2579. }
  2580. if a != "" {
  2581. outentry["error_msg"] = a + " 未填或格式错误"
  2582. error++
  2583. queryData = append(queryData, outentry)
  2584. continue
  2585. }
  2586. a = ""
  2587. for _, v := range numParamslist {
  2588. if v == ""{
  2589. continue
  2590. }
  2591. d, ok := outentry[strings.Trim(v, " ")]
  2592. if !ok || d == "" {
  2593. outentry[strings.Trim(v, " ")] = 0
  2594. }else {
  2595. var fl float64
  2596. switch d.(type) {
  2597. case string :
  2598. fl,err = strconv.ParseFloat(d.(string),64)
  2599. }
  2600. if err != nil || fl<0 {
  2601. a = strings.Trim(v, " ")
  2602. break
  2603. }
  2604. }
  2605. }
  2606. if a != "" {
  2607. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2608. error++
  2609. queryData = append(queryData, outentry)
  2610. continue
  2611. }
  2612. tx := restful.Engine.NewSession()
  2613. err := tx.Begin()
  2614. for _, sqlnamestr := range sqlslist {
  2615. sql, paramslists := restful.GetSqlByNameDB(sqlnamestr)
  2616. paramslist := strings.Split(paramslists, ",")
  2617. if len(paramslist) > 0 {
  2618. s_params := make([]interface{}, 0)
  2619. for _, value := range paramslist {
  2620. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2621. if tempv, exists := c.Get("jwt_username"); exists {
  2622. s_params = append(s_params, tempv.(string))
  2623. } else {
  2624. s_params = append(s_params, "")
  2625. }
  2626. }else if strings.ToLower(strings.Trim(value, " ")) == "pastureid"{
  2627. s_params = append(s_params, pastureid)
  2628. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2629. ids, err := setting.SnowIds.NextId()
  2630. if err != nil {
  2631. ids = time.Now().UnixNano()
  2632. logging.Info("create SnowIds err", err)
  2633. }
  2634. s_params = append(s_params, ids)
  2635. }else {
  2636. if outentry[strings.Trim(value, " ")] == nil {
  2637. s_params = append(s_params,"")
  2638. }else{
  2639. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2640. }
  2641. }
  2642. }
  2643. //fmt.Println("================",s_params)
  2644. outentry["input"] = inputdata
  2645. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2646. if err != nil {
  2647. if tx != nil {
  2648. tx.Rollback()
  2649. }
  2650. if tx != nil {
  2651. tx.Close()
  2652. }
  2653. msg := geterrmsg(err.Error())
  2654. outentry["error_msg"] = msg
  2655. error++
  2656. queryData = append(queryData, outentry)
  2657. isdone = true
  2658. break
  2659. } else{
  2660. if len(returnmsgmap1) > 0 {
  2661. if va,ok :=returnmsgmap1[0]["msg"] ; ok && va != "" {
  2662. if tx != nil {
  2663. tx.Rollback()
  2664. }
  2665. if tx != nil {
  2666. tx.Close()
  2667. }
  2668. msg := geterrmsg(va.(string))
  2669. outentry["error_msg"] = msg
  2670. error++
  2671. queryData = append(queryData, outentry)
  2672. isdone = true
  2673. break
  2674. }
  2675. }
  2676. isdone = false
  2677. }
  2678. }
  2679. }
  2680. switch {
  2681. case err != nil:
  2682. if tx != nil {
  2683. tx.Rollback()
  2684. }
  2685. default:
  2686. if tx != nil {
  2687. err = tx.Commit()
  2688. }
  2689. }
  2690. if tx != nil {
  2691. tx.Close()
  2692. }
  2693. }
  2694. if !isdone{
  2695. ok++
  2696. isdone = true
  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` = ? GROUP BY fp.`barid` 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 || key == 0{
  3285. if key == len(barids)-1 || key == 0{
  3286. dates = append(dates, value["date"].(string))
  3287. }
  3288. parammaps["date"] = value["date"]
  3289. parammaps["barid"] = value["barid"]
  3290. barres, err := FeedproviderV3(parammaps, dates, tx)
  3291. if err != nil {
  3292. return nil, err
  3293. }
  3294. resnur, err := CulNurReportCow("getbmdetaillist", parammaps, tx)
  3295. if err != nil {
  3296. return nil, err
  3297. }
  3298. restem := make(map[string]interface{}, 0)
  3299. for k, _ := range barres[0] {
  3300. //println("wwwwwww",k)
  3301. restem["barid"] = value["barid"].(string)
  3302. restem["barname"] = value["barname"].(string)
  3303. restem["ccount"] = value["ccount"].(int64)
  3304. restem[k+"-nur"] = resnur[k]
  3305. restem[k+"-FT"] = barres[0][k]
  3306. restem[k+"-H"] = barres[1][k]
  3307. restem[k+"-S"] = barres[2][k]
  3308. }
  3309. res = append(res, restem)
  3310. if err != nil {
  3311. return nil, err
  3312. }
  3313. bartem = value["barid"].(string)
  3314. dates = make([]string, 0)
  3315. parammaps["barid"] = value["barid"]
  3316. }
  3317. dates = append(dates, value["date"].(string))
  3318. }
  3319. return res, err
  3320. }
  3321. func switchname(str string) (string, int) {
  3322. tstr := ""
  3323. sort := 0
  3324. switch str {
  3325. case "dry":
  3326. tstr = "干物质(kg)"
  3327. sort = 0
  3328. case "nm":
  3329. tstr = "产奶净能(MJ)"
  3330. sort = 1
  3331. case "nuint":
  3332. tstr = "奶牛能量单位(NND)"
  3333. sort = 2
  3334. case "cp":
  3335. tstr = "粗蛋白(g)"
  3336. sort = 3
  3337. case "ca":
  3338. tstr = " 钙(g)"
  3339. sort = 4
  3340. case "p":
  3341. tstr = "磷(g)"
  3342. sort = 5
  3343. case "nmd":
  3344. tstr = "产奶净能(MCal/DM)"
  3345. sort = 6
  3346. case "cpd":
  3347. tstr = "粗蛋白(%DM)"
  3348. sort = 7
  3349. case "fat":
  3350. tstr = "脂肪"
  3351. sort = 8
  3352. case "starch":
  3353. tstr = "淀粉"
  3354. sort = 9
  3355. case "ndf":
  3356. tstr = "NDF(%DM)"
  3357. sort = 10
  3358. case "cndf":
  3359. tstr = "粗料中的NDF(%DM)"
  3360. sort = 11
  3361. case "adf":
  3362. tstr = "ADF(%DM)"
  3363. sort = 12
  3364. case "cad":
  3365. tstr = " 钙(%DM)"
  3366. sort = 13
  3367. case "pd":
  3368. tstr = "磷(%DM)"
  3369. sort = 14
  3370. case "trans35f":
  3371. tstr = "(3.5)饲料转化效率(kg/DM)"
  3372. sort = 15
  3373. case "trans4f":
  3374. tstr = "(4.0)饲料转化效率(kg/DM)"
  3375. sort = 16
  3376. case "jcrate":
  3377. tstr = "精粗比"
  3378. sort = 17
  3379. case "uprice":
  3380. tstr = "日粮成本(元)"
  3381. sort = 18
  3382. case "upriced":
  3383. tstr = "干物质成本(元/公斤)"
  3384. sort = 19
  3385. case "kprice":
  3386. tstr = "公斤奶成本(元) "
  3387. sort = 20
  3388. default:
  3389. tstr = str
  3390. sort = 21
  3391. }
  3392. return tstr, sort
  3393. }
  3394. func FeedproviderV2(parammaps map[string]interface{}, tx *xorm.Session) ([]map[string]float64, error) {
  3395. startTime, err := time.Parse("2006-01-02", parammaps["startTime"].(string))
  3396. if err != nil {
  3397. return nil, err
  3398. }
  3399. stopTime, err := time.Parse("2006-01-02", parammaps["stopTime"].(string))
  3400. if err != nil {
  3401. return nil, err
  3402. }
  3403. if stopTime.Sub(startTime) > 31*24*time.Hour {
  3404. return nil, errors.New("日期范围过大")
  3405. }
  3406. dates := make([]string, 0)
  3407. for stopTime.Sub(startTime) >= 0 {
  3408. dates = append(dates, startTime.Format("2006-01-02"))
  3409. startTime = startTime.Add(24 * time.Hour)
  3410. }
  3411. resall, err := FeedproviderV3(parammaps, dates, tx)
  3412. return resall, err
  3413. }
  3414. func FeedproviderV3(parammaps map[string]interface{}, dates []string, tx *xorm.Session) ([]map[string]float64, error) {
  3415. res := make(map[string]float64, 0)
  3416. resH := make(map[string]float64, 0)
  3417. resS := make(map[string]float64, 0)
  3418. i := 0
  3419. for _, date := range dates {
  3420. i++
  3421. //println(date)
  3422. parammaps["date"] = date
  3423. restem, err := Feedprovider(parammaps, tx)
  3424. if err != nil {
  3425. return nil, err
  3426. }
  3427. restemSH, err := SHprovider(parammaps, tx)
  3428. if err != nil {
  3429. return nil, err
  3430. }
  3431. var h, s float64
  3432. if len(restemSH) > 1 {
  3433. switch restemSH[0]["actualweightminus"].(type) {
  3434. case string:
  3435. h, _ = strconv.ParseFloat(restemSH[0]["actualweightminus"].(string), 64)
  3436. }
  3437. switch restemSH[1]["actualweightminus"].(type) {
  3438. case string:
  3439. s, _ = strconv.ParseFloat(restemSH[1]["actualweightminus"].(string), 64)
  3440. }
  3441. }
  3442. if len(restem) > 0 {
  3443. b, _ := strconv.ParseFloat(restem[0]["jcrate"].(string), 64)
  3444. res["jcrate"] = res["jcrate"] + b
  3445. resH["jcrate"] = resH["jcrate"] + h*b
  3446. resS["jcrate"] = resS["jcrate"] + s*b
  3447. b, _ = strconv.ParseFloat(restem[0]["cpd"].(string), 64)
  3448. res["cpd"] = res["cpd"] + b
  3449. resH["cpd"] = resH["cpd"] + h*b
  3450. resS["cpd"] = resS["cpd"] + s*b
  3451. b, _ = strconv.ParseFloat(restem[0]["adf"].(string), 64)
  3452. res["adf"] = res["adf"] + b
  3453. resH["adf"] = resH["adf"] + h*b
  3454. resS["adf"] = resS["adf"] + s*b
  3455. b, _ = strconv.ParseFloat(restem[0]["ca"].(string), 64)
  3456. res["ca"] = res["ca"] + b
  3457. resH["ca"] = resH["ca"] + h*b
  3458. resS["ca"] = resS["ca"] + s*b
  3459. b, _ = strconv.ParseFloat(restem[0]["cad"].(string), 64)
  3460. res["cad"] = res["cad"] + b
  3461. resH["cad"] = resH["cad"] + h*b
  3462. resS["cad"] = resS["cad"] + s*b
  3463. //b,_ =strconv.ParseFloat(restem[0]["cdry"].(string),64)
  3464. //res["cdry"] = res["cdry"]+b
  3465. //
  3466. //resH["cdry"] = resH["cdry"]+ h*b
  3467. //resS["cdry"] = resS["cdry"]+ s*b
  3468. b, _ = strconv.ParseFloat(restem[0]["cndf"].(string), 64)
  3469. res["cndf"] = res["cndf"] + b
  3470. resH["cndf"] = resH["cndf"] + h*b
  3471. resS["cndf"] = resS["cndf"] + s*b
  3472. b, _ = strconv.ParseFloat(restem[0]["cp"].(string), 64)
  3473. res["cp"] = res["cp"] + b
  3474. resH["cp"] = resH["cp"] + h*b
  3475. resS["cp"] = resS["cp"] + s*b
  3476. b, _ = strconv.ParseFloat(restem[0]["dry"].(string), 64)
  3477. res["dry"] = res["dry"] + b
  3478. resH["dry"] = resH["dry"] + h*b
  3479. resS["dry"] = resS["dry"] + s*b
  3480. b, _ = strconv.ParseFloat(restem[0]["fat"].(string), 64)
  3481. res["fat"] = res["fat"] + b
  3482. resH["fat"] = resH["fat"] + h*b
  3483. resS["fat"] = resS["fat"] + s*b
  3484. b, _ = strconv.ParseFloat(restem[0]["kprice"].(string), 64)
  3485. res["kprice"] = res["kprice"] + b
  3486. resH["kprice"] = resH["kprice"] + h*b
  3487. resS["kprice"] = resS["kprice"] + s*b
  3488. b, _ = strconv.ParseFloat(restem[0]["nm"].(string), 64)
  3489. res["nm"] = res["nm"] + b
  3490. resH["nm"] = resH["nm"] + h*b
  3491. resS["nm"] = resS["nm"] + s*b
  3492. b, _ = strconv.ParseFloat(restem[0]["ndf"].(string), 64)
  3493. res["ndf"] = res["ndf"] + b
  3494. resH["ndf"] = resH["ndf"] + h*b
  3495. resS["ndf"] = resS["ndf"] + s*b
  3496. b, _ = strconv.ParseFloat(restem[0]["nm"].(string), 64)
  3497. res["nm"] = res["nm"] + b
  3498. resH["nm"] = resH["nm"] + h*b
  3499. resS["nm"] = resS["nm"] + s*b
  3500. b, _ = strconv.ParseFloat(restem[0]["nmd"].(string), 64)
  3501. res["nmd"] = res["nmd"] + b
  3502. resH["nmd"] = resH["nmd"] + h*b
  3503. resS["nmd"] = resS["nmd"] + s*b
  3504. b, _ = strconv.ParseFloat(restem[0]["nuint"].(string), 64)
  3505. res["nuint"] = res["nuint"] + b
  3506. resH["nuint"] = resH["nuint"] + h*b
  3507. resS["nuint"] = resS["nuint"] + s*b
  3508. b, _ = strconv.ParseFloat(restem[0]["p"].(string), 64)
  3509. res["p"] = res["p"] + b
  3510. resH["p"] = resH["p"] + h*b
  3511. resS["p"] = resS["p"] + s*b
  3512. b, _ = strconv.ParseFloat(restem[0]["pd"].(string), 64)
  3513. res["pd"] = res["pd"] + b
  3514. resH["pd"] = resH["pd"] + h*b
  3515. resS["pd"] = resS["pd"] + s*b
  3516. b, _ = strconv.ParseFloat(restem[0]["starch"].(string), 64)
  3517. res["starch"] = res["starch"] + b
  3518. resH["starch"] = resH["starch"] + h*b
  3519. resS["starch"] = resS["starch"] + s*b
  3520. b, _ = strconv.ParseFloat(restem[0]["trans4f"].(string), 64)
  3521. res["trans4f"] = res["trans4f"] + b
  3522. resH["trans4f"] = resH["trans4f"] + h*b
  3523. resS["trans4f"] = resS["trans4f"] + s*b
  3524. b, _ = strconv.ParseFloat(restem[0]["trans35f"].(string), 64)
  3525. res["trans35f"] = res["trans35f"] + b
  3526. resH["trans35f"] = resH["trans35f"] + h*b
  3527. resS["trans35f"] = resS["trans35f"] + s*b
  3528. b, _ = strconv.ParseFloat(restem[0]["uprice"].(string), 64)
  3529. res["uprice"] = res["uprice"] + b
  3530. resH["uprice"] = resH["uprice"] + h*b
  3531. resS["uprice"] = resS["uprice"] + s*b
  3532. b, _ = strconv.ParseFloat(restem[0]["upriced"].(string), 64)
  3533. res["upriced"] = res["upriced"] + b
  3534. resH["upriced"] = resH["upriced"] + h*b
  3535. resS["upriced"] = resS["upriced"] + s*b
  3536. }
  3537. }
  3538. for key, _ := range res {
  3539. resf, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", res[key]/float64(i)), 64)
  3540. resHf, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", resH[key]/float64(i)), 64)
  3541. resSf, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", resS[key]/float64(i)), 64)
  3542. res[key] = resf
  3543. resH[key] = resHf
  3544. resS[key] = resSf
  3545. }
  3546. resAll := make([]map[string]float64, 0)
  3547. resAll = append(resAll, res, resH, resS)
  3548. return resAll, nil
  3549. }
  3550. func Feedprovider(parammaps map[string]interface{}, tx *xorm.Session) ([]map[string]interface{}, error) {
  3551. sql, p := restful.GetSqlByNameDBT(parammaps["name"].(string), tx)
  3552. s_params := make([]interface{}, 0)
  3553. paramslist := strings.Split(p, ",")
  3554. if len(paramslist) > 0 && p != "" {
  3555. for _, value := range paramslist {
  3556. s_params = append(s_params, parammaps[strings.Trim(value, " ")])
  3557. }
  3558. }
  3559. res, err := tx.SQL(sql, s_params...).Query().List()
  3560. return res, err
  3561. }
  3562. func SHprovider(parammaps map[string]interface{}, tx *xorm.Session) ([]map[string]interface{}, error) {
  3563. sql, p := restful.GetSqlByNameDBT(parammaps["name1"].(string), tx)
  3564. //println(parammaps["name1"].(string),sql)
  3565. s_params := make([]interface{}, 0)
  3566. paramslist := strings.Split(p, ",")
  3567. if len(paramslist) > 0 && p != "" {
  3568. for _, value := range paramslist {
  3569. s_params = append(s_params, parammaps[strings.Trim(value, " ")])
  3570. }
  3571. }
  3572. res, err := tx.SQL(sql, s_params...).Query().List()
  3573. return res, err
  3574. }
  3575. func CalNUR(formulas []map[string]interface{}, nur *Nur) (map[string]interface{}, error) {
  3576. //formulaADF := make([]map[string]interface{},1)//ADF
  3577. //formulaNDF := make([]map[string]interface{},1)//NDF
  3578. //formulaNFC := make([]map[string]interface{},1)//NFC
  3579. //formulacprotedm := make([]map[string]interface{},1)//小肠可消化粗蛋白
  3580. //formuladry := make([]map[string]interface{},1) //干物质
  3581. //formulastarch := make([]map[string]interface{},1)//淀粉
  3582. //formulap := make([]map[string]interface{},1)//磷
  3583. //formulacNDF := make([]map[string]interface{},1)//粗料中的NDF %DM
  3584. //formulajcrate := make([]map[string]interface{},1)//粗料比例
  3585. //formulacprote := make([]map[string]interface{},1)//粗蛋白
  3586. //formulaenergy := make([]map[string]interface{},1)//能量
  3587. //formulafat := make([]map[string]interface{},1)//脂肪
  3588. //formulaga := make([]map[string]interface{},1)//钙
  3589. //formulafeedrate := make([]map[string]interface{},1)//饲料转化效率,标准乳/干物质4.0
  3590. //formulafeed35rate := make([]map[string]interface{},1)//饲料转化效率,标准乳/干物质3.5
  3591. resmap := make(map[string]float64)
  3592. resmapstr := make(map[string]string)
  3593. resAll := make(map[string]interface{})
  3594. for _, formula := range formulas {
  3595. if formula["type"].(int64) == 0 {
  3596. resmapstr[formula["note"].(string)] = formula["formula"].(string)
  3597. continue
  3598. }
  3599. res, err := PraseFormula(formula["formula"].(string), nur)
  3600. if err != nil {
  3601. logging.Error("PraseFormula err", err.Error(), formula["nutrition"].(string))
  3602. //println("PraseFormula err", err.Error(), formula["nutrition"].(string))
  3603. }
  3604. switch res.(type) {
  3605. case string:
  3606. resmapstr[formula["note"].(string)] = res.(string)
  3607. case float64, int, float32, int64, int32, int16, int8:
  3608. var rest float64
  3609. switch res.(type) {
  3610. case float64:
  3611. rest = res.(float64)
  3612. case int:
  3613. rest = float64(res.(int))
  3614. case int64:
  3615. rest = float64(res.(int64))
  3616. case int32:
  3617. rest = float64(res.(int32))
  3618. case int16:
  3619. rest = float64(res.(int16))
  3620. case int8:
  3621. rest = float64(res.(int8))
  3622. }
  3623. //fmt.Printf("==============oo %+v %+v %+v\n", res,rest,formula["nutrition"].(string))
  3624. switch formula["nutrition"].(string) {
  3625. case "ADF %DM":
  3626. resmap["adf"] = resmap["adf"] + rest
  3627. case "NDF %DM":
  3628. resmap["ndf"] = resmap["ndf"] + rest
  3629. case "NFC %DM":
  3630. resmap["nfc"] = resmap["nfc"] + rest
  3631. //case "小肠可消化粗蛋白":
  3632. // resmap["cprotedm"] = resmap["cprotedm"] + rest
  3633. case "干物质":
  3634. resmap["dry"] = resmap["dry"] + rest
  3635. case "淀粉":
  3636. resmap["starch"] = resmap["starch"] + rest
  3637. case "磷":
  3638. resmap["p"] = resmap["p"] + rest
  3639. case "粗料中的NDF %DM":
  3640. resmap["cndf"] = resmap["cndf"] + rest
  3641. case "粗料比例":
  3642. resmap["jcrate"] = resmap["jcrate"] + rest
  3643. case "粗蛋白":
  3644. resmap["cp"] = resmap["cp"] + rest
  3645. case "能量":
  3646. resmap["nm"] = resmap["nm"] + rest
  3647. case "脂肪":
  3648. resmap["fat"] = resmap["fat"] + rest
  3649. case "钙":
  3650. resmap["ca"] = resmap["ca"] + rest
  3651. case "饲料转化效率,标准乳/干物质":
  3652. resmap["trans4f"] = resmap["trans4f"] + rest
  3653. case "饲料转化效率,标准乳/干物质3.5":
  3654. resmap["trans35f"] = resmap["trans35f"] + rest
  3655. }
  3656. default:
  3657. fmt.Printf("===============%T \n", res)
  3658. }
  3659. }
  3660. if resmap["dry"] == 0 { //粗蛋白%dm = 粗蛋白/干物质
  3661. resmap["cpd"] = 0
  3662. resmap["cad"] = 0
  3663. resmap["pd"] = 0
  3664. resmap["nuint"] = 0
  3665. resmap["nmd"] = 0
  3666. } else {
  3667. resmap["cpd"] = resmap["cp"] / resmap["dry"] / 10
  3668. resmap["cad"] = resmap["ca"] / resmap["dry"] / 10
  3669. resmap["pd"] = resmap["p"] / resmap["dry"] / 10
  3670. resmap["nuint"] = resmap["nm"] / 3.138
  3671. resmap["nmd"] = resmap["nm"] * 0.2389 / resmap["dry"]
  3672. }
  3673. for key, value := range resmap {
  3674. va, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", value), 64)
  3675. resAll[key] = va
  3676. }
  3677. for key, value := range resmapstr {
  3678. //println(key, value)
  3679. resAll[key] = value
  3680. }
  3681. resAll["uprice"] = ""
  3682. resAll["upriced"] = ""
  3683. resAll["kprice"] = ""
  3684. return resAll, nil
  3685. }
  3686. func PraseFormula(formula string, nur *Nur) (interface{}, error) {
  3687. str := formula
  3688. str = strings.ReplaceAll(str, "日增重", strconv.FormatFloat(nur.Dayw, 'f', -1, 64))
  3689. //str = strings.ReplaceAll(str, "体重", nur.Bw)
  3690. str = strings.ReplaceAll(str, "怀孕天数", strconv.FormatFloat(nur.Dayspre, 'f', -1, 64))
  3691. str = strings.ReplaceAll(str, "产量", strconv.FormatFloat(nur.Product, 'f', -1, 64))
  3692. str = strings.ReplaceAll(str, "乳脂率", strconv.FormatFloat(nur.Fat, 'f', -1, 64))
  3693. str = strings.ReplaceAll(str, "乳蛋白率", strconv.FormatFloat(nur.Pro, 'f', -1, 64))
  3694. str = strings.ReplaceAll(str, "乳糖率", strconv.FormatFloat(nur.Lactose, 'f', -1, 64))
  3695. str = strings.ReplaceAll(str, "标准乳", strconv.FormatFloat(0.35*nur.Product+15*nur.Fat/100*nur.Product, 'f', -1, 64)) // 3.5乳脂率
  3696. //str = strings.ReplaceAll(str, "标准乳", strconv.FormatFloat(0.35*nur.Product+18.57*nur.Fat/100*nur.Product, 'f', -1, 64))
  3697. //println("标准乳--",strconv.FormatFloat(0.4*nur.Product+15*nur.Fat/100*nur.Product, 'f', -1, 64))
  3698. str = strings.ReplaceAll(str, "泌乳天数", strconv.FormatFloat(nur.Avgdim, 'f', -1, 64))
  3699. str = strings.ReplaceAll(str, "月龄", strconv.FormatFloat(nur.Avgmonthage, 'f', -1, 64))
  3700. str = strings.ReplaceAll(str, "温度", strconv.FormatFloat(nur.Tem, 'f', -1, 64))
  3701. str = strings.ReplaceAll(str, "胎次", strconv.FormatFloat(nur.Fetal, 'f', -1, 64))
  3702. str = strings.ReplaceAll(str, "体重", strconv.FormatFloat(nur.Bw, 'f', -1, 64))
  3703. str = strings.ReplaceAll(str, "Math.pow", "Mathpow")
  3704. str = strings.ReplaceAll(str, "Math.round", "Mathround")
  3705. str = strings.ReplaceAll(str, "Math.log", "Mathlog")
  3706. str = strings.ReplaceAll(str, "Math.exp", "Mathexp")
  3707. //str := "(体重>200?4.2/0.55*Math.pow(体重,0.75):3.5/0.55*Math.pow(体重,0.75))"
  3708. functions := map[string]govaluate.ExpressionFunction{
  3709. "strlen": func(args ...interface{}) (interface{}, error) {
  3710. length := len(args[0].(string))
  3711. return (float64)(length), nil
  3712. },
  3713. "Mathpow": func(args ...interface{}) (interface{}, error) {
  3714. c := math.Pow(args[0].(float64), args[1].(float64))
  3715. return (float64)(c), nil
  3716. },
  3717. "Mathround": func(args ...interface{}) (interface{}, error) {
  3718. c := math.Round(args[0].(float64))
  3719. return (float64)(c), nil
  3720. },
  3721. "Mathlog": func(args ...interface{}) (interface{}, error) {
  3722. c := math.Log(args[0].(float64))
  3723. return (float64)(c), nil
  3724. },
  3725. "Mathexp": func(args ...interface{}) (interface{}, error) {
  3726. c := math.Exp(args[0].(float64))
  3727. return (float64)(c), nil
  3728. },
  3729. }
  3730. expression, err := govaluate.NewEvaluableExpressionWithFunctions(str, functions)
  3731. if err != nil {
  3732. return 0, err
  3733. }
  3734. //fmt.Printf("== %+v\n", str)
  3735. result, err := expression.Evaluate(nil)
  3736. //fmt.Printf("== %+v\n", result)
  3737. if err != nil || result == nil {
  3738. return 0, err
  3739. }
  3740. return result, err
  3741. }
  3742. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  3743. fsion := gofasion.NewFasion(parammaps)
  3744. sqlnamestr := fsion.Get("name").ValueStr()
  3745. sqlnamestr1 := fsion.Get("name1").ValueStr()
  3746. offset := fsion.Get("offset").ValueDefaultInt(0)
  3747. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3748. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3749. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3750. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  3751. body := []byte("")
  3752. if sql != "" {
  3753. s_params := make([]interface{}, 0)
  3754. if fsion.HasKey("parammaps") {
  3755. parammaps := fsion.Get("parammaps")
  3756. paramslist := strings.Split(p, ",")
  3757. if len(paramslist) > 0 && p != "" {
  3758. for _, value := range paramslist {
  3759. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3760. }
  3761. }
  3762. }
  3763. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3764. if err != nil {
  3765. } else {
  3766. paramslist1 := strings.Split(p1, ",")
  3767. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  3768. s_params1 := make([]interface{}, 0)
  3769. if len(paramslist1) > 0 && p1 != "" {
  3770. for _, v := range paramslist1 {
  3771. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  3772. }
  3773. }
  3774. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  3775. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  3776. body, _ = json.Marshal(queryData)
  3777. }
  3778. }
  3779. }
  3780. bs := bytes.NewBuffer(body)
  3781. client := &http.Client{}
  3782. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  3783. req, err := http.NewRequest(RequestMethod,
  3784. url,
  3785. bs,
  3786. )
  3787. if err != nil {
  3788. }
  3789. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  3790. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  3791. if err != nil {
  3792. // handle error
  3793. }
  3794. resp, err := client.Do(req)
  3795. if err != nil {
  3796. fmt.Println(err)
  3797. return ""
  3798. }
  3799. defer resp.Body.Close()
  3800. result_body, err := ioutil.ReadAll(resp.Body)
  3801. if err != nil {
  3802. fmt.Println(err)
  3803. return ""
  3804. }
  3805. fmt.Println(string(result_body))
  3806. return ""
  3807. }