12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373 |
- package api
- import (
- "../../pkg/app"
- "../../pkg/e"
- "../../pkg/logging"
- "../../pkg/setting"
- "../../routers/restful"
- "bytes"
- "database/sql"
- "encoding/json"
- "errors"
- "fmt"
- "github.com/360EntSecGroup-Skylar/excelize"
- "github.com/Anderson-Lu/gofasion/gofasion"
- "github.com/Knetic/govaluate"
- "github.com/gin-gonic/gin"
- "github.com/tealeg/xlsx"
- "github.com/xormplus/xorm"
- "io/ioutil"
- "math"
- "net/http"
- "os"
- "path"
- "regexp"
- "sort"
- "strconv"
- "strings"
- "time"
- )
- // @Summary 根据SQL执行得到数据集
- // @Tags getData
- // @Accept json
- // @Produce json
- // @Param sql query string true "sql"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/getdata [POST]
- func GetData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlstr := fsion.Get("sql").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- func Testpartitions(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
- user := fsion.Get("user").ValueStr() //获取新数据库用户
- passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
- host := fsion.Get("host").ValueStr() //获取新数据库名称
- port := fsion.Get("port").ValueStr() //获取新数据库名称
- sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
- if sqls == nil || err1 != nil {
- appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
- }
- sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
- connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
- mydb, err := sql.Open("mysql", connecting) //连接新连接
- if err != nil {
- println("err1", err.Error())
- }
- _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
- if err != nil {
- println("err2", err.Error())
- }
- mydb.Close()
- connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
- mydb, err = sql.Open("mysql", connecting)
- if err != nil {
- println("err3", err.Error())
- }
- defer mydb.Close()
- if err == nil {
- mydb.SetMaxOpenConns(10)
- mydb.SetMaxIdleConns(10)
- }
- errmsg := ""
- if err == nil {
- //tx ,_ :=mydb.Begin()
- for _, sqlstr := range sqlstrs {
- //println("sqlstr---",sqlstr)
- if sqlstr == "" {
- continue
- }
- _, err = mydb.Exec(sqlstr)
- if err != nil {
- println("err4", err.Error())
- errmsg = err.Error()
- //err1 :=tx.Rollback()
- }
- }
- //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
- //err =tx.Commit()
- }
- if errmsg == "" {
- appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
- }
- }
- func TestData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlstr := fsion.Get("sql").ValueStr()
- token := ""
- if tempv, exists := c.Get("jwt_username"); exists {
- token = tempv.(string)
- }
- appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByName
- // @Accept json
- // @Produce json
- // @Param sqlname body string true "sqlname"
- // @Param offset body int true "offset"
- // @Param pagecount body int true "pagecount"
- // @Param returntype body string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByName [POST]
- func GetDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- //fmt.Println("sql========\n",sqlnamestr,sql)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- //fmt.Printf("%v+\n",queryData)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func GetDataBySqlIN(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- //fmt.Println("sql========\n",sqlnamestr,sql)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- //fmt.Printf("%v+\n",queryData)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func geterrmsg(errstr string) (msgstr string) {
- var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
- rs := []rune(errstr)
- if hzRegexp.MatchString(string(rs[0])) {
- msgstr = errstr
- return
- }
- if strings.Contains(errstr, "Duplicate entry") {
- strs := strings.Split(errstr, ` key '`)
- if len(strs) > 1 {
- if len(strs[len(strs)-1]) > 1 {
- errstr = "Duplicate entry :" + strs[len(strs)-1]
- }
- }
- }
- msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
- if err != nil {
- msgstr = errstr
- return
- }
- if msg == nil || len(msg) == 0 {
- var param []interface{}
- param = append(param, errstr, errstr)
- go func() {
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
- if err != nil {
- logging.Error("insert into err_msg(err,msg) err", err)
- }
- }()
- msgstr = errstr
- } else {
- msgstr = msg[0]["msg"]
- }
- return
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname body json true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Param s formData json true "ss"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByNameForm [POST]
- func GetDataByNameForm(c *gin.Context) {
- appG := app.Gin{C: c}
- //sqlnamestr := c.PostForm("measureNumber")
- //dataByte, _ := ioutil.ReadAll(c.Request.Body)
- //fsion := gofasion.NewFasion(string(dataByte))
- //sqlnamestr := fsion.Get("name").ValueStr()
- //offset := fsion.Get("offset").ValueInt()
- //pagecount := fsion.Get("pagecount").ValueInt()
- //returntype := fsion.Get("returntype").ValueStr()
- //params := fsion.Get("params").Array()
- c.Request.ParseForm()
- params := c.Request.Form
- offset := 0
- pageSize_ := 0
- returntype := params.Get("page")
- if returntype == "" {
- returntype = "0"
- }
- if tempv, exists := c.Get("jwt_username"); exists {
- params.Set("JwtUserName", tempv.(string))
- } else {
- params.Set("JwtUserName", "")
- }
- sqlnamestr := params.Get("name")
- logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
- s_params := make([]interface{}, 0)
- if returntype == "1" {
- pageNum, error := strconv.Atoi(params.Get("pageNum"))
- if error != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
- }
- pageSize, error := strconv.Atoi(params.Get("pageSize"))
- if error != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
- }
- pageSize_ = pageSize
- offset = pageNum
- }
- sql, p := restful.GetSqlByNameDB(sqlnamestr)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, params.Get(strings.Trim(value, " ")))
- }
- }
- if sql != "" {
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- c.Header("Content-Type", "application/octet-stream")
- c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
- if err != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
- }
- }
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
- }
- }
- // @Summary 递归获取所有
- // @Tags menu
- // @Accept json
- // @Produce json
- // @Param Ton query string true "Ton"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Router /authdata/GetRoleMenus [GET]
- func GetRecuDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- parentidname := fsion.Get("idname").ValueStr()
- sql, p := restful.GetSqlByNameDB(sqlnamestr)
- params := make(map[string]interface{})
- s_params := make([]interface{}, 0)
- if fsion.HasKey("params") {
- for _, v_params := range fsion.Get("params").Array() {
- s_params = append(s_params, v_params.ValueStr())
- }
- params["params"] = s_params
- } else {
- jparams := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- params[value] = tempv.(string)
- } else {
- params[value] = ""
- }
- } else {
- params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
- }
- }
- }
- }
- queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
- logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags GetDataByNames
- // @Accept json
- // @Produce json
- // @RequestBody sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/GetDataByNames [POST]
- func GetDataByNames(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlParams := fsion.Array()
- queryData := make(map[string]interface{})
- for _, v := range sqlParams {
- fsion2 := gofasion.NewFasion(v.Json())
- logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
- sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
- if sql == "" {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = "sql没找到"
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- } else if sql != "" {
- offset := fsion2.Get("offset").ValueInt()
- pagecount := fsion2.Get("pagecount").ValueInt()
- returntype := fsion2.Get("returntype").ValueStr()
- s_params := make([]interface{}, 0)
- if fsion2.HasKey("parammaps") {
- parammaps := fsion2.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion2.HasKey("params") {
- params := fsion2.Get("params").Array()
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
- if err != nil {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = err.Error()
- queryData[fsion2.Get("name").ValueStr()] = errorm
- logging.Error("GetDataByNames err: ", err)
- continue
- } else {
- queryData[fsion2.Get("name").ValueStr()] = queryData1
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDataByNameForm
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByNameForm [POST]
- func PostDataByNameForm(c *gin.Context) {
- appG := app.Gin{C: c}
- c.Request.ParseForm()
- params := c.Request.Form
- sqlnamestr := params.Get("name")
- logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
- s_params := make([]interface{}, 0)
- sql, p := restful.GetSqlByNameDB(sqlnamestr)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 {
- for _, value := range paramslist {
- s_params = append(s_params, params.Get(strings.Trim(value, " ")))
- }
- }
- if sql != "" {
- queryData, err := execDataBySql(sql, s_params)
- if err != nil {
- appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
- }
- } else {
- appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
- }
- }
- func GetReportform(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- parammaps := fsion.Get("parammaps")
- logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- fmt.Println("__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- queryData, _ := praseReportform(sqlnamestr, parammaps, tx)
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- func praseReportform(sqlnamestr string, parammaps *gofasion.Fasion, tx *xorm.Session) (queryData map[string]interface{}, err error) {
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- s_params := make([]interface{}, 0)
- if sql != "" {
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- queryList, _ := tx.SQL(sql, s_params...).Query().List()
- temstr := ""
- switch sqlnamestr {
- case "getAccuracyAllHL", "getAccuracyAllQX", "getAccuracyAllJH", "getFeedEffMR", "getFeedEffHL", "getHomepageCB", "getAccuraa", "judgenurFTReportDetail":
- temstr = sqlnamestr
- default:
- temstr = sqlnamestr[:10]
- }
- switch temstr {
- case "getAccurac", "getFeedEff":
- queryData, err = getAccuracy(queryList) // 不定参数
- case "getprocess":
- //queryData, err = getAccuracyV3v1(queryList)
- queryData, err = getAccuracyV3(queryList)
- case "getHomepro":
- queryData, err = getAccuracyV3(queryList)
- case "getAccuracyAllHL", "getAccuracyAllQX", "getAccuracyAllJH", "getFeedEffMR", "getFeedEffHL", "getHomepageCB", "getAccuraa":
- queryData, err = getAccuracyV2(queryList) //固定维度 日期
- case "getMateria":
- queryData, err = getAccuracyV4(queryList)
- case "getPriceAn":
- queryData, err = getAccuracyV5(queryList)
- case "getJT1Accu":
- queryData, err = getAccuracyV6(queryList) //固定维度 牧场
- case "judgenurFT":
- queryData, err = getAccuracyV7(queryList)
- case "judgenurFTReportDetail":
- queryData, err = getAccuracyV8(queryList)
- default:
- queryData, err = nil, nil
- }
- return
- //switch sqlnamestr {
- //case "getAccuracyAllFT", "getAccuracyAllNQ", "getAccuracyAllCC", "getAccuracyAllLS","getFeedEffSL","getFeedEffZH","getFeedEffCB","getFeedEffCBLS","getFeedEffCBFT":
- // queryData, err = getAccuracy(queryList)
- //case "getprocessAnalysisTB","getHomeprocessAnalysis":
- // queryData, err = getAccuracyV3(queryList)
- //case "getAccuracyAllHL", "getAccuracyAllQX","getAccuracyAllJH","getFeedEffMR","getFeedEffHL","getHomepageCB":
- // queryData, err = getAccuracyV2(queryList)
- //default:
- // queryData, err = nil, nil
- //}
- //return
- }
- func getAccuracyV8(queryList []map[string]interface{}) (map[string]interface{}, error) {
- queryData := make(map[string]interface{})
- chartData := make(map[string]interface{})
- //list := make(map[string]interface{})
- data := []interface{}{}
- for i := 0; i < len(queryList); i++ {
- dry, _ := strconv.ParseFloat(queryList[i]["dry"].(string), 64)
- Hrate, _ := strconv.ParseFloat(queryList[i]["Hrate"].(string), 64)
- Srate, _ := strconv.ParseFloat(queryList[i]["Srate"].(string), 64)
- trans35f, _ := strconv.ParseFloat(queryList[i]["trans35f"].(string), 64)
- jcrate, _ := strconv.ParseFloat(queryList[i]["jcrate"].(string), 64)
- uprice, _ := strconv.ParseFloat(queryList[i]["uprice"].(string), 64)
- kprice, _ := strconv.ParseFloat(queryList[i]["dry"].(string), 64)
- adf, _ := strconv.ParseFloat(queryList[i]["adf"].(string), 64)
- ca, _ := strconv.ParseFloat(queryList[i]["ca"].(string), 64)
- cdry, _ := strconv.ParseFloat(queryList[i]["cdry"].(string), 64)
- cad, _ := strconv.ParseFloat(queryList[i]["cad"].(string), 64)
- cndf, _ := strconv.ParseFloat(queryList[i]["cndf"].(string), 64)
- cp, _ := strconv.ParseFloat(queryList[i]["cp"].(string), 64)
- cpd, _ := strconv.ParseFloat(queryList[i]["cpd"].(string), 64)
- fat, _ := strconv.ParseFloat(queryList[i]["fat"].(string), 64)
- ndf, _ := strconv.ParseFloat(queryList[i]["ndf"].(string), 64)
- nm, _ := strconv.ParseFloat(queryList[i]["nm"].(string), 64)
- nmd, _ := strconv.ParseFloat(queryList[i]["nmd"].(string), 64)
- nuint, _ := strconv.ParseFloat(queryList[i]["nuint"].(string), 64)
- p, _ := strconv.ParseFloat(queryList[i]["p"].(string), 64)
- pd, _ := strconv.ParseFloat(queryList[i]["pd"].(string), 64)
- starch, _ := strconv.ParseFloat(queryList[i]["starch"].(string), 64)
- trans4f, _ := strconv.ParseFloat(queryList[i]["trans4f"].(string), 64)
- list := make(map[string]interface{})
- list["ft"] = dry
- list["index"] = "干物质(kg)"
- list["tmr"] = TransFloat(dry * Hrate)
- list["cyl"] = TransFloat(dry * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = jcrate
- list["index"] = "粗精比(%)"
- list["tmr"] = TransFloat(jcrate * Hrate)
- list["cyl"] = TransFloat(jcrate * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = uprice
- list["index"] = "日粮成本(元)"
- list["tmr"] = TransFloat(uprice * Hrate)
- list["cyl"] = TransFloat(uprice * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = kprice
- list["index"] = "公斤奶成本"
- list["tmr"] = TransFloat(kprice * Hrate)
- list["cyl"] = TransFloat(kprice * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = cdry
- list["index"] = "粗料中的干物质"
- list["tmr"] = TransFloat(cdry * Hrate)
- list["cyl"] = TransFloat(cdry * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = nm
- list["index"] = " 产奶净能(MJ)"
- list["tmr"] = TransFloat(nm * Hrate)
- list["cyl"] = TransFloat(nm * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = nuint
- list["index"] = "奶牛能量单位(NND)"
- list["tmr"] = TransFloat(nuint * Hrate)
- list["cyl"] = TransFloat(nuint * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = cp
- list["index"] = "粗蛋白(g)"
- list["tmr"] = TransFloat(cp * Hrate)
- list["cyl"] = TransFloat(cp * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = cpd
- list["index"] = "粗蛋白(%DM)"
- list["tmr"] = TransFloat(cpd * Hrate)
- list["cyl"] = TransFloat(cpd * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = ca
- list["index"] = "钙(g)"
- list["tmr"] = TransFloat(ca * Hrate)
- list["cyl"] = TransFloat(ca * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = p
- list["index"] = "磷(g)"
- list["tmr"] = TransFloat(p * Hrate)
- list["cyl"] = TransFloat(p * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = nmd
- list["index"] = "产奶净能(Mcal/DM)"
- list["tmr"] = TransFloat(nmd * Hrate)
- list["cyl"] = TransFloat(nmd * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = fat
- list["index"] = "脂肪"
- list["tmr"] = TransFloat(fat * Hrate)
- list["cyl"] = TransFloat(fat * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = starch
- list["index"] = "淀粉"
- list["tmr"] = TransFloat(starch * Hrate)
- list["cyl"] = TransFloat(starch * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = ndf
- list["index"] = "NDF(%DM)"
- list["tmr"] = TransFloat(ndf * Hrate)
- list["cyl"] = TransFloat(ndf * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = cndf
- list["index"] = "粗料中的NDF(%DM)"
- list["tmr"] = TransFloat(cndf * Hrate)
- list["cyl"] = TransFloat(cndf * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = adf
- list["index"] = " ADF(%DM)"
- list["tmr"] = TransFloat(adf * Hrate)
- list["cyl"] = TransFloat(adf * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = cad
- list["index"] = "钙(%DM)"
- list["tmr"] = TransFloat(cad * Hrate)
- list["cyl"] = TransFloat(cad * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = pd
- list["index"] = " 磷(%DM)"
- list["tmr"] = TransFloat(pd * Hrate)
- list["cyl"] = TransFloat(pd * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = trans35f
- list["index"] = "(3.5)FCR(kg/DM)"
- list["tmr"] = TransFloat(trans35f * Hrate)
- list["cyl"] = TransFloat(trans35f * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["ft"] = trans4f
- list["index"] = "(4.0)FCR(kg/DM)"
- list["tmr"] = TransFloat(trans4f * Hrate)
- list["cyl"] = TransFloat(trans4f * Srate)
- data = append(data, list)
- }
- chartData["data"] = data
- queryData["list"] = chartData
- queryData["code"] = 0
- queryData["message"] = "ok"
- queryData["data"] = queryList
- return queryData, nil
- }
- func TransFloat(flo float64)(float64){
- hf,_ :=strconv.ParseFloat(fmt.Sprintf("%.3f", float64(flo)), 64)
- return hf
- }
- func getAccuracyV7(queryList []map[string]interface{}) (map[string]interface{}, error) {
- queryData := make(map[string]interface{})
- chartData := make(map[string]interface{})
- //list := make(map[string]interface{})
- data := []interface{}{}
- for i := 0; i < len(queryList); i++ {
- dry, _ := strconv.ParseFloat(queryList[i]["dry"].(string), 64)
- Hrate, _ := strconv.ParseFloat(queryList[i]["Hrate"].(string), 64)
- Srate, _ := strconv.ParseFloat(queryList[i]["Srate"].(string), 64)
- trans35f, _ := strconv.ParseFloat(queryList[i]["trans35f"].(string), 64)
- jcrate, _ := strconv.ParseFloat(queryList[i]["jcrate"].(string), 64)
- uprice, _ := strconv.ParseFloat(queryList[i]["uprice"].(string), 64)
- kprice, _ := strconv.ParseFloat(queryList[i]["dry"].(string), 64)
- list := make(map[string]interface{})
- list["tname"] = queryList[i]["tname"]
- list["ftid"] = queryList[i]["ftid"]
- list["ft"] = dry
- list["index"] = "干物质(kg)"
- list["tmr"] = TransFloat(dry * Hrate)
- list["cyl"] = TransFloat(dry * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["tname"] = queryList[i]["tname"]
- list["ftid"] = queryList[i]["ftid"]
- list["ft"] = trans35f
- list["index"] = "(3.5)FCR(kg/DM)"
- list["tmr"] = TransFloat(trans35f * Hrate)
- list["cyl"] = TransFloat(trans35f * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["tname"] = queryList[i]["tname"]
- list["ftid"] = queryList[i]["ftid"]
- list["ft"] = jcrate
- list["index"] = "粗精比(%)"
- list["tmr"] = TransFloat(jcrate * Hrate)
- list["cyl"] = TransFloat(jcrate * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["tname"] = queryList[i]["tname"]
- list["ftid"] = queryList[i]["ftid"]
- list["ft"] = uprice
- list["index"] = "日粮成本(元)"
- list["tmr"] = TransFloat(uprice * Hrate)
- list["cyl"] = TransFloat(uprice * Srate)
- data = append(data, list)
- list = make(map[string]interface{})
- list["tname"] = queryList[i]["tname"]
- list["ftid"] = queryList[i]["ftid"]
- list["ft"] = kprice
- list["index"] = "公斤奶成本"
- list["tmr"] = TransFloat(kprice * Hrate)
- list["cyl"] = TransFloat(kprice * Srate)
- data = append(data, list)
- }
- chartData["data"] = data
- queryData["list"] = chartData
- queryData["code"] = 0
- queryData["message"] = "ok"
- queryData["data"] = queryList
- return queryData, nil
- }
- func getAccuracyV6(queryList []map[string]interface{}) (map[string]interface{}, error) {
- queryData := make(map[string]interface{})
- chartData := make(map[string]interface{})
- data := []interface{}{}
- data1 := []interface{}{}
- data2 := []interface{}{}
- data3 := []interface{}{}
- data4 := []interface{}{}
- for i := 0; i < len(queryList); i++ {
- data = append(data, queryList[i]["牧场"])
- data1 = append(data1, queryList[i]["field1"])
- data2 = append(data2, queryList[i]["field2"])
- data3 = append(data3, queryList[i]["field3"])
- data4 = append(data4, queryList[i]["field4"])
- }
- chartData["data1"] = data
- chartData["data2"] = data1
- chartData["data3"] = data2
- chartData["data4"] = data3
- chartData["data5"] = data4
- queryData["list"] = chartData
- queryData["code"] = 0
- queryData["message"] = "ok"
- queryData["data"] = queryList
- return queryData, nil
- }
- func getAccuracyV5(queryList []map[string]interface{}) (map[string]interface{}, error) {
- queryData := make(map[string]interface{})
- chartData := make(map[string]interface{})
- datamap1 := make(map[string]interface{})
- datamap2 := make(map[string]interface{})
- temsmap := make(map[interface{}]interface{})
- mapc2 := make(map[interface{}]interface{})
- data3 := []interface{}{}
- datamap2child := make(map[string]interface{})
- data2 := []interface{}{}
- data1 := []interface{}{}
- var dtem interface{}
- var temstr interface{}
- var typestr interface{}
- count2 := 0
- a := 0
- for i := 0; i < len(queryList); i++ {
- if i == 0 {
- temstr = queryList[i]["fname"]
- typestr = queryList[i]["typestr"]
- }
- if temstr == queryList[i]["fname"] {
- temsmap[queryList[i]["feedname"]] = 1
- }
- if _, ok := mapc2[queryList[i]["feedname"]]; !ok {
- mapc2[queryList[i]["feedname"]] = count2
- mapc2[count2] = queryList[i]["feedname"]
- count2++
- }
- }
- //for i := 0; i<count2 ; i++ {
- // reslist := make([]map[string]interface{},1)
- // res := make(map[string]interface{})
- // res["fname"] = "分界线"
- // res["feedname"] = mapc2[i]
- // res["饲料名称"] = mapc2[i]
- // reslist[0] = res
- // queryList = append(reslist,queryList...)
- //}
- for i := 0; i < count2; i++ { // 将所有饲料种类新增为第一行 测试
- if _, ok := temsmap[mapc2[i]]; !ok {
- reslist := make([]map[string]interface{}, 1)
- res := make(map[string]interface{})
- res["fname"] = temstr
- res["feedname"] = mapc2[i]
- res["饲料名称"] = mapc2[i]
- res["typestr"] = typestr
- reslist[0] = res
- queryList = append(reslist, queryList...)
- }
- }
- for i := 0; i < len(queryList); i++ {
- a = mapc2[queryList[i]["feedname"]].(int) * 2
- if i == 0 {
- datamap2["label"] = "饲料名称"
- switch queryList[i]["typestr"].(type) {
- case string:
- datamap2child["label"] = queryList[i]["typestr"].(string) + "/饲料参数"
- default:
- datamap2child["label"] = "/饲料参数"
- }
- datamap2child["prop"] = "A"
- data3 = append(data3, datamap2child)
- datamap2["children"] = data3
- data2 = append(data2, datamap2)
- data3 = []interface{}{}
- datamap2child = make(map[string]interface{})
- datamap2 = make(map[string]interface{})
- dtem = queryList[i]["fname"]
- }
- if dtem != queryList[i]["fname"] && i != 0 {
- data1 = append(data1, datamap1)
- dtem = queryList[i]["fname"]
- datamap1 = make(map[string]interface{})
- }
- if queryList[i]["fname"] == temstr {
- datamap2["label"] = queryList[i]["feedname"]
- datamap2child["label"] = "理论"
- datamap2child["prop"] = "a" + strconv.Itoa(a)
- data3 = append(data3, datamap2child)
- datamap2child = make(map[string]interface{})
- datamap2child["label"] = "实际"
- datamap2child["prop"] = "a" + strconv.Itoa(a+1)
- data3 = append(data3, datamap2child)
- datamap2child = make(map[string]interface{})
- datamap2["children"] = data3
- data2 = append(data2, datamap2)
- data3 = []interface{}{}
- datamap2 = make(map[string]interface{})
- datamap2child = make(map[string]interface{})
- }
- datamap1["A"] = queryList[i]["fname"]
- datamap1["a"+strconv.Itoa(a)] = queryList[i]["lweight"]
- datamap1["a"+strconv.Itoa(a+1)] = queryList[i]["actualweightminus"]
- datamap2["label"] = queryList[i]["饲料名称"]
- a = a + 2
- }
- data1 = append(data1, datamap1)
- chartData["data1"] = data1
- chartData["data2"] = data2
- queryData["list"] = chartData
- queryData["code"] = 0
- queryData["message"] = "ok"
- queryData["data"] = queryList
- return queryData, nil
- }
- func getAccuracyV4(queryList []map[string]interface{}) (map[string]interface{}, error) {
- queryData := make(map[string]interface{})
- chartData := make(map[string]interface{})
- datamap1 := make(map[string]interface{})
- datamap2 := make(map[string]interface{})
- temsmap := make(map[interface{}]interface{})
- mapc2 := make(map[interface{}]interface{})
- mapc3 := make(map[interface{}]interface{})
- data3 := []interface{}{}
- datamap2child := make(map[string]interface{})
- data2 := []interface{}{}
- data1 := []interface{}{}
- a := 0
- var dtem interface{}
- count2 := 0
- var tem interface{}
- var temstr interface{}
- var typestr interface{}
- for i := 0; i < len(queryList); i++ { // 获取所有饲料种类
- if i == 0 {
- temstr = queryList[i]["fname"]
- typestr = queryList[i]["typestr"]
- }
- if temstr == queryList[i]["fname"] {
- temsmap[queryList[i]["feedname"]] = 1
- }
- if _, ok := mapc2[queryList[i]["feedname"]]; !ok {
- mapc2[queryList[i]["feedname"]] = count2 // 编号
- mapc2[count2] = queryList[i]["feedname"]
- count2++
- }
- }
- for i := 0; i < count2; i++ { // 将所有饲料种类新增为第一行 测试
- if _, ok := temsmap[mapc2[i]]; !ok {
- reslist := make([]map[string]interface{}, 1)
- res := make(map[string]interface{})
- res["fname"] = temstr
- res["feedname"] = mapc2[i]
- res["饲料名称"] = mapc2[i]
- res["typestr"] = typestr
- reslist[0] = res
- queryList = append(reslist, queryList...)
- }
- }
- //for i := 0; i<count2 ; i++ {
- // reslist := make([]map[string]interface{},1)
- // res := make(map[string]interface{})
- // res["fname"] = "分界线"
- // res["feedname"] = mapc2[i]
- // res["饲料名称"] = mapc2[i]
- // res["typestr"] =typestr
- // reslist[0] = res
- // queryList = append(reslist,queryList...)
- //}
- for i := 0; i < len(queryList); i++ {
- if i == 0 {
- tem = queryList[i]["fname"]
- }
- if queryList[i]["fname"] == tem {
- mapc3[queryList[i]["feedname"]] = i
- }
- }
- for i := 0; i < len(queryList); i++ {
- a = mapc2[queryList[i]["feedname"]].(int) * 4
- if i == 0 {
- datamap2["label"] = "饲料名称"
- switch queryList[i]["typestr"].(type) {
- case string:
- datamap2child["label"] = queryList[i]["typestr"].(string) + "/饲料参数"
- default:
- datamap2child["label"] = "/饲料参数"
- }
- datamap2child["prop"] = "A"
- data3 = append(data3, datamap2child)
- datamap2["children"] = data3
- data2 = append(data2, datamap2)
- data3 = []interface{}{}
- datamap2child = make(map[string]interface{})
- datamap2 = make(map[string]interface{})
- dtem = queryList[i]["fname"]
- }
- if dtem != queryList[i]["fname"] && i != 0 {
- data1 = append(data1, datamap1)
- dtem = queryList[i]["fname"]
- datamap1 = make(map[string]interface{})
- }
- if queryList[i]["fname"] == temstr {
- datamap2["label"] = queryList[i]["feedname"]
- datamap2child["label"] = "理论"
- datamap2child["prop"] = "a" + strconv.Itoa(a)
- data3 = append(data3, datamap2child)
- datamap2child = make(map[string]interface{})
- datamap2child["label"] = "实际"
- datamap2child["prop"] = "a" + strconv.Itoa(a+1)
- data3 = append(data3, datamap2child)
- datamap2child = make(map[string]interface{})
- datamap2child["label"] = "误差值"
- datamap2child["prop"] = "a" + strconv.Itoa(a+2)
- data3 = append(data3, datamap2child)
- datamap2child = make(map[string]interface{})
- datamap2child["label"] = "误差率"
- datamap2child["prop"] = "a" + strconv.Itoa(a+3)
- data3 = append(data3, datamap2child)
- datamap2["children"] = data3
- data2 = append(data2, datamap2)
- data3 = []interface{}{}
- datamap2 = make(map[string]interface{})
- datamap2child = make(map[string]interface{})
- }
- datamap1["A"] = queryList[i]["fname"]
- datamap1["a"+strconv.Itoa(a)] = queryList[i]["lweight"]
- datamap1["a"+strconv.Itoa(a+1)] = queryList[i]["actualweightminus"]
- datamap1["a"+strconv.Itoa(a+2)] = queryList[i]["diff"]
- datamap1["a"+strconv.Itoa(a+3)] = queryList[i]["diffrate"]
- datamap2["label"] = queryList[i]["饲料名称"]
- }
- data1 = append(data1, datamap1)
- chartData["data1"] = data1
- chartData["data2"] = data2
- queryData["list"] = chartData
- queryData["code"] = 0
- queryData["message"] = "ok"
- queryData["data"] = queryList
- return queryData, nil
- }
- func getAccuracyV3(queryList []map[string]interface{}) (map[string]interface{}, error) {
- queryData := make(map[string]interface{})
- chartData := make(map[string]interface{})
- data := []interface{}{}
- data1 := []interface{}{}
- data2 := []interface{}{}
- data3 := []interface{}{}
- data4 := []interface{}{}
- datatem := []interface{}{}
- t1 := make(map[interface{}]string, 0)
- for i := 0; i < len(queryList); i++ {
- data = append(data, queryList[i]["mtime"])
- data1 = append(data1, queryList[i]["lweight"])
- data2 = append(data2, queryList[i]["weight"])
- //data3 = append(data3, queryList[i]["field3"])
- //data4 = append(data4, queryList[i]["field4"])
- if _, ok := t1[queryList[i]["id"]]; !ok {
- datatem = append(datatem, queryList[i]["startstime"], queryList[i]["lastactualweight"])
- data3 = append(data3, datatem)
- datatem = []interface{}{}
- datatem = append(datatem, queryList[i]["intime"], queryList[i]["actualweight"])
- data3 = append(data3, datatem)
- datatem = []interface{}{}
- }
- t1[queryList[i]["id"]] = "1"
- }
- chartData["data1"] = data
- chartData["data2"] = data1
- chartData["data3"] = data2
- chartData["data4"] = data3
- chartData["data5"] = data4
- queryData["list"] = chartData
- queryData["code"] = 0
- queryData["message"] = "ok"
- queryData["data"] = queryList
- return queryData, nil
- }
- func getAccuracyV3v1(queryList []map[string]interface{}) (map[string]interface{}, error) {
- queryData := make(map[string]interface{})
- chartData := make(map[string]interface{})
- data := []interface{}{}
- data1 := []interface{}{}
- data2 := []interface{}{}
- data3 := []interface{}{}
- data4 := []interface{}{}
- datatem := []interface{}{}
- //t1 := make(map[interface{}]string, 0)
- jsonstr := ""
- jsonmap := make([]map[string]interface{},0)
- if len(queryList)>0{
- queryjsonList, _ := restful.Engine.SQL("select weightjson from recweightmuster where pid = ? and pastureid = ?" ,queryList[0]["pid"],queryList[0]["pastureid"]).Query().List()
- if len(queryjsonList)>0{
- jsonstr = queryjsonList[0]["weightjson"].(string)
- }
- }
- err := json.Unmarshal([]byte(jsonstr),&jsonmap)
- if err != nil{
- logging.Error("json.Unmarshal err",err)
- }
- for i := 0; i < len(queryList); i++ {
- datatem = append(datatem, queryList[i]["startstime"], queryList[i]["lastactualweight"])
- data3 = append(data3, datatem)
- datatem = []interface{}{}
- datatem = append(datatem, queryList[i]["intime"], queryList[i]["actualweight"])
- data3 = append(data3, datatem)
- datatem = []interface{}{}
- }
- j := 0
- for i := 0; i < len(jsonmap); i++ {
- if jsonmap[i]["mt"].(string)>queryList[j]["intime"].(string){
- if j < len(queryList)-1{
- j++
- }
- }
- data1 = append(data1, queryList[j]["lweight"])
- data = append(data, jsonmap[i]["mt"])
- data2 = append(data2, jsonmap[i]["w"])
- }
- chartData["data1"] = data
- chartData["data2"] = data1
- chartData["data3"] = data2
- chartData["data4"] = data3
- chartData["data5"] = data4
- queryData["list"] = chartData
- queryData["code"] = 0
- queryData["message"] = "ok"
- queryData["data"] = queryList
- return queryData, nil
- }
- func getAccuracyV2(queryList []map[string]interface{}) (map[string]interface{}, error) {
- queryData := make(map[string]interface{})
- chartData := make(map[string]interface{})
- data := []interface{}{}
- data1 := []interface{}{}
- data2 := []interface{}{}
- data3 := []interface{}{}
- data4 := []interface{}{}
- for i := 0; i < len(queryList); i++ {
- data = append(data, queryList[i]["日期"])
- data1 = append(data1, queryList[i]["field1"])
- data2 = append(data2, queryList[i]["field2"])
- data3 = append(data3, queryList[i]["field3"])
- data4 = append(data4, queryList[i]["field4"])
- }
- chartData["data1"] = data
- chartData["data2"] = data1
- chartData["data3"] = data2
- chartData["data4"] = data3
- chartData["data5"] = data4
- queryData["list"] = chartData
- queryData["code"] = 0
- queryData["message"] = "ok"
- queryData["data"] = queryList
- return queryData, nil
- }
- func getAccuracy(queryList []map[string]interface{}) (map[string]interface{}, error) {
- queryData := make(map[string]interface{})
- chartData := make(map[string]interface{})
- t1 := make(map[interface{}]interface{}, 0)
- t2 := make(map[interface{}]interface{}, 0)
- data := make(map[string][]interface{}, 0)
- t := make([]map[string][]interface{}, 0)
- e1 := []interface{}{}
- e2 := []string{}
- for _, value := range queryList {
- if _, ok := t1[value["名称"]]; !ok {
- e1 = append(e1, value["名称"])
- }
- if _, ok := t2[value["日期"]]; !ok {
- switch value["日期"].(type) {
- case string:
- e2 = append(e2, value["日期"].(string))
- }
- }
- t1[value["名称"]] = value["名称"]
- t2[value["日期"]] = value["日期"]
- }
- sort.Strings(e2)
- var b interface{}
- a := 0
- for i := 0; i < len(queryList); i++ {
- if i == 0 {
- b = queryList[i]["名称"]
- }
- if b != queryList[i]["名称"] {
- if a < len(e2)-1 {
- for k := 0; k < len(e2)-a; k++ {
- data["data"] = append(data["data"], "")
- }
- }
- t = append(t, data)
- data = make(map[string][]interface{}, 0)
- b = queryList[i]["名称"]
- a = 0
- }
- switch queryList[i]["日期"].(type) {
- case string:
- dates, _ := time.Parse("2006-01-02", queryList[i]["日期"].(string))
- dates1 := ""
- if a < len(e2) -1{
- dates1 = e2[a]
- }else {
- dates1 = e2[len(e2)-1]
- }
- if a < len(e2)-1 {
- if e2[a] != queryList[i]["日期"].(string) {
- if e2[a] < queryList[i]["日期"].(string) {
- dates1 = queryList[i]["日期"].(string)
- dates, _ = time.Parse("2006-01-02", e2[a])
- for ; a < len(e2)-1; a++ {
- if e2[a] >= queryList[i]["日期"].(string) {
- break
- }
- }
- }
- for ; dates.Format("2006-01-02") < dates1; dates = dates.Add(24 * time.Hour) {
- data["data"] = append(data["data"], "")
- }
- }
- }
- }
- data["data"] = append(data["data"], queryList[i]["准确率"])
- a++
- }
- if a < len(e2)-1 {
- for k := 0; k < len(e2)-a; k++ {
- data["data"] = append(data["data"], "")
- }
- }
- t = append(t, data)
- chartData["data1"] = e1
- chartData["data2"] = e2
- chartData["data3"] = t
- queryData["list"] = chartData
- queryData["code"] = 0
- queryData["message"] = "ok"
- queryData["data"] = queryList
- return queryData, nil
- }
- func GetUpkeepPlan(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- fmt.Println("__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- if v, ok := value["id"]; ok {
- //month = "2020-03"
- seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
- if seviceplans != nil {
- for _, va := range seviceplans { //根据保养计划获取保养单
- //day,_ :=strconv.Atoi(va["day"])
- bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
- //buk := make(map[string]map[string]string)
- for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
- jstr := ""
- if bu["plantime"][8:9] == "0" {
- jstr = "m" + bu["plantime"][9:]
- } else {
- jstr = "m" + bu["plantime"][8:]
- }
- if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
- } else {
- if bu["flowCompeleted"] >= "2" {
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
- } else {
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
- }
- }
- }
- }
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func GetArrList(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- fmt.Println("__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func GetRJSBData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("plancount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- fmt.Println("__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func GetAccount(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- //fmt.Println("sql========\n",sqlnamestr,sql)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- }
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- if returntype == "xlsx" {
- var xlsxfile *xlsx.File
- xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
- //c.File("c:/dd.xlsx")
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = xlsxfile.Write(c.Writer)
- } else {
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- logging.Error("GetDataByName err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDataByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func PostDataByName(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- s_params := make([]interface{}, 0)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- fmt.Println("__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- if sql != "" {
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion.HasKey("params") {
- params := fsion.Get("params").Array()
- logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
- //ids,err := setting.SnowIds.NextId()
- //if err !=nil{
- // ids = time.Now().UnixNano()
- // logging.Info("create SnowIds err",err)
- //}
- //s_params = append(s_params, ids)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- queryData, err := execDataBySqlT(sql, s_params, tx)
- if err != nil {
- logging.Error("PostDataByName err: ", err)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- func PostRJSBData(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- s_params := make([]interface{}, 0)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- fmt.Println("__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
- if !fsion.HasKey("parammaps") {
- appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- return
- }
- parammaps := fsion.Get("parammaps")
- // ==========================1========================
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql, s_params...).Execute()
- if err != nil {
- fmt.Println(err)
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- // ==========================2========================
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- // ==========================3========================
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- // ==========================4========================
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- func PostRJSBDatas(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsions := gofasion.NewFasion(string(dataByte)).Array()
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- fmt.Println("__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
- sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
- sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
- sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
- for _, fsion := range fsions {
- if !fsion.HasKey("parammaps") {
- appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
- return
- }
- parammaps := fsion.Get("parammaps")
- s_params := make([]interface{}, 0)
- // ==========================1========================
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- fmt.Println("}}}}}}}}}}}}}}}}}}}",s_params)
- _, err = tx.SQL(sql, s_params...).Execute()
- if err != nil {
- fmt.Println(err)
- logging.Error("PostRJSBData err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- // ==========================2========================
- s_params = make([]interface{}, 0)
- paramslist = strings.Split(p1, ",")
- if len(paramslist) > 0 && p1 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql1, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData1 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- // ==========================3========================
- paramslist = strings.Split(p2, ",")
- if len(paramslist) > 0 && p2 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql2, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData2 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- s_params = make([]interface{}, 0)
- // ==========================4========================
- paramslist = strings.Split(p3, ",")
- if len(paramslist) > 0 && p3 != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- _, err = tx.SQL(sql3, s_params...).Execute()
- if err != nil {
- logging.Error("PostRJSBData3 err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- return
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, "ok")
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags ExecDataByConfig
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func ExecDataByConfig(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- tempval_ := make(map[string]interface{})
- tempCommon := make(map[string]interface{})
- tempval := make([]map[string]interface{}, 0)
- err := json.Unmarshal(dataByte, &tempval_)
- logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- if err != nil {
- fmt.Println("error:", err)
- } else {
- if v, ok := tempval_["common"].(map[string]interface{}); ok {
- tempCommon = v
- }
- if v, ok := tempval_["data"].([]interface{}); ok {
- for _, Tvalue := range v {
- if v1, ok := Tvalue.(map[string]interface{}); ok {
- tempval = append(tempval, v1)
- }
- }
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- if err != nil {
- logging.Error("tx.Begin 事务启动失败__error:", err)
- }
- defer func() {
- switch {
- case err != nil:
- fmt.Println("__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- if err == nil {
- if tempv, exists := c.Get("jwt_username"); exists {
- tempCommon["jwt_username"] = tempv.(string)
- }
- for _, paramvalue := range tempval {
- if _, ok := paramvalue["resultname"]; !ok {
- paramvalue["resultname"] = paramvalue["name"]
- }
- _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
- if err != nil {
- logging.Error("ExecDataParam error:", err)
- break
- }
- }
- if err == nil {
- if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
- appG.Response(http.StatusOK, e.SUCCESS, tempval)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
- }
- } else {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- }
- }
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- }
- }
- func interfacetostring(val interface{}) string {
- switch val.(type) {
- case string:
- ss := val.(string)
- return ss
- break
- case int:
- ss := val.(int)
- return strconv.Itoa(ss)
- break
- case int64:
- ss := val.(int64)
- return strconv.FormatInt(ss, 10)
- break
- case float64:
- ss := val.(float64)
- return strconv.FormatFloat(ss, 'E', -1, 32)
- break
- }
- return ""
- }
- func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
- if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if tempstrb > -1 && tempstre > -1 {
- for _, ParamMapList := range ParamMap {
- if v, ok := ParamMapList["resultname"]; ok {
- if v == valuestring[tempstrb+1:tempstre] {
- if v1, ok := ParamMapList["resultmaps"]; ok {
- if newA, ok := v1.([]map[string]interface{}); ok {
- return interfacetostring(newA[0][valuestring[tempstre+1:]])
- } else if newA, ok := v1.(map[string]interface{}); ok {
- return interfacetostring(newA[valuestring[tempstre+1:]])
- }
- }
- }
- }
- }
- } else {
- return valuestring
- }
- } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
- return strconv.FormatInt(int64(valuestring), 10)
- }
- return ""
- }
- func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
- if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if tempstrb > -1 && tempstre > -1 {
- if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
- if s, ok := v.(string); ok {
- return s
- } else if s, ok := v.(float64); ok {
- return strconv.FormatInt(int64(s), 10)
- }
- }
- }
- }
- return ""
- }
- 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) {
- sqlname := fasion["name"].(string)
- sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
- if v, ok := fasion["type"]; ok {
- sqltype = v.(string)
- }
- sql := ""
- p := ""
- s_params := make([]interface{}, 0)
- if sqltype != "" {
- sql, p = restful.GetSqlByName(sqlname, tx)
- //sqlApi, _ := models.GetApisqlByName(sqlname)
- if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- ss := ""
- if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- if ss == "" && CommonParamMap != nil {
- if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
- ss = valuestring
- tempstrb := strings.IndexAny(valuestring, "@")
- tempstre := strings.IndexAny(valuestring, ".")
- if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
- if CommonParamMap[valuestring[tempstre+1:]] != nil {
- ss = CommonParamMap[valuestring[tempstre+1:]].(string)
- }
- } else {
- ss = ""
- }
- }
- }
- if ss == "" && ParentParamMap != nil {
- ss = getParamValue_(v, value, ParentParamMap)
- }
- if ss == "" && sameParamMap != nil {
- ss = getParamValue(v, value, sameParamMap)
- }
- if ss == "" && ParamMap != nil {
- ss = getParamValue(v, value, ParamMap)
- }
- s_params = append(s_params, ss)
- }
- }
- }
- }
- }
- if sql == "" {
- sqltype = ""
- }
- fmt.Printf("%v+ \n", s_params, sqlname)
- if sqltype == "s1" {
- tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
- if v, ok := tempValParam.(map[string]interface{}); ok {
- fasion["resultmaps"] = v["list"].([]map[string]interface{})
- }
- if err != nil {
- return nil, err
- }
- err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
- } else if sqltype == "sm" {
- tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
- if v, ok := tempValParam.(map[string]interface{}); ok {
- fasion["resultmaps"] = v["list"].([]map[string]interface{})
- } else {
- fmt.Println("sm", tempValParam)
- }
- if err != nil {
- return nil, err
- }
- err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
- } else if sqltype == "v" {
- tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
- if v, ok := tempValParam.(map[string]interface{}); ok {
- fasion["resultmaps"] = v["list"].([]map[string]interface{})
- } else {
- fmt.Println("v", tempValParam)
- }
- if err != nil {
- return nil, err
- }
- if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
- return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
- }
- } else if sqltype == "e" {
- tempVal_arrary := make([]map[string]interface{}, 0)
- tempVal_map := make(map[string]interface{})
- tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
- if err == nil {
- fasion["resultmaps"] = tempValParam.(map[string]interface{})
- tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
- tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
- tempVal_arrary = append(tempVal_arrary, tempVal_map)
- return tempVal_arrary, err
- }
- return nil, err
- } else {
- if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
- err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
- if err != nil {
- return nil, err
- }
- return nil, err
- }
- }
- return nil, nil
- }
- func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
- var err error
- subarray, ok := fasion["children"]
- if ok {
- for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
- tempVal_arrary := make([]map[string]interface{}, 0)
- for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
- tempVal_ := make(map[string]interface{})
- if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
- } else {
- tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
- }
- tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
- if err != nil {
- return err
- }
- tempVal_arrary = append(tempVal_arrary, tempVal_)
- }
- v.(map[string]interface{})["children"] = tempVal_arrary
- }
- }
- return nil
- }
- // @Summary 删除图片
- // @Tags RemovePicByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func RemovePicByName(c *gin.Context) {
- logging.Info("RemovePicByName ", c.Keys)
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- picname := fsion.Get("picname").ValueStr()
- sql, _ := restful.GetSqlByNameDB(sqlnamestr)
- params := fsion.Get("params").Array()
- s_params := make([]interface{}, 0)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- if sql != "" {
- queryData, err := execDataBySql(sql, s_params)
- if picname != "" {
- // Destination
- distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
- err := os.Remove(distPath) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!")
- //输出错误详细信息
- fmt.Printf("%s", err)
- } else {
- //如果删除成功则输出 file remove OK!
- fmt.Print("file remove OK!")
- }
- distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
- err = os.Remove(distPath) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!")
- //输出错误详细信息
- fmt.Printf("%s", err)
- } else {
- //如果删除成功则输出 file remove OK!
- fmt.Print("file remove OK!")
- }
- }
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- // @Summary 删除文件
- // @Tags RemoveFileByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func RemoveFileByName(c *gin.Context) {
- appG := app.Gin{C: c}
- id := c.Param("id")
- logging.Info("DownloadFile ", c.Keys, id)
- eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
- if eqdoc == nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
- err = os.Remove(distPath) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!")
- //输出错误详细信息
- fmt.Printf("%s", err)
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- fmt.Print("file remove OK!")
- _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
- appG.Response(http.StatusOK, e.SUCCESS, "OK")
- //dataByte, _ := ioutil.ReadAll(c.Request.Body)
- //fsion := gofasion.NewFasion(string(dataByte))
- //sqlnamestr := fsion.Get("name").ValueStr()
- //filename := fsion.Get("filename").ValueStr()
- //sql, _ := restful.GetSqlByNameDB(sqlnamestr)
- //params := fsion.Get("params").Array()
- //s_params := make([]interface{}, 0)
- //for _, v_params := range params {
- // s_params = append(s_params, v_params.ValueStr())
- //}
- //if sql != "" {
- // queryData, err := execDataBySql(sql, s_params)
- //
- // if filename != "" {
- // // Destination
- // distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, filename)
- //
- // err := os.Remove(distPath) //删除文件test.txt
- // if err != nil {
- // //如果删除失败则输出 file remove Error!
- // fmt.Println("file remove Error!")
- // //输出错误详细信息
- // fmt.Printf("%s", err)
- // } else {
- // //如果删除成功则输出 file remove OK!
- // fmt.Print("file remove OK!")
- // }
- // }
- // if err != nil {
- // appG.Response(http.StatusOK, e.ERROR, err.Error())
- // } else {
- // appG.Response(http.StatusOK, e.SUCCESS, "OK")
- // }
- //} else {
- // appG.Response(http.StatusOK, e.SUCCESS, nil)
- //}
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDataByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDataByName [POST]
- func UpdateDataRelation(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- tablename := fsion.Get("name").ValueStr()
- dataname := fsion.Get("dataname").ValueStr()
- datavalue := fsion.Get("datavalue").ValueStr()
- valuename := fsion.Get("valuename").ValueStr()
- logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
- values := fsion.Get("values").Array()
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- fmt.Println("__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
- " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
- d_params := make([]interface{}, 4)
- d_params[0] = datavalue
- s_params := ""
- for _, v_values := range values {
- d_params[1] = v_values.ValueStr()
- if s_params == "" {
- s_params = v_values.ValueStr()
- } else {
- s_params = s_params + "," + v_values.ValueStr()
- }
- d_params[2] = d_params[1]
- d_params[3] = d_params[0]
- _, err := execDataBySqlT(insertSqlstr, d_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- break
- }
- }
- if s_params != "" {
- deleteSqlstr := "delete from " + tablename + " " +
- " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
- queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else if err == nil {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- deleteSqlstr := "delete from " + tablename + " " +
- " where " + dataname + " = " + datavalue
- queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else if err == nil {
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- }
- }
- // @Summary 根据APISQL表中SQL执行得到数据集
- // @Tags PostDatasByName
- // @Accept json
- // @Produce json
- // @Param sqlname query string true "sqlname"
- // @Param offset query int true "offset"
- // @Param pagecount query int true "pagecount"
- // @Param returntype query string true "returntype"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/PostDatasByName [POST]
- func PostDataByNames(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlParams := fsion.Array()
- queryData := make(map[string]interface{})
- for _, v := range sqlParams {
- fsion2 := gofasion.NewFasion(v.Json())
- logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
- sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
- if sql == "" {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = "sql没有找到"
- errorm["param"] = ""
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- } else if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion2.HasKey("parammaps") {
- parammaps := fsion2.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- } else if fsion2.HasKey("params") {
- params := fsion2.Get("params").Array()
- //ids,err := setting.SnowIds.NextId()
- //if err !=nil{
- // ids = time.Now().UnixNano()
- // logging.Info("create SnowIds err",err)
- //}
- //s_params = append(s_params, ids)
- for _, v_params := range params {
- s_params = append(s_params, v_params.ValueStr())
- }
- }
- _, err := execDataBySql(sql, s_params)
- if err != nil {
- logging.Error("PostDataByName err: ", err)
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = err.Error()
- errorm["param"] = s_params
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- } else {
- errorm := make(map[string]interface{})
- errorm["code"] = e.SUCCESS
- errorm["message"] = "success"
- queryData[fsion2.Get("name").ValueStr()] = errorm
- continue
- }
- } else {
- errorm := make(map[string]interface{})
- errorm["code"] = e.ERROR
- errorm["message"] = "NO SQL"
- errorm["param"] = ""
- queryData[fsion2.Get("name").ValueStr()] = errorm
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
- if offset > 0 {
- offset = offset - 1
- }
- //if pagecount == 0 {
- // pagecount = setting.AppSetting.PageSize
- //}else if pagecount>setting.AppSetting.PageSize{
- // pagecount = setting.AppSetting.PageSize
- //}
- if returntype == "list" {
- queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
- return queryData, err
- } else if returntype == "listlist" {
- queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
- return queryData, err
- } else {
- queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
- return queryData, err
- }
- }
- func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
- if offset > 0 {
- offset = offset - 1
- }
- //if pagecount == 0 {
- // pagecount = setting.AppSetting.PageSize
- //}else if pagecount>setting.AppSetting.PageSize{
- // pagecount = setting.AppSetting.PageSize
- //}
- if returntype == "list" {
- queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
- return queryData, err
- } else if returntype == "listlist" {
- queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
- return queryData, err
- } else {
- queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
- return queryData, err
- }
- }
- func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
- paramslist := strings.Split(Params, ",")
- s_params := make([]interface{}, 0)
- if isList {
- for _, v_params := range thisParams["params"].([]interface{}) {
- s_params = append(s_params, v_params)
- }
- } else {
- paramslist := strings.Split(Params, ",")
- if len(paramslist) > 0 && Params != "" {
- for _, value := range paramslist {
- s_params = append(s_params, thisParams[strings.Trim(value, " ")])
- }
- }
- }
- queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
- for _, queryData_ := range queryData {
- if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
- if isList {
- //fmt.Println(idname, "-------------- -queryData_[idname]", queryData_)
- if queryData_[idname] != nil {
- thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
- }
- } else {
- if queryData_[idname] != nil {
- thisParams[idname] = queryData_[idname].(interface{})
- }
- if len(paramslist) > 0 && Params != "" {
- s_params = make([]interface{}, 0)
- for _, value := range paramslist {
- s_params = append(s_params, thisParams[strings.Trim(value, " ")])
- }
- }
- }
- queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
- } else {
- }
- }
- return queryData, err
- }
- func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
- queryData, err := restful.ExecQuery(sqlstr, params)
- return queryData, err
- }
- func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
- queryData, err := restful.ExecQueryT(sqlstr, params, tx)
- return queryData, err
- }
- func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
- queryData, err := restful.ExecQuery(sqlstr, params)
- return queryData, err
- }
- // @Summary 导入excel文件到数据库,excel第一行作为参数
- // @Tags ImportExcel
- // @Accept json
- // @Produce json
- // @Param file query string true "文件名"
- // @Param name header string true "执行sql的名字"
- // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
- // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
- // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
- // @Router /data/ImportExcel [POST]
- func ImportExcel(c *gin.Context) {
- appG := app.Gin{C: c}
- inputdata := ""
- c.Request.ParseForm()
- //tempv1, _ := c.Get("jwt_username")
- //fmt.Println("=======================",tempv1)
- params := c.Request.Form
- file, _, err := c.Request.FormFile("file")
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err)
- return
- }
- sqlnamestrs := params.Get("name")
- sheetname := params.Get("sheetname")
- pastureid := params.Get("pastureid")
- //importParams := params.Get("importParams")
- logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
- //paramslist := strings.Split(importParams, ",")
- //paramslist = append(paramslist, "jwt_username")
- requiredParams := params.Get("requiredParams")
- dateParams := params.Get("dateParams")
- numParams := params.Get("numParams")
- dateParamslist := strings.Split(dateParams, ",")
- requiredParamslist := strings.Split(requiredParams, ",")
- numParamslist := strings.Split(numParams, ",")
- queryData := make([]interface{}, 0)
- sqlslist := strings.Split(sqlnamestrs, ",")
- xlsx1, err := excelize.OpenReader(file)
- if err != nil {
- fmt.Println(err)
- return
- }
- ok := 0
- error := 0
- isdone := true
- rows, _ := xlsx1.GetRows(sheetname)
- if len(rows) > 10000 { // 限制1000条
- rows = rows[:10000]
- }
- for i, row := range rows {
- if i > 0 {
- entry := make(map[string]interface{})
- outentry := make(map[string]interface{})
- for j, colCell := range rows[0] {
- for k, colCell1 := range row {
- if j == k {
- outentry[colCell] = colCell1
- entry[colCell] = colCell1
- }
- }
- }
- inputdata = ""
- a := ""
- for _, v := range dateParamslist {
- if v == ""{
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; ok {
- dtime,err := TransfTime(d.(string))
- if err != nil {
- a = strings.Trim(v, " ")
- break
- }
- outentry[strings.Trim(v, " ")] = dtime
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- for _, v := range requiredParamslist {
- if v == ""{
- continue
- }
- if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
- a = strings.Trim(v, " ")
- break
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 未填或格式错误"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- a = ""
- for _, v := range numParamslist {
- if v == ""{
- continue
- }
- d, ok := outentry[strings.Trim(v, " ")]
- if !ok || d == "" {
- outentry[strings.Trim(v, " ")] = 0
- }else {
- var fl float64
- switch d.(type) {
- case string :
- fl,err = strconv.ParseFloat(d.(string),64)
- }
- if err != nil || fl<0 {
- a = strings.Trim(v, " ")
- break
- }
- }
- }
- if a != "" {
- outentry["error_msg"] = a + " 为数值类型且不可为负数"
- error++
- queryData = append(queryData, outentry)
- continue
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- for _, sqlnamestr := range sqlslist {
- sql, paramslists := restful.GetSqlByNameDB(sqlnamestr)
- paramslist := strings.Split(paramslists, ",")
- if len(paramslist) > 0 {
- s_params := make([]interface{}, 0)
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- }else if strings.ToLower(strings.Trim(value, " ")) == "pastureid"{
- s_params = append(s_params, pastureid)
- } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- s_params = append(s_params, ids)
- }else {
- if outentry[strings.Trim(value, " ")] == nil {
- s_params = append(s_params,"")
- }else{
- s_params = append(s_params, outentry[strings.Trim(value, " ")])
- }
- }
- }
- //fmt.Println("================",s_params)
- outentry["input"] = inputdata
- returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
- if err != nil {
- if tx != nil {
- tx.Rollback()
- }
- if tx != nil {
- tx.Close()
- }
- msg := geterrmsg(err.Error())
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- } else{
- if len(returnmsgmap1) > 0 {
- if va,ok :=returnmsgmap1[0]["msg"] ; ok && va != "" {
- if tx != nil {
- tx.Rollback()
- }
- if tx != nil {
- tx.Close()
- }
- msg := geterrmsg(va.(string))
- outentry["error_msg"] = msg
- error++
- queryData = append(queryData, outentry)
- isdone = true
- break
- }
- }
- isdone = false
- }
- }
- }
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }
- if !isdone{
- ok++
- isdone = true
- }
- }
- data := make(map[string]interface{})
- data["result"] = queryData
- data["success"] = ok
- data["err_count"] = error
- appG.Response(http.StatusOK, e.SUCCESS, data)
- }
- func TransfTime(timestr string) (string,error) {
- if timestr == "" {
- return time.Now().Format("2006-01-02"),nil
- }
- days, err := strconv.Atoi(timestr)
- if err != nil {
- if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
- return "20" + timestr[6:] + "-" + timestr[:5],nil
- }
- _,err :=time.Parse("2006-01-02",timestr)
- if err != nil{
- t,err :=time.Parse("2006/01/02",timestr)
- if err != nil{
- t,err :=time.Parse("2006.01.02",timestr)
- if err != nil {
- return "",err
- }else {
- return t.Format("2006-01-02"),nil
- }
- }else {
- return t.Format("2006-01-02"),nil
- }
- }else {
- return timestr,nil
- }
- }
- times, _ := time.Parse("2006-01-02", "1899-12-30")
- times = times.AddDate(0, 0, days)
- return times.Format("2006-01-02"),nil
- }
- func Createchart(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- chart_name := fsion.Get("chart_name").ValueStr()
- desc := fsion.Get("desc").ValueStr()
- pastureid := fsion.Get("pastureid").ValueStr()
- source_id := fsion.Get("source_id").ValueStr()
- emp := fsion.Get("emp").ValueStr()
- content := fsion.Get("content").Json()
- //fmt.Println("=============",parammaW.Json())
- var mapResult map[string]interface{}
- err1 := json.Unmarshal([]byte(content), &mapResult)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err1)
- }
- //fmt.Println("---------",mapResult)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
- ids, pastureid, chart_name, 0, emp, desc, source_id)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec)
- }
- }
- func Updatedashboard(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- dashboard_id := fsion.Get("dashboard_id").ValueStr()
- pastureid := fsion.Get("pastureid").ValueStr()
- content := fsion.Get("content").Json()
- //fmt.Println("=============",parammaW.Json())
- var mapResult map[string]interface{}
- err1 := json.Unmarshal([]byte(content), &mapResult)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err1)
- }
- layout := mapResult["layout"]
- fmt.Println("---------", layout)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- //fmt.Println("sql========\n",sqlnamestr,sql)
- exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
- if err != nil {
- println("2", err.Error())
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- if exec != nil {
- if exec[0]["content"] == nil {
- mapR := make(map[string]interface{})
- mapR["layout"] = layout
- mjson, _ := json.Marshal(mapR)
- mString := string(mjson)
- exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
- if err3 != nil {
- println("3", err3.Error())
- appG.Response(http.StatusOK, e.ERROR, err3.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec1)
- }
- } else {
- var mapR map[string]interface{}
- err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err2)
- }
- mapR["layout"] = layout
- mjson, _ := json.Marshal(mapR)
- mString := string(mjson)
- exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
- if err3 != nil {
- println("3", err3.Error())
- appG.Response(http.StatusOK, e.ERROR, err3.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec1)
- }
- }
- } else {
- appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
- }
- }
- }
- func ExecSQL(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- content := fsion.Get("content").Json()
- pastureid := fsion.Get("pastureid").ValueStr()
- //pastureid := fsion.Get("pastureid").ValueStr()
- //println(pastureid,"==================")
- //fmt.Println("=============",parammaW.Json())
- var mapResult map[string]interface{}
- err1 := json.Unmarshal([]byte(content), &mapResult)
- if err1 != nil {
- fmt.Println("JsonToMapDemo err: ", err1)
- }
- //fmt.Println("---------",mapResult)
- sqlstr := "select "
- groupstr := " GROUP BY "
- for _, value := range mapResult["selectedDimension"].([]interface{}) {
- sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
- groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
- }
- for _, value := range mapResult["selectedCalcul"].([]interface{}) {
- if value.(map[string]interface{})["calculFunc"].(string) == "none" {
- sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
- groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
- } else {
- tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- }
- }
- if _, ok := mapResult["selectedCalcul2"]; ok {
- for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
- if value.(map[string]interface{})["calculFunc"].(string) == "none" {
- sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
- groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
- } else {
- tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
- sqlstr = sqlstr + tem + ","
- }
- }
- }
- //
- sqlstr = sqlstr[0 : len(sqlstr)-1]
- sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
- //if len(mapResult["filters"].([]interface {}))>0{
- sqlstr = sqlstr + " where pastureid=" + pastureid
- //}
- //
- for _, value := range mapResult["filters"].([]interface{}) {
- switch value.(map[string]interface{})["filterOperator"].(string) {
- case ">", "=", "<", ">=", "<=", "!=", "like":
- 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 "
- case "IN":
- sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
- for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
- sqlstr = sqlstr + value1.(string) + ","
- }
- sqlstr = sqlstr[0 : len(sqlstr)-1]
- sqlstr = sqlstr + ")" + " AND "
- case "BETWEEN":
- 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 "
- }
- }
- if len(mapResult["filters"].([]interface{})) > 0 {
- sqlstr = sqlstr[0 : len(sqlstr)-4]
- }
- //
- groupstr = groupstr[0 : len(groupstr)-1]
- sqlstr = sqlstr + groupstr + " "
- if len(mapResult["orderByStrs"].([]interface{})) > 0 {
- sqlstr = sqlstr + " order by "
- }
- //
- for key, value := range mapResult["orderByStrs"].([]interface{}) {
- if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
- sqlstr = sqlstr + value.(string) + " "
- } else {
- sqlstr = sqlstr + value.(string) + ","
- }
- }
- //
- sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
- //fmt.Println("====++---------",sqlstr)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- //fmt.Println("sql========\n",sqlnamestr,sql)
- //ids,err := setting.SnowIds.NextId()
- //if err !=nil{
- // ids = time.Now().UnixNano()
- // logging.Info("create SnowIds err",err)
- //}
- // exec,err :=tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
- //ids,pastureid,chart_name,0,emp,desc,source_id)
- exec, err := tx.SQL(sqlstr).Query().List()
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, exec)
- }
- }
- func Dashboards(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- sqlnamestr := fsion.Get("name").ValueStr()
- //sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- month := fsion.Get("month").ValueDefaultStr("map")
- logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- fmt.Println("__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- } else {
- //paramslist1 := strings.Split(p1, ",")
- dids := make([]interface{}, 0)
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- var mapResult map[string]interface{}
- dids = append(dids, value["dashboard_id"])
- if value["content"] != nil {
- err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
- if err1 != nil {
- println("JsonToMapDemo1 err: ", err1)
- }
- //fmt.Printf("%v+\n",value["content"].(string))
- temap := make(map[string]interface{})
- tem := mapResult["layout"].([]interface{})
- if v, ok := value["chartids"]; ok {
- chartids := strings.Split(v.(string), ",")
- for _, va := range chartids {
- a := false
- for _, v2 := range tem {
- if v2.(map[string]interface{})["id"].(string) == va {
- a = true
- //println("va1======",va)
- }
- }
- if !a {
- laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
- va + "\",\"id\":\"" + va +
- "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
- var mapTem map[string]interface{}
- err1 := json.Unmarshal([]byte(laytem), &mapTem)
- if err1 != nil {
- println("JsonToMapDemo err: ", err1)
- }
- tem = append(tem, mapTem)
- }
- }
- temap["layout"] = tem
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
- }
- } else {
- temap := make(map[string]interface{})
- tem := make([]interface{}, 0)
- if v, ok := value["chartids"]; ok {
- chartids := strings.Split(v.(string), ",")
- for _, va := range chartids {
- laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
- va + "\",\"id\":\"" + va +
- "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
- var mapTem map[string]interface{}
- err1 := json.Unmarshal([]byte(laytem), &mapTem)
- if err1 != nil {
- println("JsonToMapDemo err: ", err1)
- }
- tem = append(tem, mapTem)
- }
- temap["layout"] = tem
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
- }
- }
- }
- queryData.(map[string]interface{})["order"] = dids
- queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
- appG.Response(http.StatusOK, e.SUCCESS, queryData)
- }
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- }
- //type Nur struct {
- // Avgmonthage float64 `json : "avgmonthage"` //月龄
- // Bw float64 `json : "bw"` //体重
- // Dayw float64 `json : "dayw"` //日增重
- // Fetal float64 `json : "fetal"` //胎次
- // Avgdim float64 `json : "avgdim"` //平均泌乳天数
- // Dayspre float64 `json : "dayspre"` //怀孕天数
- // Product float64 `json : "product"` //产奶量
- // Fat float64 `json : "fat"` //乳脂率
- // Pro float64 `json : "pro"` //乳蛋白率
- // Lactose float64 `json : "lactose"` //乳糖率
- // Source string `json : "source"` //来源
- // Tem float64 `json : "tem"` //温度
- // Cowsum float64 `json : "cowsum"` //牛头数
- // Cowclass float64 `json : "cowclass"` //牲畜类别
- // Cowclassid float64 `json : "cowclassid"` //牲畜类别id
- // Bigcowclass string `json : "bigcowclass"` //牲畜大类
- //}
- type Nur struct {
- Avgmonthage float64 //月龄
- Bw float64 //体重
- Dayw float64 //日增重
- Fetal float64 //胎次
- Avgdim float64 //平均泌乳天数
- Dayspre float64 //怀孕天数
- Product float64 //产奶量
- Fat float64 //乳脂率
- Pro float64 //乳蛋白率
- Lactose float64 //乳糖率
- Source string //来源
- Tem float64 //温度
- Cowsum float64 //牛头数
- Cowclass string //牲畜类别
- Cowclassid float64 //牲畜类别id
- Bigcowclass string //牲畜大类
- }
- func GETNurJudge(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- nurstr := fsion.Get("parammaps").Json()
- parammaps := make(map[string]interface{})
- nur := Nur{}
- _ = json.Unmarshal([]byte(nurstr), &nur) //需要json 的类型相同
- _ = json.Unmarshal([]byte(nurstr), ¶mmaps) //需要json 的类型相同
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- defer func() {
- switch {
- case err != nil:
- fmt.Println("__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- formulas, _ := tx.SQL("select * from tb_formula_d where cowclass = ? "+
- "and if (?='',''='', nutrition=? ) ORDER BY nutrition", nur.Bigcowclass, nur.Source, nur.Source).Query().List()
- resnur, err := CalNUR(formulas, &nur)
- if err != nil {
- logging.Error("GETNurJudge err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- resf, err := FeedproviderV2(parammaps, tx)
- reslist := make([]map[string]interface{}, 21)
- if len(resf) > 1 {
- for key, _ := range resf[0] {
- //println(key)
- str, sort := switchname(key)
- res := make(map[string]interface{}, 0)
- res["standard"] = str
- res["cowneed"] = resnur[key] // 奶牛需要
- res["ftpro"] = resf[0][key] // 配方提供
- res["hprov"] = resf[1][key] // tmr料
- res["sprov"] = resf[2][key] //采食量
- reslist[sort] = res
- }
- }
- if err != nil {
- logging.Error("GETNurJudge err: ", err)
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, reslist)
- }
- }
- func GETNurJudgeRport(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- nurstr := fsion.Get("parammaps").Json()
- parammaps := make(map[string]interface{})
- _ = json.Unmarshal([]byte(nurstr), ¶mmaps)
- startTime, err := time.Parse("2006-01-02", parammaps["startTime"].(string))
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- stopTime, err := time.Parse("2006-01-02", parammaps["stopTime"].(string))
- if err != nil {
- appG.Response(http.StatusOK, e.ERROR, err.Error())
- return
- }
- if stopTime.Sub(startTime) > 31*24*time.Hour {
- appG.Response(http.StatusOK, e.ERROR, errors.New("日期范围过大"))
- return
- }
- tx := restful.Engine.NewSession()
- err = tx.Begin()
- defer func() {
- switch {
- case err != nil:
- fmt.Println("__error:", err)
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- //CulNurReportCow("getbmdetaillist",parammaps,tx)
- res, err := CulNurReportFT(parammaps, tx)
- if err != nil {
- logging.Error("GETNurJudgeRport err: ", err)
- //appG.Response(http.StatusOK, e.ERROR, err.Error())
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, res)
- }
- }
- func CulNurReportCow(sqlname string, parammaps map[string]interface{}, tx *xorm.Session) (map[string]interface{}, error) {
- var nur Nur
- sql, p := restful.GetSqlByNameDBT(sqlname, tx)
- s_params := make([]interface{}, 0)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps[strings.Trim(value, " ")])
- }
- }
- res, err := tx.SQL(sql, s_params...).Query().List()
- if len(res) > 0 {
- resstr, _ := json.Marshal(res[0])
- err = json.Unmarshal(resstr, &nur)
- if err != nil {
- return nil, err
- }
- }
- formulas, _ := tx.SQL("select * from tb_formula_d where cowclass = ? and if (?='',''='', nutrition=? ) ORDER BY nutrition", nur.Bigcowclass, nur.Source, nur.Source).Query().List()
- //println(len(formulas))
- resnur, err := CalNUR(formulas, &nur)
- if err != nil {
- return nil, err
- }
- return resnur, err
- }
- func CulNurReportFT(parammaps map[string]interface{}, tx *xorm.Session) (res []map[string]interface{}, err error) {
- 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",
- parammaps["pastureid"], parammaps["startTime"], parammaps["stopTime"], parammaps["ftid"]).Query().List()
- //println(parammaps["pastureid"].(string), parammaps["startTime"].(string), parammaps["stopTime"].(string), parammaps["ftid"].(string))
- if err != nil {
- return nil, err
- }
- bartem := ""
- //println("barids", len(barids))
- dates := make([]string, 0)
- for key, value := range barids {
- if key == 0 {
- bartem = value["barid"].(string)
- parammaps["barid"] = value["barid"]
- }
- if bartem != value["barid"].(string) || key == len(barids)-1 || key == 0{
- if key == len(barids)-1 || key == 0{
- dates = append(dates, value["date"].(string))
- }
- parammaps["date"] = value["date"]
- parammaps["barid"] = value["barid"]
- barres, err := FeedproviderV3(parammaps, dates, tx)
- if err != nil {
- return nil, err
- }
- resnur, err := CulNurReportCow("getbmdetaillist", parammaps, tx)
- if err != nil {
- return nil, err
- }
- restem := make(map[string]interface{}, 0)
- for k, _ := range barres[0] {
- //println("wwwwwww",k)
- restem["barid"] = value["barid"].(string)
- restem["barname"] = value["barname"].(string)
- restem["ccount"] = value["ccount"].(int64)
- restem[k+"-nur"] = resnur[k]
- restem[k+"-FT"] = barres[0][k]
- restem[k+"-H"] = barres[1][k]
- restem[k+"-S"] = barres[2][k]
- }
- res = append(res, restem)
- if err != nil {
- return nil, err
- }
- bartem = value["barid"].(string)
- dates = make([]string, 0)
- parammaps["barid"] = value["barid"]
- }
- dates = append(dates, value["date"].(string))
- }
- return res, err
- }
- func switchname(str string) (string, int) {
- tstr := ""
- sort := 0
- switch str {
- case "dry":
- tstr = "干物质(kg)"
- sort = 0
- case "nm":
- tstr = "产奶净能(MJ)"
- sort = 1
- case "nuint":
- tstr = "奶牛能量单位(NND)"
- sort = 2
- case "cp":
- tstr = "粗蛋白(g)"
- sort = 3
- case "ca":
- tstr = " 钙(g)"
- sort = 4
- case "p":
- tstr = "磷(g)"
- sort = 5
- case "nmd":
- tstr = "产奶净能(MCal/DM)"
- sort = 6
- case "cpd":
- tstr = "粗蛋白(%DM)"
- sort = 7
- case "fat":
- tstr = "脂肪"
- sort = 8
- case "starch":
- tstr = "淀粉"
- sort = 9
- case "ndf":
- tstr = "NDF(%DM)"
- sort = 10
- case "cndf":
- tstr = "粗料中的NDF(%DM)"
- sort = 11
- case "adf":
- tstr = "ADF(%DM)"
- sort = 12
- case "cad":
- tstr = " 钙(%DM)"
- sort = 13
- case "pd":
- tstr = "磷(%DM)"
- sort = 14
- case "trans35f":
- tstr = "(3.5)饲料转化效率(kg/DM)"
- sort = 15
- case "trans4f":
- tstr = "(4.0)饲料转化效率(kg/DM)"
- sort = 16
- case "jcrate":
- tstr = "精粗比"
- sort = 17
- case "uprice":
- tstr = "日粮成本(元)"
- sort = 18
- case "upriced":
- tstr = "干物质成本(元/公斤)"
- sort = 19
- case "kprice":
- tstr = "公斤奶成本(元) "
- sort = 20
- default:
- tstr = str
- sort = 21
- }
- return tstr, sort
- }
- func FeedproviderV2(parammaps map[string]interface{}, tx *xorm.Session) ([]map[string]float64, error) {
- startTime, err := time.Parse("2006-01-02", parammaps["startTime"].(string))
- if err != nil {
- return nil, err
- }
- stopTime, err := time.Parse("2006-01-02", parammaps["stopTime"].(string))
- if err != nil {
- return nil, err
- }
- if stopTime.Sub(startTime) > 31*24*time.Hour {
- return nil, errors.New("日期范围过大")
- }
- dates := make([]string, 0)
- for stopTime.Sub(startTime) >= 0 {
- dates = append(dates, startTime.Format("2006-01-02"))
- startTime = startTime.Add(24 * time.Hour)
- }
- resall, err := FeedproviderV3(parammaps, dates, tx)
- return resall, err
- }
- func FeedproviderV3(parammaps map[string]interface{}, dates []string, tx *xorm.Session) ([]map[string]float64, error) {
- res := make(map[string]float64, 0)
- resH := make(map[string]float64, 0)
- resS := make(map[string]float64, 0)
- i := 0
- for _, date := range dates {
- i++
- //println(date)
- parammaps["date"] = date
- restem, err := Feedprovider(parammaps, tx)
- if err != nil {
- return nil, err
- }
- restemSH, err := SHprovider(parammaps, tx)
- if err != nil {
- return nil, err
- }
- var h, s float64
- if len(restemSH) > 1 {
- switch restemSH[0]["actualweightminus"].(type) {
- case string:
- h, _ = strconv.ParseFloat(restemSH[0]["actualweightminus"].(string), 64)
- }
- switch restemSH[1]["actualweightminus"].(type) {
- case string:
- s, _ = strconv.ParseFloat(restemSH[1]["actualweightminus"].(string), 64)
- }
- }
- if len(restem) > 0 {
- b, _ := strconv.ParseFloat(restem[0]["jcrate"].(string), 64)
- res["jcrate"] = res["jcrate"] + b
- resH["jcrate"] = resH["jcrate"] + h*b
- resS["jcrate"] = resS["jcrate"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["cpd"].(string), 64)
- res["cpd"] = res["cpd"] + b
- resH["cpd"] = resH["cpd"] + h*b
- resS["cpd"] = resS["cpd"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["adf"].(string), 64)
- res["adf"] = res["adf"] + b
- resH["adf"] = resH["adf"] + h*b
- resS["adf"] = resS["adf"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["ca"].(string), 64)
- res["ca"] = res["ca"] + b
- resH["ca"] = resH["ca"] + h*b
- resS["ca"] = resS["ca"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["cad"].(string), 64)
- res["cad"] = res["cad"] + b
- resH["cad"] = resH["cad"] + h*b
- resS["cad"] = resS["cad"] + s*b
- //b,_ =strconv.ParseFloat(restem[0]["cdry"].(string),64)
- //res["cdry"] = res["cdry"]+b
- //
- //resH["cdry"] = resH["cdry"]+ h*b
- //resS["cdry"] = resS["cdry"]+ s*b
- b, _ = strconv.ParseFloat(restem[0]["cndf"].(string), 64)
- res["cndf"] = res["cndf"] + b
- resH["cndf"] = resH["cndf"] + h*b
- resS["cndf"] = resS["cndf"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["cp"].(string), 64)
- res["cp"] = res["cp"] + b
- resH["cp"] = resH["cp"] + h*b
- resS["cp"] = resS["cp"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["dry"].(string), 64)
- res["dry"] = res["dry"] + b
- resH["dry"] = resH["dry"] + h*b
- resS["dry"] = resS["dry"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["fat"].(string), 64)
- res["fat"] = res["fat"] + b
- resH["fat"] = resH["fat"] + h*b
- resS["fat"] = resS["fat"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["kprice"].(string), 64)
- res["kprice"] = res["kprice"] + b
- resH["kprice"] = resH["kprice"] + h*b
- resS["kprice"] = resS["kprice"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["nm"].(string), 64)
- res["nm"] = res["nm"] + b
- resH["nm"] = resH["nm"] + h*b
- resS["nm"] = resS["nm"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["ndf"].(string), 64)
- res["ndf"] = res["ndf"] + b
- resH["ndf"] = resH["ndf"] + h*b
- resS["ndf"] = resS["ndf"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["nm"].(string), 64)
- res["nm"] = res["nm"] + b
- resH["nm"] = resH["nm"] + h*b
- resS["nm"] = resS["nm"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["nmd"].(string), 64)
- res["nmd"] = res["nmd"] + b
- resH["nmd"] = resH["nmd"] + h*b
- resS["nmd"] = resS["nmd"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["nuint"].(string), 64)
- res["nuint"] = res["nuint"] + b
- resH["nuint"] = resH["nuint"] + h*b
- resS["nuint"] = resS["nuint"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["p"].(string), 64)
- res["p"] = res["p"] + b
- resH["p"] = resH["p"] + h*b
- resS["p"] = resS["p"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["pd"].(string), 64)
- res["pd"] = res["pd"] + b
- resH["pd"] = resH["pd"] + h*b
- resS["pd"] = resS["pd"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["starch"].(string), 64)
- res["starch"] = res["starch"] + b
- resH["starch"] = resH["starch"] + h*b
- resS["starch"] = resS["starch"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["trans4f"].(string), 64)
- res["trans4f"] = res["trans4f"] + b
- resH["trans4f"] = resH["trans4f"] + h*b
- resS["trans4f"] = resS["trans4f"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["trans35f"].(string), 64)
- res["trans35f"] = res["trans35f"] + b
- resH["trans35f"] = resH["trans35f"] + h*b
- resS["trans35f"] = resS["trans35f"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["uprice"].(string), 64)
- res["uprice"] = res["uprice"] + b
- resH["uprice"] = resH["uprice"] + h*b
- resS["uprice"] = resS["uprice"] + s*b
- b, _ = strconv.ParseFloat(restem[0]["upriced"].(string), 64)
- res["upriced"] = res["upriced"] + b
- resH["upriced"] = resH["upriced"] + h*b
- resS["upriced"] = resS["upriced"] + s*b
- }
- }
- for key, _ := range res {
- resf, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", res[key]/float64(i)), 64)
- resHf, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", resH[key]/float64(i)), 64)
- resSf, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", resS[key]/float64(i)), 64)
- res[key] = resf
- resH[key] = resHf
- resS[key] = resSf
- }
- resAll := make([]map[string]float64, 0)
- resAll = append(resAll, res, resH, resS)
- return resAll, nil
- }
- func Feedprovider(parammaps map[string]interface{}, tx *xorm.Session) ([]map[string]interface{}, error) {
- sql, p := restful.GetSqlByNameDBT(parammaps["name"].(string), tx)
- s_params := make([]interface{}, 0)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps[strings.Trim(value, " ")])
- }
- }
- res, err := tx.SQL(sql, s_params...).Query().List()
- return res, err
- }
- func SHprovider(parammaps map[string]interface{}, tx *xorm.Session) ([]map[string]interface{}, error) {
- sql, p := restful.GetSqlByNameDBT(parammaps["name1"].(string), tx)
- //println(parammaps["name1"].(string),sql)
- s_params := make([]interface{}, 0)
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps[strings.Trim(value, " ")])
- }
- }
- res, err := tx.SQL(sql, s_params...).Query().List()
- return res, err
- }
- func CalNUR(formulas []map[string]interface{}, nur *Nur) (map[string]interface{}, error) {
- //formulaADF := make([]map[string]interface{},1)//ADF
- //formulaNDF := make([]map[string]interface{},1)//NDF
- //formulaNFC := make([]map[string]interface{},1)//NFC
- //formulacprotedm := make([]map[string]interface{},1)//小肠可消化粗蛋白
- //formuladry := make([]map[string]interface{},1) //干物质
- //formulastarch := make([]map[string]interface{},1)//淀粉
- //formulap := make([]map[string]interface{},1)//磷
- //formulacNDF := make([]map[string]interface{},1)//粗料中的NDF %DM
- //formulajcrate := make([]map[string]interface{},1)//粗料比例
- //formulacprote := make([]map[string]interface{},1)//粗蛋白
- //formulaenergy := make([]map[string]interface{},1)//能量
- //formulafat := make([]map[string]interface{},1)//脂肪
- //formulaga := make([]map[string]interface{},1)//钙
- //formulafeedrate := make([]map[string]interface{},1)//饲料转化效率,标准乳/干物质4.0
- //formulafeed35rate := make([]map[string]interface{},1)//饲料转化效率,标准乳/干物质3.5
- resmap := make(map[string]float64)
- resmapstr := make(map[string]string)
- resAll := make(map[string]interface{})
- for _, formula := range formulas {
- if formula["type"].(int64) == 0 {
- resmapstr[formula["note"].(string)] = formula["formula"].(string)
- continue
- }
- res, err := PraseFormula(formula["formula"].(string), nur)
- if err != nil {
- logging.Error("PraseFormula err", err.Error(), formula["nutrition"].(string))
- //println("PraseFormula err", err.Error(), formula["nutrition"].(string))
- }
- switch res.(type) {
- case string:
- resmapstr[formula["note"].(string)] = res.(string)
- case float64, int, float32, int64, int32, int16, int8:
- var rest float64
- switch res.(type) {
- case float64:
- rest = res.(float64)
- case int:
- rest = float64(res.(int))
- case int64:
- rest = float64(res.(int64))
- case int32:
- rest = float64(res.(int32))
- case int16:
- rest = float64(res.(int16))
- case int8:
- rest = float64(res.(int8))
- }
- //fmt.Printf("==============oo %+v %+v %+v\n", res,rest,formula["nutrition"].(string))
- switch formula["nutrition"].(string) {
- case "ADF %DM":
- resmap["adf"] = resmap["adf"] + rest
- case "NDF %DM":
- resmap["ndf"] = resmap["ndf"] + rest
- case "NFC %DM":
- resmap["nfc"] = resmap["nfc"] + rest
- //case "小肠可消化粗蛋白":
- // resmap["cprotedm"] = resmap["cprotedm"] + rest
- case "干物质":
- resmap["dry"] = resmap["dry"] + rest
- case "淀粉":
- resmap["starch"] = resmap["starch"] + rest
- case "磷":
- resmap["p"] = resmap["p"] + rest
- case "粗料中的NDF %DM":
- resmap["cndf"] = resmap["cndf"] + rest
- case "粗料比例":
- resmap["jcrate"] = resmap["jcrate"] + rest
- case "粗蛋白":
- resmap["cp"] = resmap["cp"] + rest
- case "能量":
- resmap["nm"] = resmap["nm"] + rest
- case "脂肪":
- resmap["fat"] = resmap["fat"] + rest
- case "钙":
- resmap["ca"] = resmap["ca"] + rest
- case "饲料转化效率,标准乳/干物质":
- resmap["trans4f"] = resmap["trans4f"] + rest
- case "饲料转化效率,标准乳/干物质3.5":
- resmap["trans35f"] = resmap["trans35f"] + rest
- }
- default:
- fmt.Printf("===============%T \n", res)
- }
- }
- if resmap["dry"] == 0 { //粗蛋白%dm = 粗蛋白/干物质
- resmap["cpd"] = 0
- resmap["cad"] = 0
- resmap["pd"] = 0
- resmap["nuint"] = 0
- resmap["nmd"] = 0
- } else {
- resmap["cpd"] = resmap["cp"] / resmap["dry"] / 10
- resmap["cad"] = resmap["ca"] / resmap["dry"] / 10
- resmap["pd"] = resmap["p"] / resmap["dry"] / 10
- resmap["nuint"] = resmap["nm"] / 3.138
- resmap["nmd"] = resmap["nm"] * 0.2389 / resmap["dry"]
- }
- for key, value := range resmap {
- va, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", value), 64)
- resAll[key] = va
- }
- for key, value := range resmapstr {
- //println(key, value)
- resAll[key] = value
- }
- resAll["uprice"] = ""
- resAll["upriced"] = ""
- resAll["kprice"] = ""
- return resAll, nil
- }
- func PraseFormula(formula string, nur *Nur) (interface{}, error) {
- str := formula
- str = strings.ReplaceAll(str, "日增重", strconv.FormatFloat(nur.Dayw, 'f', -1, 64))
- //str = strings.ReplaceAll(str, "体重", nur.Bw)
- str = strings.ReplaceAll(str, "怀孕天数", strconv.FormatFloat(nur.Dayspre, 'f', -1, 64))
- str = strings.ReplaceAll(str, "产量", strconv.FormatFloat(nur.Product, 'f', -1, 64))
- str = strings.ReplaceAll(str, "乳脂率", strconv.FormatFloat(nur.Fat, 'f', -1, 64))
- str = strings.ReplaceAll(str, "乳蛋白率", strconv.FormatFloat(nur.Pro, 'f', -1, 64))
- str = strings.ReplaceAll(str, "乳糖率", strconv.FormatFloat(nur.Lactose, 'f', -1, 64))
- str = strings.ReplaceAll(str, "标准乳", strconv.FormatFloat(0.35*nur.Product+15*nur.Fat/100*nur.Product, 'f', -1, 64)) // 3.5乳脂率
- //str = strings.ReplaceAll(str, "标准乳", strconv.FormatFloat(0.35*nur.Product+18.57*nur.Fat/100*nur.Product, 'f', -1, 64))
- //println("标准乳--",strconv.FormatFloat(0.4*nur.Product+15*nur.Fat/100*nur.Product, 'f', -1, 64))
- str = strings.ReplaceAll(str, "泌乳天数", strconv.FormatFloat(nur.Avgdim, 'f', -1, 64))
- str = strings.ReplaceAll(str, "月龄", strconv.FormatFloat(nur.Avgmonthage, 'f', -1, 64))
- str = strings.ReplaceAll(str, "温度", strconv.FormatFloat(nur.Tem, 'f', -1, 64))
- str = strings.ReplaceAll(str, "胎次", strconv.FormatFloat(nur.Fetal, 'f', -1, 64))
- str = strings.ReplaceAll(str, "体重", strconv.FormatFloat(nur.Bw, 'f', -1, 64))
- str = strings.ReplaceAll(str, "Math.pow", "Mathpow")
- str = strings.ReplaceAll(str, "Math.round", "Mathround")
- str = strings.ReplaceAll(str, "Math.log", "Mathlog")
- str = strings.ReplaceAll(str, "Math.exp", "Mathexp")
- //str := "(体重>200?4.2/0.55*Math.pow(体重,0.75):3.5/0.55*Math.pow(体重,0.75))"
- functions := map[string]govaluate.ExpressionFunction{
- "strlen": func(args ...interface{}) (interface{}, error) {
- length := len(args[0].(string))
- return (float64)(length), nil
- },
- "Mathpow": func(args ...interface{}) (interface{}, error) {
- c := math.Pow(args[0].(float64), args[1].(float64))
- return (float64)(c), nil
- },
- "Mathround": func(args ...interface{}) (interface{}, error) {
- c := math.Round(args[0].(float64))
- return (float64)(c), nil
- },
- "Mathlog": func(args ...interface{}) (interface{}, error) {
- c := math.Log(args[0].(float64))
- return (float64)(c), nil
- },
- "Mathexp": func(args ...interface{}) (interface{}, error) {
- c := math.Exp(args[0].(float64))
- return (float64)(c), nil
- },
- }
- expression, err := govaluate.NewEvaluableExpressionWithFunctions(str, functions)
- if err != nil {
- return 0, err
- }
- //fmt.Printf("== %+v\n", str)
- result, err := expression.Evaluate(nil)
- //fmt.Printf("== %+v\n", result)
- if err != nil || result == nil {
- return 0, err
- }
- return result, err
- }
- func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
- fsion := gofasion.NewFasion(parammaps)
- sqlnamestr := fsion.Get("name").ValueStr()
- sqlnamestr1 := fsion.Get("name1").ValueStr()
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- returntype := fsion.Get("returntype").ValueDefaultStr("map")
- sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
- sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
- body := []byte("")
- if sql != "" {
- s_params := make([]interface{}, 0)
- if fsion.HasKey("parammaps") {
- parammaps := fsion.Get("parammaps")
- paramslist := strings.Split(p, ",")
- if len(paramslist) > 0 && p != "" {
- for _, value := range paramslist {
- s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
- }
- }
- }
- queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
- if err != nil {
- } else {
- paramslist1 := strings.Split(p1, ",")
- for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
- s_params1 := make([]interface{}, 0)
- if len(paramslist1) > 0 && p1 != "" {
- for _, v := range paramslist1 {
- s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
- }
- }
- arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
- queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
- body, _ = json.Marshal(queryData)
- }
- }
- }
- bs := bytes.NewBuffer(body)
- client := &http.Client{}
- //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
- req, err := http.NewRequest(RequestMethod,
- url,
- bs,
- )
- if err != nil {
- }
- req.Header.Set("Content-Type", "application/json;charset=utf-8")
- req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
- if err != nil {
- // handle error
- }
- resp, err := client.Do(req)
- if err != nil {
- fmt.Println(err)
- return ""
- }
- defer resp.Body.Close()
- result_body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- fmt.Println(err)
- return ""
- }
- fmt.Println(string(result_body))
- return ""
- }
|