db.go 167 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126
  1. package api
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "path"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "time"
  17. "../../pkg/app"
  18. "../../pkg/e"
  19. "../../pkg/logging"
  20. "../../pkg/setting"
  21. "../../routers/restful"
  22. "github.com/360EntSecGroup-Skylar/excelize"
  23. "github.com/Anderson-Lu/gofasion/gofasion"
  24. "github.com/astaxie/beego/logs"
  25. "github.com/gin-gonic/gin"
  26. "github.com/tealeg/xlsx"
  27. "github.com/xormplus/xorm"
  28. )
  29. // @Summary 根据SQL执行得到数据集
  30. // @Tags getData
  31. // @Accept json
  32. // @Produce json
  33. // @Param sql query string true "sql"
  34. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  35. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  36. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  37. // @Router /data/getdata [POST]
  38. func GetData(c *gin.Context) {
  39. appG := app.Gin{C: c}
  40. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  41. fsion := gofasion.NewFasion(string(dataByte))
  42. sqlstr := fsion.Get("sql").ValueStr()
  43. offset := fsion.Get("offset").ValueDefaultInt(0)
  44. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  45. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  46. queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
  47. if err != nil {
  48. appG.Response(http.StatusOK, e.ERROR, err.Error())
  49. } else {
  50. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  51. }
  52. }
  53. func Testpartitions(c *gin.Context) {
  54. appG := app.Gin{C: c}
  55. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  56. fsion := gofasion.NewFasion(string(dataByte))
  57. databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
  58. user := fsion.Get("user").ValueStr() //获取新数据库用户
  59. passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称
  60. host := fsion.Get("host").ValueStr() //获取新数据库名称
  61. port := fsion.Get("port").ValueStr() //获取新数据库名称
  62. sqls, err1 := restful.Engine.SQL("SELECT * FROM sql_new ").QueryString() //获取新数据库表
  63. if sqls == nil || err1 != nil {
  64. appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
  65. }
  66. sqlstrs := strings.Split(sqls[0]["sql"], ";") //分割sql
  67. connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
  68. mydb, err := sql.Open("mysql", connecting) //连接新连接
  69. if err != nil {
  70. println("err1", err.Error())
  71. }
  72. _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
  73. if err != nil {
  74. println("err2", err.Error())
  75. }
  76. mydb.Close()
  77. connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
  78. mydb, err = sql.Open("mysql", connecting)
  79. if err != nil {
  80. println("err3", err.Error())
  81. }
  82. defer mydb.Close()
  83. if err == nil {
  84. mydb.SetMaxOpenConns(10)
  85. mydb.SetMaxIdleConns(10)
  86. }
  87. errmsg := ""
  88. if err == nil {
  89. //tx ,_ :=mydb.Begin()
  90. for _, sqlstr := range sqlstrs {
  91. //println("sqlstr---",sqlstr)
  92. if sqlstr == "" {
  93. continue
  94. }
  95. _, err = mydb.Exec(sqlstr)
  96. if err != nil {
  97. println("err4", err.Error())
  98. errmsg = err.Error()
  99. //err1 :=tx.Rollback()
  100. }
  101. }
  102. //_, err = mydb.Exec("CREATE TABLE `sql_new` (`sql` text DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;")
  103. //err =tx.Commit()
  104. }
  105. if errmsg == "" {
  106. appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
  107. } else {
  108. appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
  109. }
  110. }
  111. func TestData(c *gin.Context) {
  112. appG := app.Gin{C: c}
  113. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  114. fsion := gofasion.NewFasion(string(dataByte))
  115. sqlstr := fsion.Get("sql").ValueStr()
  116. token := ""
  117. if tempv, exists := c.Get("jwt_username"); exists {
  118. token = tempv.(string)
  119. }
  120. appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
  121. }
  122. // @Summary 根据APISQL表中SQL执行得到数据集
  123. // @Tags GetDataByName
  124. // @Accept json
  125. // @Produce json
  126. // @Param sqlname body string true "sqlname"
  127. // @Param offset body int true "offset"
  128. // @Param pagecount body int true "pagecount"
  129. // @Param returntype body string true "returntype"
  130. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  131. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  132. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  133. // @Router /data/GetDataByName [POST]
  134. func GetDataByName(c *gin.Context) {
  135. appG := app.Gin{C: c}
  136. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  137. fsion := gofasion.NewFasion(string(dataByte))
  138. sqlnamestr := fsion.Get("name").ValueStr()
  139. offset := fsion.Get("offset").ValueDefaultInt(0)
  140. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  141. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  142. tx := restful.Engine.NewSession()
  143. err := tx.Begin()
  144. defer func() {
  145. switch {
  146. case err != nil:
  147. logging.Error("tx.Begin 事务启动失败__error:", err)
  148. if tx != nil {
  149. tx.Rollback()
  150. }
  151. default:
  152. if tx != nil {
  153. err = tx.Commit()
  154. }
  155. }
  156. if tx != nil {
  157. tx.Close()
  158. }
  159. }()
  160. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  161. if sql != "" {
  162. s_params := make([]interface{}, 0)
  163. if fsion.HasKey("parammaps") {
  164. parammaps := fsion.Get("parammaps")
  165. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  166. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  167. }
  168. paramslist := strings.Split(p, ",")
  169. if len(paramslist) > 0 && p != "" {
  170. for _, value := range paramslist {
  171. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  172. if tempv, exists := c.Get("jwt_username"); exists {
  173. s_params = append(s_params, tempv.(string))
  174. } else {
  175. s_params = append(s_params, "")
  176. }
  177. } else {
  178. // if sqlnamestr == "getprocessAnalysis" && value == "tmrtname" {
  179. // tmrArray := parammaps.Get(strings.Trim(value, " ")).Array()
  180. // tmrNameList := []string{}
  181. // for _, tmr := range tmrArray {
  182. // tmrNameList = append(tmrNameList, tmr.ValueStr())
  183. // }
  184. // s_params = append(s_params, strings.Join(tmrNameList, ","))
  185. // } else {
  186. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  187. // }
  188. }
  189. }
  190. }
  191. } else if fsion.HasKey("params") {
  192. params := fsion.Get("params").Array()
  193. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  194. for _, v_params := range params {
  195. s_params = append(s_params, v_params.ValueStr())
  196. }
  197. }
  198. if returntype == "xlsx" {
  199. var xlsxfile *xlsx.File
  200. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  201. //c.File("c:/dd.xlsx")
  202. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  203. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  204. c.Header("Content-Transfer-Encoding", "binary")
  205. _ = xlsxfile.Write(c.Writer)
  206. } else {
  207. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  208. if err != nil {
  209. logging.Error("GetDataByName err: ", err)
  210. msg := geterrmsg(err.Error())
  211. appG.Response(http.StatusOK, e.ERROR, msg)
  212. } else {
  213. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  214. }
  215. }
  216. } else {
  217. appG.Response(http.StatusOK, e.SUCCESS, nil)
  218. }
  219. }
  220. // @Summary 根据APISQL表中SQL执行得到数据集
  221. // @Tags GetDataByName
  222. // @Accept json
  223. // @Produce json
  224. // @Param sqlname body string true "sqlname"
  225. // @Param offset body int true "offset"
  226. // @Param pagecount body int true "pagecount"
  227. // @Param returntype body string true "returntype"
  228. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  229. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  230. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  231. // @Router /data/GetDataByName [POST]
  232. func GetDataBySqlIN(c *gin.Context) {
  233. appG := app.Gin{C: c}
  234. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  235. fsion := gofasion.NewFasion(string(dataByte))
  236. sqlnamestr := fsion.Get("name").ValueStr()
  237. offset := fsion.Get("offset").ValueDefaultInt(0)
  238. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  239. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  240. tx := restful.Engine.NewSession()
  241. err := tx.Begin()
  242. defer func() {
  243. switch {
  244. case err != nil:
  245. logging.Error("tx.Begin 事务启动失败__error:", err)
  246. if tx != nil {
  247. tx.Rollback()
  248. }
  249. default:
  250. if tx != nil {
  251. err = tx.Commit()
  252. }
  253. }
  254. if tx != nil {
  255. tx.Close()
  256. }
  257. }()
  258. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  259. if sql != "" {
  260. s_params := make([]interface{}, 0)
  261. if fsion.HasKey("parammaps") {
  262. parammaps := fsion.Get("parammaps")
  263. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  264. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  265. }
  266. paramslist := strings.Split(p, ",")
  267. if len(paramslist) > 0 && p != "" {
  268. for _, value := range paramslist {
  269. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  270. if tempv, exists := c.Get("jwt_username"); exists {
  271. s_params = append(s_params, tempv.(string))
  272. } else {
  273. s_params = append(s_params, "")
  274. }
  275. } else {
  276. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  277. }
  278. }
  279. }
  280. } else if fsion.HasKey("params") {
  281. params := fsion.Get("params").Array()
  282. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  283. for _, v_params := range params {
  284. s_params = append(s_params, v_params.ValueStr())
  285. }
  286. }
  287. if returntype == "xlsx" {
  288. var xlsxfile *xlsx.File
  289. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  290. //c.File("c:/dd.xlsx")
  291. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  292. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  293. c.Header("Content-Transfer-Encoding", "binary")
  294. _ = xlsxfile.Write(c.Writer)
  295. } else {
  296. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  297. if err != nil {
  298. logging.Error("GetDataByName err: ", err)
  299. msg := geterrmsg(err.Error())
  300. appG.Response(http.StatusOK, e.ERROR, msg)
  301. } else {
  302. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  303. }
  304. }
  305. } else {
  306. appG.Response(http.StatusOK, e.SUCCESS, nil)
  307. }
  308. }
  309. // 错误处理
  310. // 将报错信息处理成汉字
  311. func geterrmsg(errstr string) (msgstr string) {
  312. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
  313. rs := []rune(errstr)
  314. if hzRegexp.MatchString(string(rs[0])) {
  315. msgstr = errstr
  316. return
  317. }
  318. if strings.Contains(errstr, "Duplicate entry") {
  319. strs := strings.Split(errstr, ` key '`)
  320. if len(strs) > 1 {
  321. if len(strs[len(strs)-1]) > 1 {
  322. errstr = "Duplicate entry :" + strs[len(strs)-1]
  323. }
  324. }
  325. }
  326. msg, err := restful.Engine.SQL("SELECT msg FROM err_msg where err = ? ", errstr).QueryString()
  327. if err != nil {
  328. msgstr = errstr
  329. return
  330. }
  331. if msg == nil || len(msg) == 0 {
  332. var param []interface{}
  333. param = append(param, errstr, errstr)
  334. go func() {
  335. tx := restful.Engine.NewSession()
  336. err := tx.Begin()
  337. defer func() {
  338. switch {
  339. case err != nil:
  340. logging.Error("tx.Begin 事务启动失败__error:", err)
  341. if tx != nil {
  342. tx.Rollback()
  343. }
  344. default:
  345. if tx != nil {
  346. err = tx.Commit()
  347. }
  348. }
  349. if tx != nil {
  350. tx.Close()
  351. }
  352. }()
  353. _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
  354. if err != nil {
  355. logging.Error("insert into err_msg(err,msg) err", err)
  356. }
  357. }()
  358. msgstr = errstr
  359. } else {
  360. msgstr = msg[0]["msg"]
  361. }
  362. return
  363. }
  364. // @Summary 根据APISQL表中SQL执行得到数据集
  365. // @Tags GetDataByNameForm
  366. // @Accept json
  367. // @Produce json
  368. // @Param sqlname body json true "sqlname"
  369. // @Param offset query int true "offset"
  370. // @Param pagecount query int true "pagecount"
  371. // @Param returntype query string true "returntype"
  372. // @Param s formData json true "ss"
  373. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  374. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  375. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  376. // @Router /data/GetDataByNameForm [POST]
  377. func GetDataByNameForm(c *gin.Context) {
  378. appG := app.Gin{C: c}
  379. //sqlnamestr := c.PostForm("measureNumber")
  380. //dataByte, _ := ioutil.ReadAll(c.Request.Body)
  381. //fsion := gofasion.NewFasion(string(dataByte))
  382. //sqlnamestr := fsion.Get("name").ValueStr()
  383. //offset := fsion.Get("offset").ValueInt()
  384. //pagecount := fsion.Get("pagecount").ValueInt()
  385. //returntype := fsion.Get("returntype").ValueStr()
  386. //params := fsion.Get("params").Array()
  387. c.Request.ParseForm()
  388. params := c.Request.Form
  389. offset := 0
  390. pageSize_ := 0
  391. returntype := params.Get("page")
  392. if returntype == "" {
  393. returntype = "0"
  394. }
  395. if tempv, exists := c.Get("jwt_username"); exists {
  396. params.Set("JwtUserName", tempv.(string))
  397. } else {
  398. params.Set("JwtUserName", "")
  399. }
  400. sqlnamestr := params.Get("name")
  401. logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
  402. s_params := make([]interface{}, 0)
  403. if returntype == "1" {
  404. pageNum, error := strconv.Atoi(params.Get("pageNum"))
  405. if error != nil {
  406. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
  407. }
  408. pageSize, error := strconv.Atoi(params.Get("pageSize"))
  409. if error != nil {
  410. appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
  411. }
  412. pageSize_ = pageSize
  413. offset = pageNum
  414. }
  415. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  416. paramslist := strings.Split(p, ",")
  417. if len(paramslist) > 0 && p != "" {
  418. for _, value := range paramslist {
  419. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  420. }
  421. }
  422. if sql != "" {
  423. if returntype == "xlsx" {
  424. var xlsxfile *xlsx.File
  425. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  426. c.Header("Content-Type", "application/octet-stream")
  427. c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
  428. c.Header("Content-Transfer-Encoding", "binary")
  429. _ = xlsxfile.Write(c.Writer)
  430. } else {
  431. queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
  432. if err != nil {
  433. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  434. } else {
  435. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  436. }
  437. }
  438. } else {
  439. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  440. }
  441. }
  442. // @Summary 递归获取所有
  443. // @Tags menu
  444. // @Accept json
  445. // @Produce json
  446. // @Param Ton query string true "Ton"
  447. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  448. // @Router /authdata/GetRoleMenus [GET]
  449. func GetRecuDataByName(c *gin.Context) {
  450. appG := app.Gin{C: c}
  451. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  452. fsion := gofasion.NewFasion(string(dataByte))
  453. sqlnamestr := fsion.Get("name").ValueStr()
  454. parentidname := fsion.Get("idname").ValueStr()
  455. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  456. params := make(map[string]interface{})
  457. s_params := make([]interface{}, 0)
  458. if fsion.HasKey("params") {
  459. for _, v_params := range fsion.Get("params").Array() {
  460. s_params = append(s_params, v_params.ValueStr())
  461. }
  462. params["params"] = s_params
  463. } else {
  464. jparams := fsion.Get("parammaps")
  465. paramslist := strings.Split(p, ",")
  466. if len(paramslist) > 0 && p != "" {
  467. for _, value := range paramslist {
  468. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  469. if tempv, exists := c.Get("jwt_username"); exists {
  470. params[value] = tempv.(string)
  471. } else {
  472. params[value] = ""
  473. }
  474. } else {
  475. params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
  476. }
  477. }
  478. }
  479. }
  480. queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
  481. logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  482. if err != nil {
  483. appG.Response(http.StatusOK, e.ERROR, err.Error())
  484. }
  485. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  486. }
  487. // @Summary 根据APISQL表中SQL执行得到数据集
  488. // @Tags GetDataByNames
  489. // @Accept json
  490. // @Produce json
  491. // @RequestBody sqlname query string true "sqlname"
  492. // @Param offset query int true "offset"
  493. // @Param pagecount query int true "pagecount"
  494. // @Param returntype query string true "returntype"
  495. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  496. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  497. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  498. // @Router /data/GetDataByNames [POST]
  499. func GetDataByNames(c *gin.Context) {
  500. appG := app.Gin{C: c}
  501. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  502. fsion := gofasion.NewFasion(string(dataByte))
  503. sqlParams := fsion.Array()
  504. queryData := make(map[string]interface{})
  505. for _, v := range sqlParams {
  506. fsion2 := gofasion.NewFasion(v.Json())
  507. logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
  508. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  509. if sql == "" {
  510. errorm := make(map[string]interface{})
  511. errorm["code"] = e.ERROR
  512. errorm["message"] = "sql没找到"
  513. queryData[fsion2.Get("name").ValueStr()] = errorm
  514. continue
  515. } else if sql != "" {
  516. offset := fsion2.Get("offset").ValueInt()
  517. pagecount := fsion2.Get("pagecount").ValueInt()
  518. returntype := fsion2.Get("returntype").ValueStr()
  519. s_params := make([]interface{}, 0)
  520. if fsion2.HasKey("parammaps") {
  521. parammaps := fsion2.Get("parammaps")
  522. paramslist := strings.Split(p, ",")
  523. if len(paramslist) > 0 && p != "" {
  524. for _, value := range paramslist {
  525. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  526. if tempv, exists := c.Get("jwt_username"); exists {
  527. s_params = append(s_params, tempv.(string))
  528. } else {
  529. s_params = append(s_params, "")
  530. }
  531. } else {
  532. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  533. }
  534. }
  535. }
  536. } else if fsion2.HasKey("params") {
  537. params := fsion2.Get("params").Array()
  538. for _, v_params := range params {
  539. s_params = append(s_params, v_params.ValueStr())
  540. }
  541. }
  542. queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
  543. if err != nil {
  544. errorm := make(map[string]interface{})
  545. errorm["code"] = e.ERROR
  546. errorm["message"] = err.Error()
  547. queryData[fsion2.Get("name").ValueStr()] = errorm
  548. logging.Error("GetDataByNames err: ", err)
  549. continue
  550. } else {
  551. queryData[fsion2.Get("name").ValueStr()] = queryData1
  552. }
  553. }
  554. }
  555. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  556. }
  557. // @Summary 根据APISQL表中SQL执行得到数据集
  558. // @Tags PostDataByNameForm
  559. // @Accept json
  560. // @Produce json
  561. // @Param sqlname query string true "sqlname"
  562. // @Param offset query int true "offset"
  563. // @Param pagecount query int true "pagecount"
  564. // @Param returntype query string true "returntype"
  565. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  566. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  567. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  568. // @Router /data/PostDataByNameForm [POST]
  569. func PostDataByNameForm(c *gin.Context) {
  570. appG := app.Gin{C: c}
  571. c.Request.ParseForm()
  572. params := c.Request.Form
  573. sqlnamestr := params.Get("name")
  574. logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
  575. s_params := make([]interface{}, 0)
  576. sql, p := restful.GetSqlByNameDB(sqlnamestr)
  577. paramslist := strings.Split(p, ",")
  578. if len(paramslist) > 0 {
  579. for _, value := range paramslist {
  580. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  581. }
  582. }
  583. if sql != "" {
  584. queryData, err := execDataBySql(sql, s_params)
  585. if err != nil {
  586. appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
  587. } else {
  588. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
  589. }
  590. } else {
  591. appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
  592. }
  593. }
  594. // @Summary 将数据集转换格式
  595. // @Tags PostDataByNameForm
  596. // @Accept json
  597. // @Produce json
  598. // @Param sqlname query string true "sqlname"
  599. // @Param offset query int true "offset"
  600. // @Param pagecount query int true "pagecount"
  601. // @Param returntype query string true "returntype"
  602. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  603. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  604. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  605. func GetReportform(c *gin.Context) {
  606. appG := app.Gin{C: c}
  607. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  608. fsion := gofasion.NewFasion(string(dataByte))
  609. sqlnamestr := fsion.Get("name").ValueStr()
  610. checked := fsion.Get("checked").ValueStr()
  611. offset := fsion.Get("offset").ValueDefaultInt(0)
  612. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  613. parammaps := fsion.Get("parammaps")
  614. typea := parammaps.Get("typea").ValueDefaultInt(0) //0 全部 1 理论, 2实际
  615. logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
  616. tx := restful.Engine.NewSession()
  617. err := tx.Begin()
  618. defer func() {
  619. switch {
  620. case err != nil:
  621. if tx != nil {
  622. tx.Rollback()
  623. }
  624. default:
  625. if tx != nil {
  626. err = tx.Commit()
  627. }
  628. }
  629. if tx != nil {
  630. tx.Close()
  631. }
  632. }()
  633. queryData, err := praseReportform(sqlnamestr, parammaps, tx, checked, offset, pagecount, typea)
  634. if err != nil {
  635. appG.Response(http.StatusOK, e.ERROR, err.Error())
  636. } else {
  637. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  638. }
  639. }
  640. //保养计划
  641. func GetUpkeepPlan(c *gin.Context) {
  642. appG := app.Gin{C: c}
  643. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  644. fsion := gofasion.NewFasion(string(dataByte))
  645. sqlnamestr := fsion.Get("name").ValueStr()
  646. offset := fsion.Get("offset").ValueDefaultInt(0)
  647. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  648. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  649. month := fsion.Get("month").ValueDefaultStr("map")
  650. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  651. tx := restful.Engine.NewSession()
  652. err := tx.Begin()
  653. defer func() {
  654. switch {
  655. case err != nil:
  656. if tx != nil {
  657. tx.Rollback()
  658. }
  659. default:
  660. if tx != nil {
  661. err = tx.Commit()
  662. }
  663. }
  664. if tx != nil {
  665. tx.Close()
  666. }
  667. }()
  668. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  669. if sql != "" {
  670. s_params := make([]interface{}, 0)
  671. if fsion.HasKey("parammaps") {
  672. parammaps := fsion.Get("parammaps")
  673. paramslist := strings.Split(p, ",")
  674. if len(paramslist) > 0 && p != "" {
  675. for _, value := range paramslist {
  676. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  677. if tempv, exists := c.Get("jwt_username"); exists {
  678. s_params = append(s_params, tempv.(string))
  679. } else {
  680. s_params = append(s_params, "")
  681. }
  682. } else {
  683. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  684. }
  685. }
  686. }
  687. } else if fsion.HasKey("params") {
  688. params := fsion.Get("params").Array()
  689. for _, v_params := range params {
  690. s_params = append(s_params, v_params.ValueStr())
  691. }
  692. }
  693. if returntype == "xlsx" {
  694. var xlsxfile *xlsx.File
  695. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  696. //c.File("c:/dd.xlsx")
  697. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  698. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  699. c.Header("Content-Transfer-Encoding", "binary")
  700. _ = xlsxfile.Write(c.Writer)
  701. } else {
  702. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  703. if err != nil {
  704. appG.Response(http.StatusOK, e.ERROR, err.Error())
  705. } else {
  706. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  707. if v, ok := value["id"]; ok {
  708. //month = "2020-03"
  709. seviceplans, _ := tx.SQL("SELECT * FROM seviceplan where eqId = ? and month=? ", v, month).QueryString() //获取保养计划
  710. if seviceplans != nil {
  711. for _, va := range seviceplans { //根据保养计划获取保养单
  712. //day,_ :=strconv.Atoi(va["day"])
  713. bigupkeeps, _ := tx.SQL("SELECT * FROM bigupkeep where seviceplanId = ?", va["id"]).QueryString() //获取保养计划中的保养单
  714. //buk := make(map[string]map[string]string)
  715. for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
  716. jstr := ""
  717. if bu["plantime"][8:9] == "0" {
  718. jstr = "m" + bu["plantime"][9:]
  719. } else {
  720. jstr = "m" + bu["plantime"][8:]
  721. }
  722. if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
  723. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
  724. } else {
  725. if bu["flowCompeleted"] >= "2" {
  726. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
  727. } else {
  728. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
  729. }
  730. }
  731. }
  732. }
  733. }
  734. }
  735. }
  736. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  737. }
  738. }
  739. } else {
  740. appG.Response(http.StatusOK, e.SUCCESS, nil)
  741. }
  742. }
  743. // @Summary 根据APISQL表中的两条SQL执行得到数据集,其中name1会根据name的每一条去执行
  744. // todo 优化性能 children统一查询
  745. // @Tags PostDataByNameForm
  746. // @Accept json
  747. // @Produce json
  748. // @Param sqlname query string true "sqlname"
  749. // @Param offset query int true "offset"
  750. // @Param pagecount query int true "pagecount"
  751. // @Param returntype query string true "returntype"
  752. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  753. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}"
  754. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  755. func GetArrList(c *gin.Context) {
  756. appG := app.Gin{C: c}
  757. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  758. fsion := gofasion.NewFasion(string(dataByte))
  759. sqlnamestr := fsion.Get("name").ValueStr()
  760. sqlnamestr1 := fsion.Get("name1").ValueStr()
  761. offset := fsion.Get("offset").ValueDefaultInt(0)
  762. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  763. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  764. month := fsion.Get("month").ValueDefaultStr("map")
  765. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  766. tx := restful.Engine.NewSession()
  767. err := tx.Begin()
  768. defer func() {
  769. switch {
  770. case err != nil:
  771. if tx != nil {
  772. tx.Rollback()
  773. }
  774. default:
  775. if tx != nil {
  776. err = tx.Commit()
  777. }
  778. }
  779. if tx != nil {
  780. tx.Close()
  781. }
  782. }()
  783. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  784. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  785. if sql != "" {
  786. s_params := make([]interface{}, 0)
  787. if fsion.HasKey("parammaps") {
  788. parammaps := fsion.Get("parammaps")
  789. paramslist := strings.Split(p, ",")
  790. if len(paramslist) > 0 && p != "" {
  791. for _, value := range paramslist {
  792. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  793. if tempv, exists := c.Get("jwt_username"); exists {
  794. s_params = append(s_params, tempv.(string))
  795. } else {
  796. s_params = append(s_params, "")
  797. }
  798. } else {
  799. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  800. }
  801. }
  802. }
  803. }
  804. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  805. if err != nil {
  806. appG.Response(http.StatusOK, e.ERROR, err.Error())
  807. } else {
  808. paramslist1 := strings.Split(p1, ",")
  809. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  810. s_params1 := make([]interface{}, 0)
  811. if len(paramslist1) > 0 && p1 != "" {
  812. for _, v := range paramslist1 {
  813. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  814. }
  815. }
  816. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  817. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  818. }
  819. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  820. }
  821. } else {
  822. appG.Response(http.StatusOK, e.SUCCESS, nil)
  823. }
  824. }
  825. func GetAccount(c *gin.Context) {
  826. appG := app.Gin{C: c}
  827. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  828. fsion := gofasion.NewFasion(string(dataByte))
  829. sqlnamestr := fsion.Get("name").ValueStr()
  830. offset := fsion.Get("offset").ValueDefaultInt(0)
  831. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  832. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  833. tx := restful.Engine.NewSession()
  834. err := tx.Begin()
  835. defer func() {
  836. switch {
  837. case err != nil:
  838. logging.Error("tx.Begin 事务启动失败__error:", err)
  839. if tx != nil {
  840. tx.Rollback()
  841. }
  842. default:
  843. if tx != nil {
  844. err = tx.Commit()
  845. }
  846. }
  847. if tx != nil {
  848. tx.Close()
  849. }
  850. }()
  851. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  852. if sql != "" {
  853. s_params := make([]interface{}, 0)
  854. if fsion.HasKey("parammaps") {
  855. parammaps := fsion.Get("parammaps")
  856. if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
  857. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  858. }
  859. paramslist := strings.Split(p, ",")
  860. if len(paramslist) > 0 && p != "" {
  861. for _, value := range paramslist {
  862. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  863. if tempv, exists := c.Get("jwt_username"); exists {
  864. s_params = append(s_params, tempv.(string))
  865. } else {
  866. s_params = append(s_params, "")
  867. }
  868. } else {
  869. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  870. }
  871. }
  872. }
  873. } else if fsion.HasKey("params") {
  874. params := fsion.Get("params").Array()
  875. logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  876. for _, v_params := range params {
  877. s_params = append(s_params, v_params.ValueStr())
  878. }
  879. }
  880. if returntype == "xlsx" {
  881. var xlsxfile *xlsx.File
  882. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  883. //c.File("c:/dd.xlsx")
  884. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  885. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  886. c.Header("Content-Transfer-Encoding", "binary")
  887. _ = xlsxfile.Write(c.Writer)
  888. } else {
  889. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  890. if err != nil {
  891. logging.Error("GetDataByName err: ", err)
  892. msg := geterrmsg(err.Error())
  893. appG.Response(http.StatusOK, e.ERROR, msg)
  894. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  895. } else {
  896. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  897. }
  898. }
  899. } else {
  900. appG.Response(http.StatusOK, e.SUCCESS, nil)
  901. }
  902. }
  903. // @Summary 根据APISQL表中SQL执行得到数据集
  904. // @Tags PostDataByName
  905. // @Accept json
  906. // @Produce json
  907. // @Param sqlname query string true "sqlname"
  908. // @Param offset query int true "offset"
  909. // @Param pagecount query int true "pagecount"
  910. // @Param returntype query string true "returntype"
  911. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  912. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  913. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  914. // @Router /data/PostDataByName [POST]
  915. func PostDataByName(c *gin.Context) {
  916. appG := app.Gin{C: c}
  917. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  918. fsion := gofasion.NewFasion(string(dataByte))
  919. sqlnamestr := fsion.Get("name").ValueStr()
  920. s_params := make([]interface{}, 0)
  921. tx := restful.Engine.NewSession()
  922. err := tx.Begin()
  923. defer func() {
  924. switch {
  925. case err != nil:
  926. if tx != nil {
  927. tx.Rollback()
  928. }
  929. default:
  930. if tx != nil {
  931. err = tx.Commit()
  932. }
  933. }
  934. if tx != nil {
  935. tx.Close()
  936. }
  937. }()
  938. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  939. if sql != "" {
  940. if fsion.HasKey("parammaps") {
  941. parammaps := fsion.Get("parammaps")
  942. logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  943. paramslist := strings.Split(p, ",")
  944. if len(paramslist) > 0 && p != "" {
  945. for _, value := range paramslist {
  946. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  947. if tempv, exists := c.Get("jwt_username"); exists {
  948. s_params = append(s_params, tempv.(string))
  949. } else {
  950. s_params = append(s_params, "")
  951. }
  952. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  953. ids, err := setting.SnowIds.NextId()
  954. if err != nil {
  955. ids = time.Now().UnixNano()
  956. logging.Info("create SnowIds err", err)
  957. }
  958. s_params = append(s_params, ids)
  959. } else {
  960. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  961. }
  962. }
  963. }
  964. } else if fsion.HasKey("params") {
  965. params := fsion.Get("params").Array()
  966. logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
  967. //ids,err := setting.SnowIds.NextId()
  968. //if err !=nil{
  969. // ids = time.Now().UnixNano()
  970. // logging.Info("create SnowIds err",err)
  971. //}
  972. //s_params = append(s_params, ids)
  973. for _, v_params := range params {
  974. s_params = append(s_params, v_params.ValueStr())
  975. }
  976. }
  977. queryData, err := execDataBySqlT(sql, s_params, tx)
  978. if err != nil {
  979. logging.Error("PostDataByName err: ", err)
  980. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  981. if (sqlnamestr == "copybarfeedremain" || sqlnamestr == "copyFtdry" || sqlnamestr == "copyPennsieve") &&
  982. strings.Contains(err.Error(), "Duplicate entry") {
  983. appG.Response(http.StatusOK, e.ERROR, "同一栏舍,同一班次不可重复录入")
  984. } else if (sqlnamestr == "copybarmilk" || sqlnamestr == "copyBodyscore" || sqlnamestr == "copyDungsieve" || sqlnamestr == "copyDungscore") &&
  985. strings.Contains(err.Error(), "Duplicate entry") {
  986. appG.Response(http.StatusOK, e.ERROR, "同一栏舍不可重复录入")
  987. } else {
  988. msg := geterrmsg(err.Error())
  989. appG.Response(http.StatusOK, e.ERROR, msg)
  990. }
  991. } else {
  992. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  993. }
  994. } else {
  995. appG.Response(http.StatusOK, e.SUCCESS, nil)
  996. }
  997. }
  998. //人脸识别/格润富德接口
  999. func GetRJSBData(c *gin.Context) {
  1000. appG := app.Gin{C: c}
  1001. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1002. fsion := gofasion.NewFasion(string(dataByte))
  1003. sqlnamestr := fsion.Get("name").ValueStr()
  1004. sqlnamestr1 := fsion.Get("name1").ValueStr()
  1005. offset := fsion.Get("offset").ValueDefaultInt(0)
  1006. pagecount := fsion.Get("plancount").ValueDefaultInt(0)
  1007. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  1008. month := fsion.Get("month").ValueDefaultStr("map")
  1009. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  1010. tx := restful.Engine.NewSession()
  1011. err := tx.Begin()
  1012. defer func() {
  1013. switch {
  1014. case err != nil:
  1015. if tx != nil {
  1016. tx.Rollback()
  1017. }
  1018. default:
  1019. if tx != nil {
  1020. err = tx.Commit()
  1021. }
  1022. }
  1023. if tx != nil {
  1024. tx.Close()
  1025. }
  1026. }()
  1027. //STR :=Httppostdata("http://192.168.1.104:8081/authdata/GetDataBySqlIN","POST",string(dataByte),tx)
  1028. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  1029. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  1030. if sql != "" {
  1031. s_params := make([]interface{}, 0)
  1032. if fsion.HasKey("parammaps") {
  1033. parammaps := fsion.Get("parammaps")
  1034. paramslist := strings.Split(p, ",")
  1035. if len(paramslist) > 0 && p != "" {
  1036. for _, value := range paramslist {
  1037. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1038. if tempv, exists := c.Get("jwt_username"); exists {
  1039. s_params = append(s_params, tempv.(string))
  1040. } else {
  1041. s_params = append(s_params, "")
  1042. }
  1043. } else {
  1044. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1045. }
  1046. }
  1047. }
  1048. }
  1049. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  1050. if err != nil {
  1051. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1052. } else {
  1053. paramslist1 := strings.Split(p1, ",")
  1054. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1055. s_params1 := make([]interface{}, 0)
  1056. if len(paramslist1) > 0 && p1 != "" {
  1057. for _, v := range paramslist1 {
  1058. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  1059. }
  1060. }
  1061. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  1062. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  1063. }
  1064. var wg sync.WaitGroup
  1065. for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  1066. wg.Add(1)
  1067. go func(value map[string]interface{}) {
  1068. defer wg.Done()
  1069. _, err = tx.SQL(`update downloadedplan set havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
  1070. }(value)
  1071. }
  1072. wg.Wait()
  1073. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1074. }
  1075. } else {
  1076. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1077. }
  1078. }
  1079. func PostRJSBData(c *gin.Context) {
  1080. appG := app.Gin{C: c}
  1081. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1082. fsion := gofasion.NewFasion(string(dataByte))
  1083. logging.Info("PostRJSBData err: ", string(dataByte))
  1084. s_params := make([]interface{}, 0)
  1085. tx := restful.Engine.NewSession()
  1086. err := tx.Begin()
  1087. defer func() {
  1088. switch {
  1089. case err != nil:
  1090. if tx != nil {
  1091. tx.Rollback()
  1092. }
  1093. default:
  1094. if tx != nil {
  1095. err = tx.Commit()
  1096. }
  1097. }
  1098. if tx != nil {
  1099. tx.Close()
  1100. }
  1101. }()
  1102. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1103. sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
  1104. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
  1105. sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
  1106. if !fsion.HasKey("parammaps") {
  1107. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1108. return
  1109. }
  1110. parammaps := fsion.Get("parammaps")
  1111. paramslist := strings.Split(p, ",")
  1112. if len(paramslist) > 0 && p != "" {
  1113. for _, value := range paramslist {
  1114. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1115. }
  1116. }
  1117. _, err = tx.SQL(sql, s_params...).Execute()
  1118. if err != nil {
  1119. logging.Error("PostRJSBData err: ", err)
  1120. msg := geterrmsg(err.Error())
  1121. appG.Response(http.StatusOK, e.ERROR, msg)
  1122. return
  1123. }
  1124. s_params = make([]interface{}, 0)
  1125. paramslist = strings.Split(p1, ",")
  1126. if len(paramslist) > 0 && p1 != "" {
  1127. for _, value := range paramslist {
  1128. // if value == "ID" {
  1129. // id := parammaps.Get("ID").ValueStr()
  1130. // pastureid := parammaps.Get("pastureid").ValueStr()
  1131. // datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  1132. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1133. // if err != nil {
  1134. // logging.Error("PostRJSBData err: ", err)
  1135. // msg := geterrmsg(err.Error())
  1136. // appG.Response(http.StatusOK, e.ERROR, msg)
  1137. // return
  1138. // }
  1139. // for _, item := range datalist {
  1140. // id = item["id"]
  1141. // }
  1142. // s_params = append(s_params, id)
  1143. // } else {
  1144. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1145. // }
  1146. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1147. }
  1148. }
  1149. _, err = tx.SQL(sql1, s_params...).Execute()
  1150. if err != nil {
  1151. logging.Error("PostRJSBData1 err: ", err)
  1152. msg := geterrmsg(err.Error())
  1153. appG.Response(http.StatusOK, e.ERROR, msg)
  1154. return
  1155. }
  1156. s_params = make([]interface{}, 0)
  1157. paramslist = strings.Split(p2, ",")
  1158. if len(paramslist) > 0 && p2 != "" {
  1159. for _, value := range paramslist {
  1160. if value == "ID" {
  1161. id := parammaps.Get("ID").ValueStr()
  1162. pastureid := parammaps.Get("pastureid").ValueStr()
  1163. datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  1164. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1165. if err != nil {
  1166. logging.Error("PostRJSBData err: ", err)
  1167. msg := geterrmsg(err.Error())
  1168. appG.Response(http.StatusOK, e.ERROR, msg)
  1169. return
  1170. }
  1171. for _, item := range datalist {
  1172. id = item["id"]
  1173. }
  1174. s_params = append(s_params, id)
  1175. } else {
  1176. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1177. }
  1178. }
  1179. }
  1180. _, err = tx.SQL(sql2, s_params...).Execute()
  1181. if err != nil {
  1182. logging.Error("PostRJSBData2 err: ", err)
  1183. msg := geterrmsg(err.Error())
  1184. appG.Response(http.StatusOK, e.ERROR, msg)
  1185. return
  1186. }
  1187. s_params = make([]interface{}, 0)
  1188. paramslist = strings.Split(p3, ",")
  1189. if len(paramslist) > 0 && p3 != "" {
  1190. for _, value := range paramslist {
  1191. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1192. }
  1193. }
  1194. _, err = tx.SQL(sql3, s_params...).Execute()
  1195. if err != nil {
  1196. logging.Error("PostRJSBData3 err: ", err)
  1197. msg := geterrmsg(err.Error())
  1198. appG.Response(http.StatusOK, e.ERROR, msg)
  1199. return
  1200. }
  1201. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1202. }
  1203. func PostRJSBDatas(c *gin.Context) {
  1204. appG := app.Gin{C: c}
  1205. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1206. fsions := gofasion.NewFasion(string(dataByte)).Array()
  1207. logging.Info("PostRJSBDatas err: ", string(dataByte))
  1208. tx := restful.Engine.NewSession()
  1209. err := tx.Begin()
  1210. defer func() {
  1211. switch {
  1212. case err != nil:
  1213. if tx != nil {
  1214. tx.Rollback()
  1215. }
  1216. default:
  1217. if tx != nil {
  1218. err = tx.Commit()
  1219. }
  1220. }
  1221. if tx != nil {
  1222. tx.Close()
  1223. }
  1224. }()
  1225. sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
  1226. sql1, p1 := restful.GetSqlByNameDBT("updated1YJV2", tx)
  1227. sql2, p2 := restful.GetSqlByNameDBT("updated1execYJV2", tx)
  1228. sql3, p3 := restful.GetSqlByNameDBT("updated2YJV2", tx)
  1229. for _, fsion := range fsions {
  1230. if !fsion.HasKey("parammaps") {
  1231. appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
  1232. return
  1233. }
  1234. parammaps := fsion.Get("parammaps")
  1235. s_params := make([]interface{}, 0)
  1236. paramslist := strings.Split(p, ",")
  1237. if len(paramslist) > 0 && p != "" {
  1238. for _, value := range paramslist {
  1239. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1240. }
  1241. }
  1242. _, err = tx.SQL(sql, s_params...).Execute()
  1243. if err != nil {
  1244. logging.Error("PostRJSBData err: ", err)
  1245. msg := geterrmsg(err.Error())
  1246. appG.Response(http.StatusOK, e.ERROR, msg)
  1247. return
  1248. }
  1249. s_params = make([]interface{}, 0)
  1250. paramslist = strings.Split(p1, ",")
  1251. if len(paramslist) > 0 && p1 != "" {
  1252. for _, value := range paramslist {
  1253. // if value == "ID" {
  1254. // id := parammaps.Get("ID").ValueStr()
  1255. // pastureid := parammaps.Get("pastureid").ValueStr()
  1256. // datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  1257. // d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1258. // if err != nil {
  1259. // logging.Error("PostRJSBData err: ", err)
  1260. // msg := geterrmsg(err.Error())
  1261. // appG.Response(http.StatusOK, e.ERROR, msg)
  1262. // return
  1263. // }
  1264. // for _, item := range datalist {
  1265. // id = item["id"]
  1266. // }
  1267. // s_params = append(s_params, id)
  1268. // } else {
  1269. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1270. // }
  1271. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1272. }
  1273. }
  1274. _, err = tx.SQL(sql1, s_params...).Execute()
  1275. if err != nil {
  1276. logging.Error("PostRJSBData1 err: ", err)
  1277. msg := geterrmsg(err.Error())
  1278. appG.Response(http.StatusOK, e.ERROR, msg)
  1279. return
  1280. }
  1281. s_params = make([]interface{}, 0)
  1282. paramslist = strings.Split(p2, ",")
  1283. if len(paramslist) > 0 && p2 != "" {
  1284. for _, value := range paramslist {
  1285. if value == "ID" {
  1286. id := parammaps.Get("ID").ValueStr()
  1287. pastureid := parammaps.Get("pastureid").ValueStr()
  1288. datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec d2 on d1.id = d2.id where d1.pid = (select pid from downloadplandtl1 where id = ? and pastureid = ? ) and
  1289. d1.sort = (select sort from downloadplandtl1 where id = ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
  1290. if err != nil {
  1291. logging.Error("PostRJSBData err: ", err)
  1292. msg := geterrmsg(err.Error())
  1293. appG.Response(http.StatusOK, e.ERROR, msg)
  1294. return
  1295. }
  1296. for _, item := range datalist {
  1297. id = item["id"]
  1298. }
  1299. s_params = append(s_params, id)
  1300. } else {
  1301. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1302. }
  1303. // s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1304. }
  1305. }
  1306. _, err = tx.SQL(sql2, s_params...).Execute()
  1307. if err != nil {
  1308. logging.Error("PostRJSBData2 err: ", err)
  1309. msg := geterrmsg(err.Error())
  1310. appG.Response(http.StatusOK, e.ERROR, msg)
  1311. return
  1312. }
  1313. s_params = make([]interface{}, 0)
  1314. paramslist = strings.Split(p3, ",")
  1315. if len(paramslist) > 0 && p3 != "" {
  1316. for _, value := range paramslist {
  1317. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1318. }
  1319. }
  1320. _, err = tx.SQL(sql3, s_params...).Execute()
  1321. if err != nil {
  1322. logging.Error("PostRJSBData3 err: ", err)
  1323. msg := geterrmsg(err.Error())
  1324. appG.Response(http.StatusOK, e.ERROR, msg)
  1325. return
  1326. }
  1327. }
  1328. appG.Response(http.StatusOK, e.SUCCESS, "ok")
  1329. }
  1330. // @Summary 根据APISQL表中SQL执行得到数据集
  1331. // @Tags ExecDataByConfig
  1332. // @Accept json
  1333. // @Produce json
  1334. // @Param sqlname query string true "sqlname"
  1335. // @Param offset query int true "offset"
  1336. // @Param pagecount query int true "pagecount"
  1337. // @Param returntype query string true "returntype"
  1338. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1339. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1340. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1341. // @Router /data/PostDataByName [POST]
  1342. func ExecDataByConfig(c *gin.Context) {
  1343. appG := app.Gin{C: c}
  1344. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1345. tempval_ := make(map[string]interface{})
  1346. tempCommon := make(map[string]interface{})
  1347. tempval := make([]map[string]interface{}, 0)
  1348. err := json.Unmarshal(dataByte, &tempval_)
  1349. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1350. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1351. if err != nil {
  1352. } else {
  1353. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1354. tempCommon = v
  1355. }
  1356. if v, ok := tempval_["data"].([]interface{}); ok {
  1357. for _, Tvalue := range v {
  1358. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1359. tempval = append(tempval, v1)
  1360. }
  1361. }
  1362. }
  1363. tx := restful.Engine.NewSession()
  1364. err := tx.Begin()
  1365. if err != nil {
  1366. logging.Error("tx.Begin 事务启动失败__error:", err)
  1367. }
  1368. defer func() {
  1369. switch {
  1370. case err != nil:
  1371. if tx != nil {
  1372. tx.Rollback()
  1373. }
  1374. default:
  1375. if tx != nil {
  1376. err = tx.Commit()
  1377. }
  1378. }
  1379. if tx != nil {
  1380. tx.Close()
  1381. }
  1382. }()
  1383. if err == nil {
  1384. if tempv, exists := c.Get("jwt_username"); exists {
  1385. tempCommon["jwt_username"] = tempv.(string)
  1386. }
  1387. for _, paramvalue := range tempval {
  1388. if _, ok := paramvalue["resultname"]; !ok {
  1389. paramvalue["resultname"] = paramvalue["name"]
  1390. }
  1391. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1392. if err != nil {
  1393. logging.Error("ExecDataParam error:", err)
  1394. break
  1395. }
  1396. }
  1397. if err == nil {
  1398. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1399. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1400. } else {
  1401. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1402. }
  1403. } else {
  1404. msg := geterrmsg(err.Error())
  1405. appG.Response(http.StatusOK, e.ERROR, msg)
  1406. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1407. }
  1408. }
  1409. }
  1410. if err != nil {
  1411. msg := geterrmsg(err.Error())
  1412. appG.Response(http.StatusOK, e.ERROR, msg)
  1413. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  1414. }
  1415. }
  1416. func interfacetostring(val interface{}) string {
  1417. switch val.(type) {
  1418. case string:
  1419. ss := val.(string)
  1420. return ss
  1421. break
  1422. case int:
  1423. ss := val.(int)
  1424. return strconv.Itoa(ss)
  1425. break
  1426. case int64:
  1427. ss := val.(int64)
  1428. return strconv.FormatInt(ss, 10)
  1429. break
  1430. case float64:
  1431. ss := val.(float64)
  1432. return strconv.FormatFloat(ss, 'E', -1, 32)
  1433. break
  1434. }
  1435. return ""
  1436. }
  1437. func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
  1438. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1439. tempstrb := strings.IndexAny(valuestring, "@")
  1440. tempstre := strings.IndexAny(valuestring, ".")
  1441. if tempstrb > -1 && tempstre > -1 {
  1442. for _, ParamMapList := range ParamMap {
  1443. if v, ok := ParamMapList["resultname"]; ok {
  1444. if v == valuestring[tempstrb+1:tempstre] {
  1445. if v1, ok := ParamMapList["resultmaps"]; ok {
  1446. if newA, ok := v1.([]map[string]interface{}); ok {
  1447. return interfacetostring(newA[0][valuestring[tempstre+1:]])
  1448. } else if newA, ok := v1.(map[string]interface{}); ok {
  1449. return interfacetostring(newA[valuestring[tempstre+1:]])
  1450. }
  1451. }
  1452. }
  1453. }
  1454. }
  1455. } else {
  1456. return valuestring
  1457. }
  1458. } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
  1459. return strconv.FormatInt(int64(valuestring), 10)
  1460. }
  1461. return ""
  1462. }
  1463. func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
  1464. if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
  1465. tempstrb := strings.IndexAny(valuestring, "@")
  1466. tempstre := strings.IndexAny(valuestring, ".")
  1467. if tempstrb > -1 && tempstre > -1 {
  1468. if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
  1469. if s, ok := v.(string); ok {
  1470. return s
  1471. } else if s, ok := v.(float64); ok {
  1472. return strconv.FormatFloat(s, 'f', -1, 64)
  1473. // return strconv.FormatInt(int64(s), 10)
  1474. }
  1475. }
  1476. }
  1477. }
  1478. return ""
  1479. }
  1480. 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) {
  1481. sqlname := fasion["name"].(string)
  1482. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  1483. if v, ok := fasion["type"]; ok {
  1484. sqltype = v.(string)
  1485. }
  1486. sql := ""
  1487. p := ""
  1488. s_params := make([]interface{}, 0)
  1489. if sqltype != "" {
  1490. sql, p = restful.GetSqlByName(sqlname, tx)
  1491. //sqlApi, _ := models.GetApisqlByName(sqlname)
  1492. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  1493. paramslist := strings.Split(p, ",")
  1494. if len(paramslist) > 0 && p != "" {
  1495. for _, value := range paramslist {
  1496. ss := ""
  1497. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1498. ids, err := setting.SnowIds.NextId()
  1499. if err != nil {
  1500. ids = time.Now().UnixNano()
  1501. logging.Info("create SnowIds err", err)
  1502. }
  1503. s_params = append(s_params, ids)
  1504. } else {
  1505. if ss == "" && CommonParamMap != nil {
  1506. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  1507. ss = valuestring
  1508. tempstrb := strings.IndexAny(valuestring, "@")
  1509. tempstre := strings.IndexAny(valuestring, ".")
  1510. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  1511. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  1512. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  1513. }
  1514. } else {
  1515. ss = ""
  1516. }
  1517. }
  1518. }
  1519. if ss == "" && ParentParamMap != nil {
  1520. ss = getParamValue_(v, value, ParentParamMap)
  1521. }
  1522. if ss == "" && sameParamMap != nil {
  1523. ss = getParamValue(v, value, sameParamMap)
  1524. }
  1525. if ss == "" && ParamMap != nil {
  1526. ss = getParamValue(v, value, ParamMap)
  1527. }
  1528. s_params = append(s_params, ss)
  1529. }
  1530. }
  1531. }
  1532. }
  1533. }
  1534. if sql == "" {
  1535. sqltype = ""
  1536. }
  1537. if sqltype == "s1" {
  1538. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1539. if v, ok := tempValParam.(map[string]interface{}); ok {
  1540. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1541. }
  1542. if err != nil {
  1543. return nil, err
  1544. }
  1545. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1546. if err != nil {
  1547. return nil, err
  1548. }
  1549. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1550. } else if sqltype == "sm" {
  1551. tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
  1552. if v, ok := tempValParam.(map[string]interface{}); ok {
  1553. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1554. } else {
  1555. }
  1556. if err != nil {
  1557. return nil, err
  1558. }
  1559. err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1560. if err != nil {
  1561. return nil, err
  1562. }
  1563. return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
  1564. } else if sqltype == "v" {
  1565. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  1566. if v, ok := tempValParam.(map[string]interface{}); ok {
  1567. fasion["resultmaps"] = v["list"].([]map[string]interface{})
  1568. } else {
  1569. }
  1570. if err != nil {
  1571. return nil, err
  1572. }
  1573. if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
  1574. return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
  1575. }
  1576. } else if sqltype == "e" {
  1577. tempVal_arrary := make([]map[string]interface{}, 0)
  1578. tempVal_map := make(map[string]interface{})
  1579. tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
  1580. if err == nil {
  1581. fasion["resultmaps"] = tempValParam.(map[string]interface{})
  1582. tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
  1583. tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
  1584. tempVal_arrary = append(tempVal_arrary, tempVal_map)
  1585. return tempVal_arrary, err
  1586. }
  1587. return nil, err
  1588. } else {
  1589. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  1590. err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  1591. if err != nil {
  1592. return nil, err
  1593. }
  1594. return nil, err
  1595. }
  1596. }
  1597. return nil, nil
  1598. }
  1599. func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  1600. var err error
  1601. subarray, ok := fasion["children"]
  1602. if ok {
  1603. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  1604. tempVal_arrary := make([]map[string]interface{}, 0)
  1605. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  1606. tempVal_ := make(map[string]interface{})
  1607. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  1608. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  1609. } else {
  1610. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  1611. }
  1612. tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  1613. if err != nil {
  1614. return err
  1615. }
  1616. tempVal_arrary = append(tempVal_arrary, tempVal_)
  1617. }
  1618. v.(map[string]interface{})["children"] = tempVal_arrary
  1619. }
  1620. }
  1621. return nil
  1622. }
  1623. // @Summary 删除图片
  1624. // @Tags RemovePicByName
  1625. // @Accept json
  1626. // @Produce json
  1627. // @Param sqlname query string true "sqlname"
  1628. // @Param offset query int true "offset"
  1629. // @Param pagecount query int true "pagecount"
  1630. // @Param returntype query string true "returntype"
  1631. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1632. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1633. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1634. // @Router /data/PostDataByName [POST]
  1635. func RemovePicByName(c *gin.Context) {
  1636. logging.Info("RemovePicByName ", c.Keys)
  1637. appG := app.Gin{C: c}
  1638. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1639. fsion := gofasion.NewFasion(string(dataByte))
  1640. sqlnamestr := fsion.Get("name").ValueStr()
  1641. picname := fsion.Get("picname").ValueStr()
  1642. sql, _ := restful.GetSqlByNameDB(sqlnamestr)
  1643. params := fsion.Get("params").Array()
  1644. s_params := make([]interface{}, 0)
  1645. for _, v_params := range params {
  1646. s_params = append(s_params, v_params.ValueStr())
  1647. }
  1648. if sql != "" {
  1649. queryData, err := execDataBySql(sql, s_params)
  1650. if picname != "" {
  1651. // Destination
  1652. distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
  1653. err := os.Remove(distPath) //删除文件test.txt
  1654. if err != nil {
  1655. //如果删除失败则输出 file remove Error!
  1656. fmt.Println("file remove Error!")
  1657. //输出错误详细信息
  1658. fmt.Printf("%s", err)
  1659. } else {
  1660. //如果删除成功则输出 file remove OK!
  1661. fmt.Print("file remove OK!")
  1662. }
  1663. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
  1664. err = os.Remove(distPath) //删除文件test.txt
  1665. if err != nil {
  1666. //如果删除失败则输出 file remove Error!
  1667. fmt.Println("file remove Error!")
  1668. //输出错误详细信息
  1669. fmt.Printf("%s", err)
  1670. } else {
  1671. //如果删除成功则输出 file remove OK!
  1672. fmt.Print("file remove OK!")
  1673. }
  1674. }
  1675. if err != nil {
  1676. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1677. } else {
  1678. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1679. }
  1680. } else {
  1681. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1682. }
  1683. }
  1684. // @Summary 删除文件
  1685. // @Tags RemoveFileByName
  1686. // @Accept json
  1687. // @Produce json
  1688. // @Param sqlname query string true "sqlname"
  1689. // @Param offset query int true "offset"
  1690. // @Param pagecount query int true "pagecount"
  1691. // @Param returntype query string true "returntype"
  1692. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1693. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1694. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1695. // @Router /data/PostDataByName [POST]
  1696. func RemoveFileByName(c *gin.Context) {
  1697. appG := app.Gin{C: c}
  1698. id := c.Param("id")
  1699. logging.Info("DownloadFile ", c.Keys, id)
  1700. eqdoc, err := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", id).QueryString()
  1701. if eqdoc == nil {
  1702. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1703. return
  1704. }
  1705. distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
  1706. err = os.Remove(distPath) //删除文件test.txt
  1707. if err != nil {
  1708. //如果删除失败则输出 file remove Error!
  1709. fmt.Println("file remove Error!")
  1710. //输出错误详细信息
  1711. fmt.Printf("%s", err)
  1712. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1713. return
  1714. }
  1715. _, err = restful.Engine.SQL("delete FROM eq_doc where id = ? ", id).QueryString()
  1716. appG.Response(http.StatusOK, e.SUCCESS, "OK")
  1717. }
  1718. // @Summary 根据APISQL表中SQL执行得到数据集
  1719. // @Tags PostDataByName
  1720. // @Accept json
  1721. // @Produce json
  1722. // @Param sqlname query string true "sqlname"
  1723. // @Param offset query int true "offset"
  1724. // @Param pagecount query int true "pagecount"
  1725. // @Param returntype query string true "returntype"
  1726. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1727. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1728. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1729. // @Router /data/PostDataByName [POST]
  1730. func UpdateDataRelation(c *gin.Context) {
  1731. appG := app.Gin{C: c}
  1732. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1733. fsion := gofasion.NewFasion(string(dataByte))
  1734. tablename := fsion.Get("name").ValueStr()
  1735. dataname := fsion.Get("dataname").ValueStr()
  1736. datavalue := fsion.Get("datavalue").ValueStr()
  1737. valuename := fsion.Get("valuename").ValueStr()
  1738. logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
  1739. values := fsion.Get("values").Array()
  1740. tx := restful.Engine.NewSession()
  1741. err := tx.Begin()
  1742. defer func() {
  1743. switch {
  1744. case err != nil:
  1745. if tx != nil {
  1746. tx.Rollback()
  1747. }
  1748. default:
  1749. if tx != nil {
  1750. err = tx.Commit()
  1751. }
  1752. }
  1753. if tx != nil {
  1754. tx.Close()
  1755. }
  1756. }()
  1757. insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " +
  1758. " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
  1759. d_params := make([]interface{}, 4)
  1760. d_params[0] = datavalue
  1761. s_params := ""
  1762. for _, v_values := range values {
  1763. d_params[1] = v_values.ValueStr()
  1764. if s_params == "" {
  1765. s_params = v_values.ValueStr()
  1766. } else {
  1767. s_params = s_params + "," + v_values.ValueStr()
  1768. }
  1769. d_params[2] = d_params[1]
  1770. d_params[3] = d_params[0]
  1771. _, err := execDataBySqlT(insertSqlstr, d_params, tx)
  1772. if err != nil {
  1773. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1774. break
  1775. }
  1776. }
  1777. if s_params != "" {
  1778. deleteSqlstr := "delete from " + tablename + " " +
  1779. " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
  1780. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1781. if err != nil {
  1782. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1783. } else if err == nil {
  1784. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1785. }
  1786. } else {
  1787. deleteSqlstr := "delete from " + tablename + " " +
  1788. " where " + dataname + " = " + datavalue
  1789. queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
  1790. if err != nil {
  1791. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1792. } else if err == nil {
  1793. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1794. }
  1795. }
  1796. }
  1797. // @Summary 根据APISQL表中SQL执行得到数据集
  1798. // @Tags PostDatasByName
  1799. // @Accept json
  1800. // @Produce json
  1801. // @Param sqlname query string true "sqlname"
  1802. // @Param offset query int true "offset"
  1803. // @Param pagecount query int true "pagecount"
  1804. // @Param returntype query string true "returntype"
  1805. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1806. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1807. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1808. // @Router /data/PostDatasByName [POST]
  1809. func PostDataByNames(c *gin.Context) {
  1810. appG := app.Gin{C: c}
  1811. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1812. fsion := gofasion.NewFasion(string(dataByte))
  1813. sqlParams := fsion.Get("array").Array()
  1814. queryData := make(map[string]interface{})
  1815. for _, v := range sqlParams {
  1816. fsion2 := gofasion.NewFasion(v.Json())
  1817. ss := fsion2.Get("name")
  1818. aa := fsion2.Get("params")
  1819. fmt.Println(ss, aa)
  1820. logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
  1821. sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
  1822. if sql == "" {
  1823. errorm := make(map[string]interface{})
  1824. errorm["code"] = e.ERROR
  1825. errorm["message"] = "sql没有找到"
  1826. errorm["param"] = ""
  1827. queryData[fsion2.Get("name").ValueStr()] = errorm
  1828. continue
  1829. } else if sql != "" {
  1830. s_params := make([]interface{}, 0)
  1831. if fsion2.HasKey("parammaps") {
  1832. parammaps := fsion2.Get("parammaps")
  1833. paramslist := strings.Split(p, ",")
  1834. if len(paramslist) > 0 && p != "" {
  1835. for _, value := range paramslist {
  1836. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  1837. if tempv, exists := c.Get("jwt_username"); exists {
  1838. s_params = append(s_params, tempv.(string))
  1839. } else {
  1840. s_params = append(s_params, "")
  1841. }
  1842. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  1843. ids, err := setting.SnowIds.NextId()
  1844. if err != nil {
  1845. ids = time.Now().UnixNano()
  1846. logging.Info("create SnowIds err", err)
  1847. }
  1848. s_params = append(s_params, ids)
  1849. } else {
  1850. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  1851. }
  1852. }
  1853. }
  1854. } else if fsion2.HasKey("params") {
  1855. params := fsion2.Get("params").Array()
  1856. //ids,err := setting.SnowIds.NextId()
  1857. //if err !=nil{
  1858. // ids = time.Now().UnixNano()
  1859. // logging.Info("create SnowIds err",err)
  1860. //}
  1861. //s_params = append(s_params, ids)
  1862. for _, v_params := range params {
  1863. s_params = append(s_params, v_params.ValueStr())
  1864. }
  1865. }
  1866. _, err := execDataBySql(sql, s_params)
  1867. if err != nil {
  1868. logging.Error("PostDataByName err: ", err)
  1869. errorm := make(map[string]interface{})
  1870. errorm["code"] = e.ERROR
  1871. errorm["message"] = err.Error()
  1872. errorm["param"] = s_params
  1873. queryData[fsion2.Get("name").ValueStr()] = errorm
  1874. continue
  1875. } else {
  1876. errorm := make(map[string]interface{})
  1877. errorm["code"] = e.SUCCESS
  1878. errorm["message"] = "success"
  1879. queryData[fsion2.Get("name").ValueStr()] = errorm
  1880. continue
  1881. }
  1882. } else {
  1883. errorm := make(map[string]interface{})
  1884. errorm["code"] = e.ERROR
  1885. errorm["message"] = "NO SQL"
  1886. errorm["param"] = ""
  1887. queryData[fsion2.Get("name").ValueStr()] = errorm
  1888. }
  1889. }
  1890. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  1891. }
  1892. func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
  1893. if offset > 0 {
  1894. offset = offset - 1
  1895. }
  1896. //if pagecount == 0 {
  1897. // pagecount = setting.AppSetting.PageSize
  1898. //}else if pagecount>setting.AppSetting.PageSize{
  1899. // pagecount = setting.AppSetting.PageSize
  1900. //}
  1901. if returntype == "list" {
  1902. queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
  1903. return queryData, err
  1904. } else if returntype == "listlist" {
  1905. queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
  1906. return queryData, err
  1907. } else {
  1908. queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
  1909. return queryData, err
  1910. }
  1911. }
  1912. func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1913. if offset > 0 {
  1914. offset = offset - 1
  1915. }
  1916. //if pagecount == 0 {
  1917. // pagecount = setting.AppSetting.PageSize
  1918. //}else if pagecount>setting.AppSetting.PageSize{
  1919. // pagecount = setting.AppSetting.PageSize
  1920. //}
  1921. if returntype == "list" {
  1922. queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
  1923. return queryData, err
  1924. } else if returntype == "listlist" {
  1925. queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
  1926. return queryData, err
  1927. } else {
  1928. fmt.Println(params)
  1929. queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
  1930. return queryData, err
  1931. }
  1932. }
  1933. func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
  1934. paramslist := strings.Split(Params, ",")
  1935. s_params := make([]interface{}, 0)
  1936. if isList {
  1937. for _, v_params := range thisParams["params"].([]interface{}) {
  1938. s_params = append(s_params, v_params)
  1939. }
  1940. } else {
  1941. paramslist := strings.Split(Params, ",")
  1942. if len(paramslist) > 0 && Params != "" {
  1943. for _, value := range paramslist {
  1944. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1945. }
  1946. }
  1947. }
  1948. queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
  1949. for _, queryData_ := range queryData {
  1950. if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
  1951. if isList {
  1952. if queryData_[idname] != nil {
  1953. thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
  1954. }
  1955. } else {
  1956. if queryData_[idname] != nil {
  1957. thisParams[idname] = queryData_[idname].(interface{})
  1958. }
  1959. if len(paramslist) > 0 && Params != "" {
  1960. s_params = make([]interface{}, 0)
  1961. for _, value := range paramslist {
  1962. s_params = append(s_params, thisParams[strings.Trim(value, " ")])
  1963. }
  1964. }
  1965. }
  1966. queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
  1967. } else {
  1968. }
  1969. }
  1970. return queryData, err
  1971. }
  1972. func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1973. queryData, err := restful.ExecQuery(sqlstr, params)
  1974. return queryData, err
  1975. }
  1976. func execDataBySqlT(sqlstr string, params []interface{}, tx *xorm.Session) (interface{}, error) {
  1977. queryData, err := restful.ExecQueryT(sqlstr, params, tx)
  1978. return queryData, err
  1979. }
  1980. func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
  1981. queryData, err := restful.ExecQuery(sqlstr, params)
  1982. return queryData, err
  1983. }
  1984. // @Summary 导入excel文件到数据库,excel第一行作为参数
  1985. // @Tags ImportExcel
  1986. // @Accept json
  1987. // @Produce json
  1988. // @Param file query string true "文件名"
  1989. // @Param name header string true "执行sql的名字"
  1990. // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
  1991. // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}"
  1992. // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
  1993. // @Router /data/ImportExcel [POST]
  1994. func ImportExcel(c *gin.Context) {
  1995. appG := app.Gin{C: c}
  1996. inputdata := ""
  1997. c.Request.ParseForm()
  1998. params := c.Request.Form
  1999. file, _, err := c.Request.FormFile("file")
  2000. if err != nil {
  2001. appG.Response(http.StatusOK, e.ERROR, err)
  2002. return
  2003. }
  2004. sqlnamestrs := params.Get("name")
  2005. sheetname := params.Get("sheetname")
  2006. pastureid := params.Get("pastureid")
  2007. //importParams := params.Get("importParams")
  2008. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  2009. // 必输项参数 (字符串格式 "field1,field2,field3")
  2010. requiredParams := params.Get("requiredParams")
  2011. // 日期参数
  2012. dateParams := params.Get("dateParams")
  2013. // 数字参数
  2014. numParams := params.Get("numParams")
  2015. //将字符串分割开
  2016. dateParamslist := strings.Split(dateParams, ",")
  2017. requiredParamslist := strings.Split(requiredParams, ",")
  2018. numParamslist := strings.Split(numParams, ",")
  2019. queryData := make([]interface{}, 0)
  2020. sqlslist := strings.Split(sqlnamestrs, ",")
  2021. xlsx1, err := excelize.OpenReader(file)
  2022. if err != nil {
  2023. fmt.Println(err)
  2024. return
  2025. }
  2026. ok := 0
  2027. error := 0
  2028. isdone := true
  2029. rows, _ := xlsx1.GetRows(sheetname)
  2030. // 限制10000条,多余的截取掉
  2031. if len(rows) > 10000 {
  2032. rows = rows[:10000]
  2033. }
  2034. for i, row := range rows {
  2035. if i > 0 {
  2036. entry := make(map[string]interface{})
  2037. outentry := make(map[string]interface{})
  2038. for j, colCell := range rows[0] {
  2039. for k, colCell1 := range row {
  2040. if j == k {
  2041. outentry[colCell] = colCell1
  2042. entry[colCell] = colCell1
  2043. }
  2044. }
  2045. }
  2046. inputdata = ""
  2047. a := ""
  2048. fmt.Println(outentry, entry)
  2049. //校验日期格式
  2050. for _, v := range dateParamslist {
  2051. if v == "" {
  2052. continue
  2053. }
  2054. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  2055. dtime, err := TransfTime(d.(string))
  2056. if err != nil {
  2057. a = strings.Trim(v, " ")
  2058. break
  2059. }
  2060. outentry[strings.Trim(v, " ")] = dtime
  2061. }
  2062. }
  2063. if a != "" {
  2064. outentry["error_msg"] = a + " 格式错误"
  2065. error++
  2066. queryData = append(queryData, outentry)
  2067. continue
  2068. }
  2069. a = ""
  2070. //校验必填格式
  2071. for _, v := range requiredParamslist {
  2072. if v == "" {
  2073. continue
  2074. }
  2075. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  2076. a = strings.Trim(v, " ")
  2077. break
  2078. }
  2079. }
  2080. if a != "" {
  2081. outentry["error_msg"] = a + " 未填或格式错误"
  2082. error++
  2083. queryData = append(queryData, outentry)
  2084. continue
  2085. }
  2086. a = ""
  2087. //校验数字格式
  2088. for _, v := range numParamslist {
  2089. if v == "" {
  2090. continue
  2091. }
  2092. d, ok := outentry[strings.Trim(v, " ")]
  2093. if !ok || d == "" {
  2094. outentry[strings.Trim(v, " ")] = 0
  2095. } else {
  2096. var fl float64
  2097. switch d.(type) {
  2098. case string:
  2099. fl, err = strconv.ParseFloat(d.(string), 64)
  2100. }
  2101. if err != nil || fl < 0 {
  2102. a = strings.Trim(v, " ")
  2103. break
  2104. }
  2105. }
  2106. }
  2107. if a != "" {
  2108. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  2109. error++
  2110. queryData = append(queryData, outentry)
  2111. continue
  2112. }
  2113. tx := restful.Engine.NewSession()
  2114. err := tx.Begin()
  2115. for _, sqlnamestr := range sqlslist {
  2116. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  2117. paramslist := strings.Split(paramslists, ",")
  2118. if len(paramslist) > 0 {
  2119. s_params := make([]interface{}, 0)
  2120. for _, value := range paramslist {
  2121. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2122. if tempv, exists := c.Get("jwt_username"); exists {
  2123. s_params = append(s_params, tempv.(string))
  2124. } else {
  2125. s_params = append(s_params, "")
  2126. }
  2127. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  2128. s_params = append(s_params, pastureid)
  2129. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  2130. ids, err := setting.SnowIds.NextId()
  2131. if err != nil {
  2132. ids = time.Now().UnixNano()
  2133. logging.Info("create SnowIds err", err)
  2134. }
  2135. s_params = append(s_params, ids)
  2136. } else {
  2137. if outentry[strings.Trim(value, " ")] == nil {
  2138. s_params = append(s_params, "")
  2139. } else {
  2140. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  2141. }
  2142. }
  2143. }
  2144. outentry["input"] = inputdata
  2145. fmt.Println(sql, s_params)
  2146. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  2147. if err != nil {
  2148. if tx != nil {
  2149. tx.Rollback()
  2150. }
  2151. if tx != nil {
  2152. tx.Close()
  2153. }
  2154. msg := geterrmsg(err.Error())
  2155. outentry["error_msg"] = msg
  2156. error++
  2157. queryData = append(queryData, outentry)
  2158. isdone = true
  2159. break
  2160. } else {
  2161. if len(returnmsgmap1) > 0 {
  2162. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  2163. if tx != nil {
  2164. tx.Rollback()
  2165. }
  2166. if tx != nil {
  2167. tx.Close()
  2168. }
  2169. msg := geterrmsg(va.(string))
  2170. outentry["error_msg"] = msg
  2171. error++
  2172. queryData = append(queryData, outentry)
  2173. isdone = true
  2174. break
  2175. }
  2176. }
  2177. isdone = false
  2178. }
  2179. }
  2180. }
  2181. switch {
  2182. case err != nil:
  2183. if tx != nil {
  2184. tx.Rollback()
  2185. }
  2186. default:
  2187. if tx != nil {
  2188. err = tx.Commit()
  2189. }
  2190. }
  2191. if tx != nil {
  2192. tx.Close()
  2193. }
  2194. }
  2195. if !isdone {
  2196. ok++
  2197. isdone = true
  2198. }
  2199. }
  2200. data := make(map[string]interface{})
  2201. data["result"] = queryData
  2202. data["success"] = ok
  2203. data["err_count"] = error
  2204. appG.Response(http.StatusOK, e.SUCCESS, data)
  2205. }
  2206. func TransfTime(timestr string) (string, error) {
  2207. if timestr == "" {
  2208. return time.Now().Format("2006-01-02"), nil
  2209. }
  2210. days, err := strconv.Atoi(timestr)
  2211. if err != nil {
  2212. if len(timestr) == 8 && strings.Count(timestr, "-") == 2 {
  2213. return "20" + timestr[6:] + "-" + timestr[:5], nil
  2214. }
  2215. _, err := time.Parse("2006-01-02", timestr)
  2216. if err != nil {
  2217. t, err := time.Parse("2006/01/02", timestr)
  2218. if err != nil {
  2219. t, err := time.Parse("2006.01.02", timestr)
  2220. if err != nil {
  2221. return "", err
  2222. } else {
  2223. return t.Format("2006-01-02"), nil
  2224. }
  2225. } else {
  2226. return t.Format("2006-01-02"), nil
  2227. }
  2228. } else {
  2229. return timestr, nil
  2230. }
  2231. }
  2232. times, _ := time.Parse("2006-01-02", "1899-12-30")
  2233. times = times.AddDate(0, 0, days)
  2234. return times.Format("2006-01-02"), nil
  2235. }
  2236. func Createchart(c *gin.Context) {
  2237. appG := app.Gin{C: c}
  2238. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2239. fsion := gofasion.NewFasion(string(dataByte))
  2240. chart_name := fsion.Get("chart_name").ValueStr()
  2241. desc := fsion.Get("desc").ValueStr()
  2242. pastureid := fsion.Get("pastureid").ValueStr()
  2243. source_id := fsion.Get("source_id").ValueStr()
  2244. emp := fsion.Get("emp").ValueStr()
  2245. content := fsion.Get("content").Json()
  2246. var mapResult map[string]interface{}
  2247. err1 := json.Unmarshal([]byte(content), &mapResult)
  2248. if err1 != nil {
  2249. fmt.Println("JsonToMapDemo err: ", err1)
  2250. }
  2251. tx := restful.Engine.NewSession()
  2252. err := tx.Begin()
  2253. defer func() {
  2254. switch {
  2255. case err != nil:
  2256. logging.Error("tx.Begin 事务启动失败__error:", err)
  2257. if tx != nil {
  2258. tx.Rollback()
  2259. }
  2260. default:
  2261. if tx != nil {
  2262. err = tx.Commit()
  2263. }
  2264. }
  2265. if tx != nil {
  2266. tx.Close()
  2267. }
  2268. }()
  2269. ids, err := setting.SnowIds.NextId()
  2270. if err != nil {
  2271. ids = time.Now().UnixNano()
  2272. logging.Info("create SnowIds err", err)
  2273. }
  2274. exec, err := tx.Exec("insert into chart(id,pastureid,cname,statue,emp,opratetime,content,sourceid)VALUEs(?,?,?,?,?,?,?)",
  2275. ids, pastureid, chart_name, 0, emp, desc, source_id)
  2276. if err != nil {
  2277. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2278. } else {
  2279. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2280. }
  2281. }
  2282. func Updatedashboard(c *gin.Context) {
  2283. appG := app.Gin{C: c}
  2284. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2285. fsion := gofasion.NewFasion(string(dataByte))
  2286. dashboard_id := fsion.Get("dashboard_id").ValueStr()
  2287. pastureid := fsion.Get("pastureid").ValueStr()
  2288. content := fsion.Get("content").Json()
  2289. var mapResult map[string]interface{}
  2290. err1 := json.Unmarshal([]byte(content), &mapResult)
  2291. if err1 != nil {
  2292. fmt.Println("JsonToMapDemo err: ", err1)
  2293. }
  2294. layout := mapResult["layout"]
  2295. tx := restful.Engine.NewSession()
  2296. err := tx.Begin()
  2297. defer func() {
  2298. switch {
  2299. case err != nil:
  2300. logging.Error("tx.Begin 事务启动失败__error:", err)
  2301. if tx != nil {
  2302. tx.Rollback()
  2303. }
  2304. default:
  2305. if tx != nil {
  2306. err = tx.Commit()
  2307. }
  2308. }
  2309. if tx != nil {
  2310. tx.Close()
  2311. }
  2312. }()
  2313. exec, err := tx.SQL("select content from dashboard where pastureid=? and id=?", pastureid, dashboard_id).Query().List()
  2314. if err != nil {
  2315. println("2", err.Error())
  2316. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2317. } else {
  2318. if exec != nil {
  2319. if exec[0]["content"] == nil {
  2320. mapR := make(map[string]interface{})
  2321. mapR["layout"] = layout
  2322. mjson, _ := json.Marshal(mapR)
  2323. mString := string(mjson)
  2324. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2325. if err3 != nil {
  2326. println("3", err3.Error())
  2327. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2328. } else {
  2329. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2330. }
  2331. } else {
  2332. var mapR map[string]interface{}
  2333. err2 := json.Unmarshal([]byte(exec[0]["content"].(string)), &mapR)
  2334. if err1 != nil {
  2335. fmt.Println("JsonToMapDemo err: ", err2)
  2336. }
  2337. mapR["layout"] = layout
  2338. mjson, _ := json.Marshal(mapR)
  2339. mString := string(mjson)
  2340. exec1, err3 := tx.Exec("update dashboard set content=? where pastureid=? and id=?", mString, pastureid, dashboard_id)
  2341. if err3 != nil {
  2342. println("3", err3.Error())
  2343. appG.Response(http.StatusOK, e.ERROR, err3.Error())
  2344. } else {
  2345. appG.Response(http.StatusOK, e.SUCCESS, exec1)
  2346. }
  2347. }
  2348. } else {
  2349. appG.Response(http.StatusOK, e.ERROR, "未找到对应的仪表盘")
  2350. }
  2351. }
  2352. }
  2353. func ExecSQL(c *gin.Context) {
  2354. appG := app.Gin{C: c}
  2355. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2356. fsion := gofasion.NewFasion(string(dataByte))
  2357. content := fsion.Get("content").Json()
  2358. pastureid := fsion.Get("pastureid").ValueStr()
  2359. var mapResult map[string]interface{}
  2360. err1 := json.Unmarshal([]byte(content), &mapResult)
  2361. if err1 != nil {
  2362. fmt.Println("JsonToMapDemo err: ", err1)
  2363. }
  2364. sqlstr := "select "
  2365. groupstr := " GROUP BY "
  2366. for _, value := range mapResult["selectedDimension"].([]interface{}) {
  2367. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2368. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2369. }
  2370. for _, value := range mapResult["selectedCalcul"].([]interface{}) {
  2371. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2372. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2373. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2374. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2375. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2376. sqlstr = sqlstr + tem + ","
  2377. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2378. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2379. sqlstr = sqlstr + tem + ","
  2380. } else {
  2381. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2382. sqlstr = sqlstr + tem + ","
  2383. }
  2384. }
  2385. if _, ok := mapResult["selectedCalcul2"]; ok {
  2386. for _, value := range mapResult["selectedCalcul2"].([]interface{}) {
  2387. if value.(map[string]interface{})["calculFunc"].(string) == "none" {
  2388. sqlstr = sqlstr + value.(map[string]interface{})["Column"].(string) + ","
  2389. groupstr = groupstr + value.(map[string]interface{})["Column"].(string) + ","
  2390. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbiaozhun" {
  2391. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2392. sqlstr = sqlstr + tem + ","
  2393. } else if value.(map[string]interface{})["calculFunc"].(string) == "custbianyi" {
  2394. tem := "STDDEV" + "(" + value.(map[string]interface{})["Column"].(string) + ")/ AVG(" + value.(map[string]interface{})["Column"].(string) + ")as " + value.(map[string]interface{})["Column"].(string)
  2395. sqlstr = sqlstr + tem + ","
  2396. } else {
  2397. tem := value.(map[string]interface{})["calculFunc"].(string) + "(" + value.(map[string]interface{})["Column"].(string) + ") as " + value.(map[string]interface{})["Column"].(string)
  2398. sqlstr = sqlstr + tem + ","
  2399. }
  2400. }
  2401. }
  2402. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2403. sqlstr = sqlstr + " from " + mapResult["dataSrc"].(string)
  2404. sqlstr = sqlstr + " where pastureid=" + pastureid
  2405. if len(mapResult["filters"].([]interface{})) > 0 {
  2406. sqlstr = sqlstr + " and "
  2407. }
  2408. println(len(mapResult["filters"].([]interface{})), sqlstr)
  2409. for _, value := range mapResult["filters"].([]interface{}) {
  2410. switch value.(map[string]interface{})["filterOperator"].(string) {
  2411. case ">", "=", "<", ">=", "<=", "!=", "like":
  2412. 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 "
  2413. case "IN":
  2414. sqlstr = sqlstr + value.(map[string]interface{})["filteCol"].(string) + " " + value.(map[string]interface{})["filterOperator"].(string) + "("
  2415. for _, value1 := range value.(map[string]interface{})["value"].(map[string]interface{})["arrValue"].([]interface{}) {
  2416. sqlstr = sqlstr + value1.(string) + ","
  2417. }
  2418. sqlstr = sqlstr[0 : len(sqlstr)-1]
  2419. sqlstr = sqlstr + ")" + " AND "
  2420. case "BETWEEN":
  2421. 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 "
  2422. }
  2423. }
  2424. if len(mapResult["filters"].([]interface{})) > 0 {
  2425. sqlstr = sqlstr[0 : len(sqlstr)-4]
  2426. }
  2427. //
  2428. groupstr = groupstr[0 : len(groupstr)-1]
  2429. sqlstr = sqlstr + groupstr + " "
  2430. if len(mapResult["orderByStrs"].([]interface{})) > 0 {
  2431. sqlstr = sqlstr + " order by "
  2432. }
  2433. //
  2434. for key, value := range mapResult["orderByStrs"].([]interface{}) {
  2435. if key == len(mapResult["orderByStrs"].([]interface{}))-1 {
  2436. sqlstr = sqlstr + value.(string) + " "
  2437. } else {
  2438. sqlstr = sqlstr + value.(string) + ","
  2439. }
  2440. }
  2441. //
  2442. sqlstr = sqlstr + " limit " + strconv.Itoa(int(mapResult["limit"].(float64)))
  2443. tx := restful.Engine.NewSession()
  2444. err := tx.Begin()
  2445. defer func() {
  2446. switch {
  2447. case err != nil:
  2448. logging.Error("tx.Begin 事务启动失败__error:", err)
  2449. if tx != nil {
  2450. tx.Rollback()
  2451. }
  2452. default:
  2453. if tx != nil {
  2454. err = tx.Commit()
  2455. }
  2456. }
  2457. if tx != nil {
  2458. tx.Close()
  2459. }
  2460. }()
  2461. exec, err := tx.SQL(sqlstr).Query().List()
  2462. if err != nil {
  2463. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2464. } else {
  2465. appG.Response(http.StatusOK, e.SUCCESS, exec)
  2466. }
  2467. }
  2468. func Dashboards(c *gin.Context) {
  2469. appG := app.Gin{C: c}
  2470. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2471. fsion := gofasion.NewFasion(string(dataByte))
  2472. sqlnamestr := fsion.Get("name").ValueStr()
  2473. //sqlnamestr1 := fsion.Get("name1").ValueStr()
  2474. offset := fsion.Get("offset").ValueDefaultInt(0)
  2475. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2476. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2477. month := fsion.Get("month").ValueDefaultStr("map")
  2478. logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
  2479. tx := restful.Engine.NewSession()
  2480. err := tx.Begin()
  2481. defer func() {
  2482. switch {
  2483. case err != nil:
  2484. if tx != nil {
  2485. tx.Rollback()
  2486. }
  2487. default:
  2488. if tx != nil {
  2489. err = tx.Commit()
  2490. }
  2491. }
  2492. if tx != nil {
  2493. tx.Close()
  2494. }
  2495. }()
  2496. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2497. //sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2498. if sql != "" {
  2499. s_params := make([]interface{}, 0)
  2500. if fsion.HasKey("parammaps") {
  2501. parammaps := fsion.Get("parammaps")
  2502. paramslist := strings.Split(p, ",")
  2503. if len(paramslist) > 0 && p != "" {
  2504. for _, value := range paramslist {
  2505. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2506. if tempv, exists := c.Get("jwt_username"); exists {
  2507. s_params = append(s_params, tempv.(string))
  2508. } else {
  2509. s_params = append(s_params, "")
  2510. }
  2511. } else {
  2512. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2513. }
  2514. }
  2515. }
  2516. }
  2517. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2518. if err != nil {
  2519. appG.Response(http.StatusOK, e.ERROR, err.Error())
  2520. } else {
  2521. //paramslist1 := strings.Split(p1, ",")
  2522. dids := make([]interface{}, 0)
  2523. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2524. var mapResult map[string]interface{}
  2525. dids = append(dids, value["dashboard_id"])
  2526. if value["content"] != nil {
  2527. err1 := json.Unmarshal([]byte(value["content"].(string)), &mapResult)
  2528. if err1 != nil {
  2529. println("JsonToMapDemo1 err: ", err1)
  2530. }
  2531. temap := make(map[string]interface{})
  2532. tem := mapResult["layout"].([]interface{})
  2533. if v, ok := value["chartids"]; ok {
  2534. chartids := strings.Split(v.(string), ",")
  2535. for _, va := range chartids {
  2536. a := false
  2537. for _, v2 := range tem {
  2538. if v2.(map[string]interface{})["id"].(string) == va {
  2539. a = true
  2540. //println("va1======",va)
  2541. }
  2542. }
  2543. if !a {
  2544. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2545. va + "\",\"id\":\"" + va +
  2546. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":100,\"yOffSet\":18}"
  2547. var mapTem map[string]interface{}
  2548. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2549. if err1 != nil {
  2550. println("JsonToMapDemo err: ", err1)
  2551. }
  2552. tem = append(tem, mapTem)
  2553. }
  2554. }
  2555. temap["layout"] = tem
  2556. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2557. }
  2558. } else {
  2559. temap := make(map[string]interface{})
  2560. tem := make([]interface{}, 0)
  2561. if v, ok := value["chartids"]; ok {
  2562. chartids := strings.Split(v.(string), ",")
  2563. for _, va := range chartids {
  2564. laytem := "{\"bottomLine\":[[3,18],[15,18]],\"h\":9,\"i\":\"" +
  2565. va + "\",\"id\":\"" + va +
  2566. "\",\"moved\":false,\"topLine\":[[3,9],[15,9]],\"w\":12,\"x\":0,\"xOffSet\":15,\"y\":0,\"yOffSet\":18}"
  2567. var mapTem map[string]interface{}
  2568. err1 := json.Unmarshal([]byte(laytem), &mapTem)
  2569. if err1 != nil {
  2570. println("JsonToMapDemo err: ", err1)
  2571. }
  2572. tem = append(tem, mapTem)
  2573. }
  2574. temap["layout"] = tem
  2575. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["content"] = temap
  2576. }
  2577. }
  2578. }
  2579. queryData.(map[string]interface{})["order"] = dids
  2580. queryData.(map[string]interface{})["dashboards"] = queryData.(map[string]interface{})["list"]
  2581. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2582. }
  2583. } else {
  2584. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2585. }
  2586. }
  2587. func HttpPostData(url, RequestMethod, parammaps string, tx *xorm.Session) string {
  2588. fsion := gofasion.NewFasion(parammaps)
  2589. sqlnamestr := fsion.Get("name").ValueStr()
  2590. sqlnamestr1 := fsion.Get("name1").ValueStr()
  2591. offset := fsion.Get("offset").ValueDefaultInt(0)
  2592. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2593. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2594. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2595. sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
  2596. body := []byte("")
  2597. if sql != "" {
  2598. s_params := make([]interface{}, 0)
  2599. if fsion.HasKey("parammaps") {
  2600. parammaps := fsion.Get("parammaps")
  2601. paramslist := strings.Split(p, ",")
  2602. if len(paramslist) > 0 && p != "" {
  2603. for _, value := range paramslist {
  2604. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2605. }
  2606. }
  2607. }
  2608. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2609. if err != nil {
  2610. } else {
  2611. paramslist1 := strings.Split(p1, ",")
  2612. for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
  2613. s_params1 := make([]interface{}, 0)
  2614. if len(paramslist1) > 0 && p1 != "" {
  2615. for _, v := range paramslist1 {
  2616. s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
  2617. }
  2618. }
  2619. arr, _ := tx.SQL(sql1, s_params1...).QueryString() //获取
  2620. queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
  2621. body, _ = json.Marshal(queryData)
  2622. }
  2623. }
  2624. }
  2625. bs := bytes.NewBuffer(body)
  2626. client := &http.Client{}
  2627. //body1 := bytes.NewBuffer([]byte("{\"username\":\"00028\",\"password\":\"123456\"}"))
  2628. req, err := http.NewRequest(RequestMethod,
  2629. url,
  2630. bs,
  2631. )
  2632. if err != nil {
  2633. }
  2634. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  2635. req.Header.Set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjAwMDI4IiwicGFzc3dvcmQiOiJlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZSIsImV4cCI6MTYxOTM4NjU0MiwiaXNzIjoiaHR0cHM6Ly9naXRodWIuY29tL2twdHl1bi9nby1hZG1pbi8ifQ.sJwnE9HTOVnDNOaeHqOQzi7cSydYkWS4uQHxtjY7UMY")
  2636. if err != nil {
  2637. // handle error
  2638. }
  2639. resp, err := client.Do(req)
  2640. if err != nil {
  2641. return ""
  2642. }
  2643. defer resp.Body.Close()
  2644. result_body, err := ioutil.ReadAll(resp.Body)
  2645. if err != nil {
  2646. return ""
  2647. }
  2648. fmt.Println(string(result_body))
  2649. return ""
  2650. }
  2651. func GetSummary(c *gin.Context) {
  2652. appG := app.Gin{C: c}
  2653. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2654. fsion := gofasion.NewFasion(string(dataByte))
  2655. offset := fsion.Get("offset").ValueDefaultInt(0)
  2656. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  2657. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  2658. parammaps := fsion.Get("parammaps")
  2659. status := parammaps.Get("status").ValueStr() //0 按驾驶员 1 配方名称 2 栏舍名称 3 牲畜名称 4 车次 5 tmr名称
  2660. genre := parammaps.Get("genre").ValueStr() //0 混料 1 撒料
  2661. isDate := parammaps.Get("isdate").ValueStr() //0 不按时间 1 按时间
  2662. tx := restful.Engine.NewSession()
  2663. defer tx.Close()
  2664. sqlnamestr := ""
  2665. if genre == "0" {
  2666. if status == "0" {
  2667. sqlnamestr = "getAccuracyJSY"
  2668. } else if status == "1" {
  2669. sqlnamestr = "getAccuracyHFT"
  2670. } else if status == "2" {
  2671. sqlnamestr = "getAccuracyHNS"
  2672. } else if status == "3" {
  2673. sqlnamestr = "getAccuracyHSC"
  2674. } else if status == "4" {
  2675. sqlnamestr = "getAccuracyHCC"
  2676. } else if status == "5" {
  2677. sqlnamestr = "getAccuracyMC"
  2678. }
  2679. } else {
  2680. if status == "0" {
  2681. sqlnamestr = "getAccuracySCCJSY"
  2682. } else if status == "1" {
  2683. sqlnamestr = "getAccuracySFT"
  2684. } else if status == "2" {
  2685. sqlnamestr = "getAccuracySNS"
  2686. } else if status == "3" {
  2687. sqlnamestr = "getAccuracySSC"
  2688. } else if status == "4" {
  2689. sqlnamestr = "getAccuracySCC"
  2690. } else if status == "5" {
  2691. sqlnamestr = "getAccuracySLCL"
  2692. }
  2693. }
  2694. if isDate == "1" {
  2695. sqlnamestr += "Date"
  2696. }
  2697. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  2698. // fmt.Println(sqlnamestr, sql)
  2699. if sql != "" {
  2700. s_params := make([]interface{}, 0)
  2701. // if fsion.HasKey("parammaps") {
  2702. fmt.Println(s_params, "222", p)
  2703. paramslist := strings.Split(p, ",")
  2704. if len(paramslist) > 0 && p != "" {
  2705. for _, value := range paramslist {
  2706. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  2707. if tempv, exists := c.Get("jwt_username"); exists {
  2708. s_params = append(s_params, tempv.(string))
  2709. } else {
  2710. s_params = append(s_params, "")
  2711. }
  2712. } else {
  2713. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  2714. }
  2715. }
  2716. }
  2717. if returntype == "xlsx" {
  2718. var xlsxfile *xlsx.File
  2719. xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
  2720. //c.File("c:/dd.xlsx")
  2721. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2722. c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
  2723. c.Header("Content-Transfer-Encoding", "binary")
  2724. _ = xlsxfile.Write(c.Writer)
  2725. } else {
  2726. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  2727. if err != nil {
  2728. logging.Error("GetDataByName err: ", err)
  2729. msg := geterrmsg(err.Error())
  2730. appG.Response(http.StatusOK, e.ERROR, msg)
  2731. } else {
  2732. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  2733. }
  2734. }
  2735. } else {
  2736. appG.Response(http.StatusOK, e.SUCCESS, nil)
  2737. }
  2738. }
  2739. // type lpplanStruct struct {
  2740. // Id int64 `xorm:"id"`
  2741. // Tmrname string `xorm:"tmrname"`
  2742. // Tmrid int64 `xorm:"tmrid"`
  2743. // Sort int64 `xorm:"sort"`
  2744. // Sel int64 `xorm:"sel"`
  2745. // Times int64 `xorm:"times"`
  2746. // Ftname string `xorm:"ftname"`
  2747. // Ftid int64 `xorm:"ftid"`
  2748. // Maxweight float64 `xorm:"maxweight"`
  2749. // Sumweight float64 `xorm:"sumweight"`
  2750. // Sumcowcount int64 `xorm:"sumcowcount"`
  2751. // Pastureid string `xorm:"pastureid"`
  2752. // Display string `xorm:"display"`
  2753. // Issplit int64 `xorm:"issplit"`
  2754. // BeginTime string `xorm:"begintime"`
  2755. // }
  2756. func UpdateFTdetail(c *gin.Context) {
  2757. fmt.Println(time.Now())
  2758. appG := app.Gin{C: c}
  2759. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  2760. tempval_ := make(map[string]interface{})
  2761. tempCommon := make(map[string]interface{})
  2762. tempval := make([]map[string]interface{}, 0)
  2763. fTChange := make(map[string]interface{}, 0)
  2764. fpdOldDataList := make([]map[string]interface{}, 0)
  2765. fpdDataList := make([]map[string]interface{}, 0)
  2766. err := json.Unmarshal(dataByte, &tempval_)
  2767. if err != nil {
  2768. appG.Response(http.StatusOK, e.ERROR, false)
  2769. return
  2770. }
  2771. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  2772. tx := restful.Engine.NewSession()
  2773. if v, ok := tempval_["data"].([]interface{}); ok {
  2774. for _, Tvalue := range v {
  2775. if v1, ok := Tvalue.(map[string]interface{}); ok {
  2776. if v1["name"] == "updateFPbyFTChange" {
  2777. fTChange = v1
  2778. continue
  2779. }
  2780. tempval = append(tempval, v1)
  2781. }
  2782. }
  2783. }
  2784. parammaps := fTChange["parammaps"].(map[string]interface{})
  2785. // oldFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2786. // if err != nil {
  2787. // logs.Error(err)
  2788. // appG.Response(http.StatusOK, e.ERROR, false)
  2789. // return
  2790. // }
  2791. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  2792. // if err != nil {
  2793. // logs.Error(err)
  2794. // appG.Response(http.StatusOK, e.ERROR, false)
  2795. // return
  2796. // }
  2797. // oldFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  2798. // if err != nil {
  2799. // logs.Error(err)
  2800. // appG.Response(http.StatusOK, e.ERROR, false)
  2801. // return
  2802. // }
  2803. err = tx.Begin()
  2804. if err != nil {
  2805. logging.Error("tx.Begin 事务启动失败__error:", err)
  2806. }
  2807. defer func() {
  2808. if err != nil {
  2809. if tx != nil {
  2810. tx.Rollback()
  2811. }
  2812. }
  2813. if tx != nil {
  2814. tx.Close()
  2815. }
  2816. }()
  2817. if err != nil {
  2818. } else {
  2819. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  2820. tempCommon = v
  2821. }
  2822. fpdOldDataList, err = tx.SQL(`select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  2823. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2824. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2825. UNION
  2826. SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  2827. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2828. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2829. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2830. if err == nil {
  2831. if tempv, exists := c.Get("jwt_username"); exists {
  2832. tempCommon["jwt_username"] = tempv.(string)
  2833. }
  2834. for _, paramvalue := range tempval {
  2835. if _, ok := paramvalue["resultname"]; !ok {
  2836. paramvalue["resultname"] = paramvalue["name"]
  2837. }
  2838. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  2839. if err != nil {
  2840. logging.Error("ExecDataParam error:", err)
  2841. break
  2842. }
  2843. }
  2844. if err != nil {
  2845. msg := geterrmsg(err.Error())
  2846. appG.Response(http.StatusOK, e.ERROR, msg)
  2847. //appG.Response(http.StatusOK, e.ERROR, err.Error())
  2848. }
  2849. }
  2850. }
  2851. tx.Commit()
  2852. // go func() {
  2853. if fTChange != nil {
  2854. parammaps := fTChange["parammaps"].(map[string]interface{})
  2855. if parammaps["type"].(float64) == 1 {
  2856. _, err = tx.SQL(`UPDATE feedp fp
  2857. set
  2858. fp.ftweight= IFNULL(IF(
  2859. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2860. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2861. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2862. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2863. ),0),fp.feedweight = IFNULL(IF(
  2864. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2865. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2866. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2867. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2868. ),0) +ifnull(fp.supplyweight,0)
  2869. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2870. _, err = tx.SQL(`UPDATE fpdetail fpd
  2871. INNER JOIN feedp fp
  2872. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2873. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2874. WHERE fp.pastureid = ? AND fp.ftid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2875. } else {
  2876. _, err = tx.SQL(`UPDATE feedp fp
  2877. SET
  2878. fp.supplyweight= IFNULL(IF(
  2879. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2880. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2881. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2882. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2883. ),0),fp.feedweight = IFNULL(IF(
  2884. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  2885. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  2886. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  2887. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  2888. ),0) +ifnull(fp.supplyweight,0)
  2889. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2890. _, err = tx.SQL(`UPDATE fpdetail fpd
  2891. INNER JOIN feedp fp
  2892. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  2893. SET fpd.weight = fp.feedweight*fpd.tratio/100
  2894. WHERE fp.pastureid = ? AND fp.ptsfid =?`, parammaps["pastureid"], parammaps["ftid"]).Execute()
  2895. }
  2896. fpdDataList, err = tx.SQL(`select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  2897. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  2898. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)
  2899. UNION
  2900. SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,0) weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  2901. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  2902. WHERE fpdetail.pastureid = ? and (ptid = ? or ptsid = ?)) t
  2903. order by t.barname,t.times`, parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"], parammaps["pastureid"], parammaps["ftid"], parammaps["ftid"]).Query().List()
  2904. lpplanList := make([]*lpplanStruct, 0)
  2905. err = tx.SQL(`select id,times,maxweight from lpplan where pastureid = ? and ftid = ? order by sort desc`, parammaps["pastureid"], parammaps["ftid"]).Find(&lpplanList)
  2906. if err != nil {
  2907. logs.Error(err, 1)
  2908. return
  2909. }
  2910. lppidlist := []string{}
  2911. for _, lpp := range lpplanList {
  2912. lppidlist = append(lppidlist, strconv.FormatInt(lpp.Id, 10))
  2913. }
  2914. if len(lppidlist) <= 0 {
  2915. appG.Response(http.StatusOK, e.SUCCESS, true)
  2916. return
  2917. }
  2918. lpplandtl1AllList := make([]*lpplandtl1, 0)
  2919. err = tx.SQL(fmt.Sprintf(`select id,lppid,barid,fpdid,lweight from lpplandtl1 where pastureid = ? and lppid in (%s)
  2920. order by sort desc`, strings.Join(lppidlist, ",")), parammaps["pastureid"]).Find(&lpplandtl1AllList)
  2921. if err != nil {
  2922. // tx.Rollback()
  2923. logs.Error(err, 2, parammaps["pastureid"])
  2924. return
  2925. }
  2926. var wg sync.WaitGroup
  2927. for _, old := range fpdOldDataList {
  2928. for _, fpd := range fpdDataList {
  2929. wg.Add(1)
  2930. go func(old, fpd map[string]interface{}) {
  2931. updateLppandList := make([]*lpplandtl1, 0)
  2932. defer wg.Done()
  2933. if fpd["id"].(string) == old["id"].(string) && fpd["fttype"].(int64) == old["fttype"].(int64) &&
  2934. fpd["weight"].(string) != old["weight"].(string) && fpd["times"].(int64) == old["times"].(int64) {
  2935. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  2936. oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
  2937. var w float64
  2938. var status int
  2939. if fpd["barname"].(string) == "D1" {
  2940. fmt.Println("1")
  2941. }
  2942. if weight < oldweight {
  2943. if weight >= 0 {
  2944. return
  2945. }
  2946. w = weight
  2947. status = 0
  2948. } else {
  2949. if oldweight > 0 {
  2950. return
  2951. }
  2952. w = weight
  2953. status = 1
  2954. }
  2955. // fweight = w
  2956. for _, lpp := range lpplanList {
  2957. var fweight float64
  2958. var lweight float64
  2959. lpplandtl1List := make([]*lpplandtl1, 0)
  2960. fpdid, _ := strconv.ParseInt(fpd["id"].(string), 10, 64)
  2961. for _, lppland := range lpplandtl1AllList {
  2962. if lppland.Lppid == lpp.Id && lppland.Fpdid == fpdid {
  2963. lpplandtl1List = append(lpplandtl1List, lppland)
  2964. }
  2965. }
  2966. if len(lpplandtl1List) == 0 {
  2967. continue
  2968. }
  2969. for _, lppland := range lpplandtl1List {
  2970. lweight += lppland.Lweight
  2971. }
  2972. if status == 0 {
  2973. if lweight <= 0 {
  2974. continue
  2975. }
  2976. } else {
  2977. if lpp.Maxweight <= lweight {
  2978. continue
  2979. }
  2980. }
  2981. for _, lppland := range lpplandtl1List {
  2982. if fpdid == lppland.Fpdid {
  2983. if status == 1 {
  2984. // if w <= lppland.Lweight {
  2985. if lpp.Maxweight <= lweight {
  2986. continue
  2987. }
  2988. if w+lweight <= lpp.Maxweight {
  2989. lppland.Lweight += w
  2990. lweight += w
  2991. fweight += w
  2992. w = 0
  2993. } else {
  2994. w = w - (lpp.Maxweight - lweight)
  2995. n := (lpp.Maxweight - lweight)
  2996. lppland.Lweight = lppland.Lweight + n
  2997. lweight += n
  2998. fweight += n
  2999. }
  3000. } else {
  3001. if lppland.Lweight == 0 {
  3002. continue
  3003. }
  3004. if w+lppland.Lweight >= 0 {
  3005. lppland.Lweight = lppland.Lweight + w
  3006. lweight = lweight + w
  3007. fweight = fweight + w
  3008. w = 0
  3009. } else {
  3010. w = w + lppland.Lweight
  3011. lweight = lweight - lppland.Lweight
  3012. fweight = fweight - lppland.Lweight
  3013. lppland.Lweight = 0
  3014. }
  3015. }
  3016. updateLppandList = append(updateLppandList, lppland)
  3017. break
  3018. }
  3019. }
  3020. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3021. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3022. WHERE pastureid=? AND id=?`, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"]).Execute()
  3023. if err != nil {
  3024. // tx.Rollback()
  3025. logs.Error(err, 4, parammaps["type"], fweight, fweight, parammaps["type"], fweight, fweight, parammaps["pastureid"], fpd["id"])
  3026. return
  3027. }
  3028. for _, lppland := range updateLppandList {
  3029. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3030. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, parammaps["pastureid"]).Execute()
  3031. if err != nil {
  3032. fmt.Println(lppland.Lweight, lppland.Id, parammaps["pastureid"], status)
  3033. // tx.Rollback()
  3034. logs.Error(err, 3)
  3035. return
  3036. }
  3037. // defer wg.Done()
  3038. }
  3039. updateLppandList = []*lpplandtl1{}
  3040. if w == 0 {
  3041. break
  3042. }
  3043. }
  3044. }
  3045. }(old, fpd)
  3046. }
  3047. }
  3048. wg.Wait()
  3049. }
  3050. // newFpdDataList, err := tx.SQL(` select * from fpdetail where ptid = ? or ptsid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3051. // if err != nil {
  3052. // logs.Error(err)
  3053. // appG.Response(http.StatusOK, e.ERROR, false)
  3054. // return
  3055. // }
  3056. // newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.ftid = ? `, parammaps["ftid"]).Query().List()
  3057. // if err != nil {
  3058. // logs.Error(err)
  3059. // appG.Response(http.StatusOK, e.ERROR, false)
  3060. // return
  3061. // }
  3062. // newFeedpList, err := tx.SQL(` select * from feedp where ftid = ? or ptsfid = ? `, parammaps["ftid"], parammaps["ftid"]).Query().List()
  3063. // if err != nil {
  3064. // logs.Error(err)
  3065. // appG.Response(http.StatusOK, e.ERROR, false)
  3066. // return
  3067. // }
  3068. // now := time.Now()
  3069. // for _, oldFpd := range oldFpdDataList {
  3070. // for _, newFpd := range newFpdDataList {
  3071. // if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
  3072. // if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
  3073. // // go func() {
  3074. // _, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
  3075. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
  3076. // newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
  3077. // newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
  3078. // if err != nil {
  3079. // logs.Error(err)
  3080. // appG.Response(http.StatusOK, e.ERROR, false)
  3081. // return
  3082. // }
  3083. // // }()
  3084. // }
  3085. // break
  3086. // }
  3087. // }
  3088. // }
  3089. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3090. // for _, newLpplandtl1 := range newLpplandtl1List {
  3091. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3092. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3093. // // go func() {
  3094. // _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3095. // background,cowcount,ccountradio,lweighthis,createdate)
  3096. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3097. // newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3098. // newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3099. // newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3100. // newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3101. // newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  3102. // if err != nil {
  3103. // logs.Error(err)
  3104. // appG.Response(http.StatusOK, e.ERROR, false)
  3105. // return
  3106. // }
  3107. // // }()
  3108. // }
  3109. // break
  3110. // }
  3111. // }
  3112. // }
  3113. // for _, oldFeedp := range oldFeedpList {
  3114. // for _, newFeedp := range newFeedpList {
  3115. // if oldFeedp["id"].(int64) == newFeedp["id"].(int64) && oldFeedp["feedweight"].(string) != newFeedp["feedweight"].(string) &&
  3116. // oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
  3117. // // go func() {
  3118. // _, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
  3119. // ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
  3120. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3121. // newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
  3122. // newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
  3123. // newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
  3124. // newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
  3125. // newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
  3126. // if err != nil {
  3127. // logs.Error(err)
  3128. // appG.Response(http.StatusOK, e.ERROR, false)
  3129. // return
  3130. // }
  3131. // // }()
  3132. // }
  3133. // }
  3134. // }
  3135. appG.Response(http.StatusOK, e.SUCCESS, true)
  3136. }
  3137. type lpplandtlInfo struct {
  3138. Id int64 `xorm:"id"`
  3139. Pastureid int64 `xorm:"pastureid"`
  3140. Lppid int64 `xorm:"lppid"`
  3141. Barid int64 `xorm:"barid"`
  3142. Barname string `xorm:"barname"`
  3143. Fpdid int64 `xorm:"fpdid"`
  3144. Fttype int64 `xorm:"fttype"`
  3145. Lweight float64 `xorm:"lweight"`
  3146. Sort int64 `xorm:"sort"`
  3147. Tmrid int64 `xorm:"tmrid"`
  3148. Tmrname string `xorm:"tmrname"`
  3149. Cowcount int64 `xorm:"cowcount"`
  3150. Ccountradio float64 `xorm:"ccountradio"`
  3151. Background string `xorm:"background"`
  3152. Lweighthis float64 `xorm:"lweighthis"`
  3153. Maxweight float64 `xorm:"maxweight"`
  3154. }
  3155. func UpdateFpdetailBar(c *gin.Context) {
  3156. appG := app.Gin{C: c}
  3157. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3158. fsion := gofasion.NewFasion(string(dataByte))
  3159. pastureid := fsion.Get("pastureid").ValueStr()
  3160. id := fsion.Get("id").ValueStr()
  3161. tx := restful.Engine.NewSession()
  3162. // oldLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? `, id).Query().List()
  3163. // if err != nil {
  3164. // logs.Error(err)
  3165. // appG.Response(http.StatusOK, e.ERROR, false)
  3166. // return
  3167. // }
  3168. tx.Begin()
  3169. for _, list := range fsion.Get("data").Array() {
  3170. ftmap := make(map[string]interface{})
  3171. ftmap["old"] = list.Get("old").ValueFloat64()
  3172. ftmap["new"] = list.Get("new").ValueFloat64()
  3173. ftmap["times"] = list.Get("times").ValueInt64()
  3174. ftmap["ptid"] = list.Get("ptid").ValueStr()
  3175. ftmap["ptsid"] = list.Get("ptsid").ValueStr()
  3176. // fmt.Println(ftmap)
  3177. fpdDataList, err := tx.SQL(`select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  3178. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  3179. WHERE fpdetail.pastureid = ? and barid = ? and times = ?
  3180. UNION
  3181. SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  3182. (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  3183. WHERE fpdetail.pastureid = ? and barid = ? and times = ? ) t
  3184. order by t.barname,t.times`, pastureid, id, ftmap["times"], pastureid, id, ftmap["times"]).Query().List()
  3185. // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
  3186. if err != nil {
  3187. tx.Rollback()
  3188. logs.Error(err)
  3189. }
  3190. for _, fpd := range fpdDataList {
  3191. if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
  3192. fttype := -1
  3193. if ftmap["ptid"].(string) != "-1" {
  3194. fttype = 1
  3195. }
  3196. var fweight float64
  3197. var lweight float64
  3198. lpplandtl1List := make([]*lpplandtlInfo, 0)
  3199. err = tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  3200. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  3201. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  3202. fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
  3203. if err != nil {
  3204. tx.Rollback()
  3205. logs.Error(err)
  3206. }
  3207. weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  3208. var w float64
  3209. var status int
  3210. if ftmap["new"].(float64) < ftmap["old"].(float64) {
  3211. if weight >= 0 {
  3212. continue
  3213. }
  3214. w = weight
  3215. status = 0
  3216. } else {
  3217. if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
  3218. continue
  3219. }
  3220. w = weight
  3221. status = 1
  3222. }
  3223. for _, lppland := range lpplandtl1List {
  3224. lweight += lppland.Lweight
  3225. }
  3226. for _, lppland := range lpplandtl1List {
  3227. if status == 1 {
  3228. // if w <= lppland.Lweight {
  3229. if lppland.Maxweight <= lweight {
  3230. continue
  3231. }
  3232. if w+lweight <= lppland.Maxweight {
  3233. lppland.Lweight += w
  3234. lweight += w
  3235. fweight += w
  3236. w = 0
  3237. } else {
  3238. w = w - (lppland.Maxweight - lweight)
  3239. n := (lppland.Maxweight - lweight)
  3240. lppland.Lweight = lppland.Lweight + n
  3241. lweight += n
  3242. fweight += n
  3243. }
  3244. } else {
  3245. if lppland.Lweight == 0 {
  3246. continue
  3247. }
  3248. if w+lppland.Lweight >= 0 {
  3249. lppland.Lweight = lppland.Lweight + w
  3250. lweight = lweight + w
  3251. fweight = fweight + w
  3252. w = 0
  3253. } else {
  3254. w = w + lppland.Lweight
  3255. lweight = lweight - lppland.Lweight
  3256. fweight = fweight - lppland.Lweight
  3257. lppland.Lweight = 0
  3258. }
  3259. }
  3260. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  3261. if err != nil {
  3262. tx.Rollback()
  3263. logs.Error(err)
  3264. return
  3265. }
  3266. break
  3267. }
  3268. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  3269. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  3270. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
  3271. if err != nil {
  3272. tx.Rollback()
  3273. logs.Error(err)
  3274. }
  3275. if w == 0 {
  3276. break
  3277. }
  3278. }
  3279. }
  3280. }
  3281. tx.Commit()
  3282. // now := time.Now()
  3283. // newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barid = ? `, id).Query().List()
  3284. // if err != nil {
  3285. // logs.Error(err)
  3286. // appG.Response(http.StatusOK, e.ERROR, false)
  3287. // return
  3288. // }
  3289. // for _, oldLpplandtl1 := range oldLpplandtl1List {
  3290. // for _, newLpplandtl1 := range newLpplandtl1List {
  3291. // if oldLpplandtl1["id"].(int64) == newLpplandtl1["id"].(int64) {
  3292. // if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
  3293. // go func() {
  3294. // _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  3295. // background,cowcount,ccountradio,lweighthis,createdate)
  3296. // values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  3297. // newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
  3298. // newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
  3299. // newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
  3300. // newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
  3301. // newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
  3302. // if err != nil {
  3303. // logs.Error(err)
  3304. // appG.Response(http.StatusOK, e.ERROR, false)
  3305. // return
  3306. // }
  3307. // }()
  3308. // }
  3309. // break
  3310. // }
  3311. // }
  3312. // }
  3313. appG.Response(http.StatusOK, e.SUCCESS, true)
  3314. }
  3315. func GetProcessAnalysis(c *gin.Context) {
  3316. appG := app.Gin{C: c}
  3317. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3318. fsion := gofasion.NewFasion(string(dataByte))
  3319. sqlnamestr := fsion.Get("name").ValueStr()
  3320. offset := fsion.Get("offset").ValueDefaultInt(0)
  3321. pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
  3322. returntype := fsion.Get("returntype").ValueDefaultStr("map")
  3323. parammaps := fsion.Get("parammaps")
  3324. tx := restful.Engine.NewSession()
  3325. err := tx.Begin()
  3326. defer func() {
  3327. switch {
  3328. case err != nil:
  3329. logging.Error("tx.Begin 事务启动失败__error:", err)
  3330. if tx != nil {
  3331. tx.Rollback()
  3332. }
  3333. default:
  3334. if tx != nil {
  3335. err = tx.Commit()
  3336. }
  3337. }
  3338. if tx != nil {
  3339. tx.Close()
  3340. }
  3341. }()
  3342. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3343. s_params := make([]interface{}, 0)
  3344. paramslist := strings.Split(p, ",")
  3345. if len(paramslist) > 0 && p != "" {
  3346. for _, value := range paramslist {
  3347. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3348. if tempv, exists := c.Get("jwt_username"); exists {
  3349. s_params = append(s_params, tempv.(string))
  3350. } else {
  3351. s_params = append(s_params, "")
  3352. }
  3353. } else {
  3354. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3355. }
  3356. }
  3357. }
  3358. tmrtnameStr := ""
  3359. for _, tmr := range parammaps.Get("tmrtname").Array() {
  3360. if len(tmrtnameStr) == 0 {
  3361. tmrtnameStr = fmt.Sprintf("'%s'", tmr.ValueStr())
  3362. } else {
  3363. tmrtnameStr += fmt.Sprintf(",'%s'", tmr.ValueStr())
  3364. }
  3365. }
  3366. if len(tmrtnameStr) > 0 {
  3367. sql += fmt.Sprintf(" AND (d.`tmrtname` in (%s) ) ", tmrtnameStr)
  3368. }
  3369. sql += " ORDER BY d.intime"
  3370. queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
  3371. if err != nil {
  3372. logging.Error("GetDataByName err: ", err)
  3373. msg := geterrmsg(err.Error())
  3374. appG.Response(http.StatusOK, e.ERROR, msg)
  3375. } else {
  3376. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3377. }
  3378. }
  3379. func UpdateFeedtempletStatus(c *gin.Context) {
  3380. appG := app.Gin{C: c}
  3381. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3382. fsion := gofasion.NewFasion(string(dataByte))
  3383. parammaps := fsion.Get("parammaps")
  3384. tx := restful.Engine.NewSession()
  3385. tx.Begin()
  3386. _, err := tx.SQL(fmt.Sprintf(" update feedtemplet set enable = ? where id in (%s) ", parammaps.Get("id").ValueStr()), parammaps.Get("enable").ValueInt64()).Execute()
  3387. if err != nil {
  3388. tx.Rollback()
  3389. logs.Error(err)
  3390. appG.Response(http.StatusOK, e.ERROR, err)
  3391. return
  3392. }
  3393. tx.Commit()
  3394. appG.Response(http.StatusOK, e.SUCCESS, true)
  3395. }
  3396. func AddFtdry(c *gin.Context) {
  3397. appG := app.Gin{C: c}
  3398. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3399. fsion := gofasion.NewFasion(string(dataByte))
  3400. sqlnamestr := fsion.Get("name").ValueStr()
  3401. s_params := make([]interface{}, 0)
  3402. tx := restful.Engine.NewSession()
  3403. err := tx.Begin()
  3404. defer func() {
  3405. switch {
  3406. case err != nil:
  3407. if tx != nil {
  3408. tx.Rollback()
  3409. }
  3410. default:
  3411. if tx != nil {
  3412. err = tx.Commit()
  3413. }
  3414. }
  3415. if tx != nil {
  3416. tx.Close()
  3417. }
  3418. }()
  3419. sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
  3420. if sql != "" {
  3421. parammaps := fsion.Get("parammaps")
  3422. logging.Info("AddFtdry ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
  3423. paramslist := strings.Split(p, ",")
  3424. if len(paramslist) > 0 && p != "" {
  3425. for _, value := range paramslist {
  3426. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3427. if tempv, exists := c.Get("jwt_username"); exists {
  3428. s_params = append(s_params, tempv.(string))
  3429. } else {
  3430. s_params = append(s_params, "")
  3431. }
  3432. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3433. ids, err := setting.SnowIds.NextId()
  3434. if err != nil {
  3435. ids = time.Now().UnixNano()
  3436. logging.Info("create SnowIds err", err)
  3437. }
  3438. s_params = append(s_params, ids)
  3439. } else {
  3440. s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
  3441. }
  3442. }
  3443. }
  3444. var actweight float64
  3445. actweightList, err := tx.SQL(`select ROUND(avg(actweight),2) as actweight from ftdry
  3446. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))
  3447. and operatetime = (select date_format(operatetime ,'%Y-%m-%d') from ftdry
  3448. where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? ))
  3449. and date_format(operatetime ,'%Y-%m-%d') <date_format(? ,'%Y-%m-%d') and pastureid = ?
  3450. group by operatetime order by operatetime desc limit 1) and pastureid = ?`,
  3451. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("operatetime").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3452. if err != nil {
  3453. logging.Error("AddFtdry err: ", err)
  3454. msg := geterrmsg(err.Error())
  3455. appG.Response(http.StatusOK, e.ERROR, msg)
  3456. }
  3457. if len(actweightList) > 0 {
  3458. for _, item := range actweightList {
  3459. fl, err := strconv.ParseFloat(item["actweight"].(string), 64)
  3460. if err != nil {
  3461. logging.Error("AddFtdry err: ", err)
  3462. msg := geterrmsg(err.Error())
  3463. appG.Response(http.StatusOK, e.ERROR, msg)
  3464. }
  3465. actweight = fl
  3466. }
  3467. } else {
  3468. dryList, err := tx.SQL(`select ifnull(dry,0.0) as dry from feednur where fid in (select fid from ftdetail
  3469. where ftid = (select ftid from feedp where barid = ? and pastureid = ?)) and pastureid = ?`,
  3470. parammaps.Get("barid").ValueStr(), parammaps.Get("pastureid").ValueStr(), parammaps.Get("pastureid").ValueStr()).Query().List()
  3471. if err != nil {
  3472. logging.Error("AddFtdry err: ", err)
  3473. msg := geterrmsg(err.Error())
  3474. appG.Response(http.StatusOK, e.ERROR, msg)
  3475. }
  3476. for _, item := range dryList {
  3477. dry, err := strconv.ParseFloat(item["dry"].(string), 64)
  3478. if err != nil {
  3479. logging.Error("AddFtdry err: ", err)
  3480. msg := geterrmsg(err.Error())
  3481. appG.Response(http.StatusOK, e.ERROR, msg)
  3482. }
  3483. actweight += parammaps.Get("freshweight").ValueFloat64() * dry
  3484. }
  3485. }
  3486. if sqlnamestr == "insertFtdry" {
  3487. s_params = append(s_params, actweight)
  3488. } else if sqlnamestr == "updateFtdry" {
  3489. sql = fmt.Sprintf(sql, actweight)
  3490. }
  3491. queryData, err := execDataBySqlT(sql, s_params, tx)
  3492. if err != nil {
  3493. logging.Error("AddFtdry err: ", err)
  3494. msg := geterrmsg(err.Error())
  3495. appG.Response(http.StatusOK, e.ERROR, msg)
  3496. } else {
  3497. appG.Response(http.StatusOK, e.SUCCESS, queryData)
  3498. }
  3499. } else {
  3500. appG.Response(http.StatusOK, e.SUCCESS, nil)
  3501. }
  3502. }
  3503. func CheckDates(c *gin.Context) {
  3504. tx := restful.Engine.NewSession()
  3505. defer tx.Close()
  3506. appG := app.Gin{C: c}
  3507. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  3508. tempval_ := make(map[string]interface{})
  3509. tempCommon := make(map[string]interface{})
  3510. tempval := make([]map[string]interface{}, 0)
  3511. err := json.Unmarshal(dataByte, &tempval_)
  3512. logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3513. // fmt.Println("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  3514. if err != nil {
  3515. } else {
  3516. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  3517. tempCommon = v
  3518. }
  3519. if v, ok := tempval_["data"].([]interface{}); ok {
  3520. for _, Tvalue := range v {
  3521. if v1, ok := Tvalue.(map[string]interface{}); ok {
  3522. tempval = append(tempval, v1)
  3523. }
  3524. }
  3525. }
  3526. if err == nil {
  3527. if tempv, exists := c.Get("jwt_username"); exists {
  3528. tempCommon["jwt_username"] = tempv.(string)
  3529. }
  3530. for _, paramvalue := range tempval {
  3531. if _, ok := paramvalue["resultname"]; !ok {
  3532. paramvalue["resultname"] = paramvalue["name"]
  3533. }
  3534. _, err := ExecDataQuery(paramvalue, tempCommon, tempval, nil, nil, tx)
  3535. if err != nil {
  3536. logging.Error("ExecDataParam error:", err)
  3537. }
  3538. }
  3539. if err == nil {
  3540. vmsg := ""
  3541. for _, item := range tempval {
  3542. for _, list := range item["resultmaps"].(map[string]interface{}) {
  3543. for _, childrenList := range list.([]interface{}) {
  3544. for k, children := range childrenList.(map[string]interface{}) {
  3545. if k != "children" {
  3546. continue
  3547. }
  3548. for _, v := range children.([]map[string]interface{}) {
  3549. for k1, v1 := range v["resultmaps"].(map[string]interface{}) {
  3550. if k1 == "list" {
  3551. for _, v2 := range v1.([]map[string]interface{}) {
  3552. if v2["vmsg"].(string) != "1" {
  3553. if len(vmsg) == 0 {
  3554. vmsg = v2["vmsg"].(string)
  3555. } else {
  3556. vmsg = fmt.Sprintf("%s,%s", vmsg, v2["vmsg"])
  3557. }
  3558. }
  3559. }
  3560. }
  3561. }
  3562. }
  3563. }
  3564. }
  3565. }
  3566. }
  3567. if len(vmsg) > 0 {
  3568. appG.Response(http.StatusOK, e.SUCCESS, vmsg)
  3569. } else {
  3570. appG.Response(http.StatusOK, e.SUCCESS, true)
  3571. }
  3572. } else {
  3573. msg := geterrmsg(err.Error())
  3574. appG.Response(http.StatusInternalServerError, e.ERROR, msg)
  3575. }
  3576. }
  3577. }
  3578. if err != nil {
  3579. msg := geterrmsg(err.Error())
  3580. appG.Response(http.StatusOK, e.ERROR, msg)
  3581. }
  3582. }
  3583. func ExecDataQuery(fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, ParentParamMap map[string]interface{}, sameParamMap []map[string]interface{}, tx *xorm.Session) (interface{}, error) {
  3584. sqlname := fasion["name"].(string)
  3585. sqltype := "" //v 校验/s1 查询/sm 查询/e 执行
  3586. if v, ok := fasion["type"]; ok {
  3587. sqltype = v.(string)
  3588. }
  3589. sql := ""
  3590. p := ""
  3591. s_params := make([]interface{}, 0)
  3592. if sqltype != "" {
  3593. sql, p = restful.GetSqlByName(sqlname, tx)
  3594. //sqlApi, _ := models.GetApisqlByName(sqlname)
  3595. if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
  3596. paramslist := strings.Split(p, ",")
  3597. if len(paramslist) > 0 && p != "" {
  3598. for _, value := range paramslist {
  3599. ss := ""
  3600. if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3601. ids, err := setting.SnowIds.NextId()
  3602. if err != nil {
  3603. ids = time.Now().UnixNano()
  3604. logging.Info("create SnowIds err", err)
  3605. }
  3606. s_params = append(s_params, ids)
  3607. } else {
  3608. if ss == "" && CommonParamMap != nil {
  3609. if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
  3610. ss = valuestring
  3611. tempstrb := strings.IndexAny(valuestring, "@")
  3612. tempstre := strings.IndexAny(valuestring, ".")
  3613. if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
  3614. if CommonParamMap[valuestring[tempstre+1:]] != nil {
  3615. ss = CommonParamMap[valuestring[tempstre+1:]].(string)
  3616. }
  3617. } else {
  3618. ss = ""
  3619. }
  3620. }
  3621. }
  3622. if ss == "" && ParentParamMap != nil {
  3623. ss = getParamValue_(v, value, ParentParamMap)
  3624. }
  3625. if ss == "" && sameParamMap != nil {
  3626. ss = getParamValue(v, value, sameParamMap)
  3627. }
  3628. if ss == "" && ParamMap != nil {
  3629. ss = getParamValue(v, value, ParamMap)
  3630. }
  3631. s_params = append(s_params, ss)
  3632. }
  3633. }
  3634. }
  3635. }
  3636. }
  3637. if sql == "" {
  3638. sqltype = ""
  3639. }
  3640. if sql != "" {
  3641. tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
  3642. if err != nil {
  3643. return nil, err
  3644. }
  3645. // fmt.Println(tempValParam)
  3646. return tempValParam.(map[string]interface{}), nil
  3647. } else {
  3648. if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
  3649. err := ExitsChildrenQuery(fasion, tempValParam, ParamMap, CommonParamMap, tx)
  3650. if err != nil {
  3651. return nil, err
  3652. }
  3653. return nil, err
  3654. }
  3655. }
  3656. return nil, nil
  3657. }
  3658. func ExitsChildrenQuery(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *xorm.Session) error {
  3659. var err error
  3660. subarray, ok := fasion["children"]
  3661. if ok {
  3662. for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
  3663. tempVal_arrary := make([]map[string]interface{}, 0)
  3664. for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
  3665. tempVal_ := make(map[string]interface{})
  3666. if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
  3667. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
  3668. } else {
  3669. tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
  3670. }
  3671. tempVal_["resultmaps"], err = ExecDataQuery(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
  3672. if err != nil {
  3673. return err
  3674. }
  3675. tempVal_arrary = append(tempVal_arrary, tempVal_)
  3676. }
  3677. v.(map[string]interface{})["children"] = tempVal_arrary
  3678. }
  3679. }
  3680. return nil
  3681. }
  3682. func FpdImportExcel(c *gin.Context) {
  3683. appG := app.Gin{C: c}
  3684. inputdata := ""
  3685. c.Request.ParseForm()
  3686. params := c.Request.Form
  3687. file, _, err := c.Request.FormFile("file")
  3688. if err != nil {
  3689. appG.Response(http.StatusOK, e.ERROR, err)
  3690. return
  3691. }
  3692. sqlnamestrs := params.Get("name")
  3693. sheetname := params.Get("sheetname")
  3694. pastureid := params.Get("pastureid")
  3695. // importParams := params.Get("importParams")
  3696. logging.Info("ImportExcel ", c.Keys, c.Request.RemoteAddr, sqlnamestrs)
  3697. // 必输项参数 (字符串格式 "field1,field2,field3")
  3698. requiredParams := params.Get("requiredParams")
  3699. // 日期参数
  3700. dateParams := params.Get("dateParams")
  3701. // 数字参数
  3702. numParams := params.Get("numParams")
  3703. //将字符串分割开
  3704. dateParamslist := strings.Split(dateParams, ",")
  3705. requiredParamslist := strings.Split(requiredParams, ",")
  3706. numParamslist := strings.Split(numParams, ",")
  3707. queryData := make([]interface{}, 0)
  3708. sqlslist := strings.Split(sqlnamestrs, ",")
  3709. xlsx1, err := excelize.OpenReader(file)
  3710. if err != nil {
  3711. fmt.Println(err)
  3712. return
  3713. }
  3714. ok := 0
  3715. error := 0
  3716. isdone := true
  3717. tx := restful.Engine.NewSession()
  3718. defer tx.Close()
  3719. oldFpdList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  3720. join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  3721. if err != nil {
  3722. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3723. return
  3724. }
  3725. for _, item := range oldFpdList {
  3726. fmt.Println(item)
  3727. }
  3728. rows, _ := xlsx1.GetRows(sheetname)
  3729. // 限制10000条,多余的截取掉
  3730. if len(rows) > 10000 {
  3731. rows = rows[:10000]
  3732. }
  3733. for i, row := range rows {
  3734. if i > 0 {
  3735. entry := make(map[string]interface{})
  3736. outentry := make(map[string]interface{})
  3737. for j, colCell := range rows[0] {
  3738. for k, colCell1 := range row {
  3739. if j == k {
  3740. outentry[colCell] = colCell1
  3741. entry[colCell] = colCell1
  3742. }
  3743. }
  3744. }
  3745. inputdata = ""
  3746. a := ""
  3747. // fmt.Println(outentry, entry, "aaaaaaaaaaa")
  3748. //校验日期格式
  3749. for _, v := range dateParamslist {
  3750. if v == "" {
  3751. continue
  3752. }
  3753. if d, ok := outentry[strings.Trim(v, " ")]; ok {
  3754. dtime, err := TransfTime(d.(string))
  3755. if err != nil {
  3756. a = strings.Trim(v, " ")
  3757. break
  3758. }
  3759. outentry[strings.Trim(v, " ")] = dtime
  3760. }
  3761. }
  3762. if a != "" {
  3763. outentry["error_msg"] = a + " 格式错误"
  3764. error++
  3765. queryData = append(queryData, outentry)
  3766. continue
  3767. }
  3768. a = ""
  3769. //校验必填格式
  3770. for _, v := range requiredParamslist {
  3771. if v == "" {
  3772. continue
  3773. }
  3774. if d, ok := outentry[strings.Trim(v, " ")]; !ok || d == "" {
  3775. a = strings.Trim(v, " ")
  3776. break
  3777. }
  3778. }
  3779. if a != "" {
  3780. outentry["error_msg"] = a + " 未填或格式错误"
  3781. error++
  3782. queryData = append(queryData, outentry)
  3783. continue
  3784. }
  3785. a = ""
  3786. //校验数字格式
  3787. for _, v := range numParamslist {
  3788. if v == "" {
  3789. continue
  3790. }
  3791. d, ok := outentry[strings.Trim(v, " ")]
  3792. if !ok || d == "" {
  3793. outentry[strings.Trim(v, " ")] = 0
  3794. } else {
  3795. var fl float64
  3796. switch d.(type) {
  3797. case string:
  3798. fl, err = strconv.ParseFloat(d.(string), 64)
  3799. }
  3800. if err != nil || fl < 0 {
  3801. a = strings.Trim(v, " ")
  3802. break
  3803. }
  3804. }
  3805. }
  3806. if a != "" {
  3807. outentry["error_msg"] = a + " 为数值类型且不可为负数"
  3808. error++
  3809. queryData = append(queryData, outentry)
  3810. continue
  3811. }
  3812. errExist := false
  3813. for _, sqlnamestr := range sqlslist {
  3814. sql, paramslists := restful.GetSqlByNameDB(strings.Replace(sqlnamestr, " ", "", -1))
  3815. paramslist := strings.Split(paramslists, ",")
  3816. if len(paramslist) > 0 {
  3817. s_params := make([]interface{}, 0)
  3818. for _, value := range paramslist {
  3819. if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
  3820. if tempv, exists := c.Get("jwt_username"); exists {
  3821. s_params = append(s_params, tempv.(string))
  3822. } else {
  3823. s_params = append(s_params, "")
  3824. }
  3825. } else if strings.ToLower(strings.Trim(value, " ")) == "pastureid" {
  3826. s_params = append(s_params, pastureid)
  3827. } else if strings.ToLower(strings.Trim(value, " ")) == "snowid" {
  3828. ids, err := setting.SnowIds.NextId()
  3829. if err != nil {
  3830. ids = time.Now().UnixNano()
  3831. logging.Info("create SnowIds err", err)
  3832. }
  3833. s_params = append(s_params, ids)
  3834. } else {
  3835. if outentry[strings.Trim(value, " ")] == nil {
  3836. s_params = append(s_params, "")
  3837. } else {
  3838. s_params = append(s_params, outentry[strings.Trim(value, " ")])
  3839. }
  3840. }
  3841. }
  3842. outentry["input"] = inputdata
  3843. returnmsgmap1, err := tx.SQL(sql, s_params...).Query().List()
  3844. if err != nil {
  3845. errExist = true
  3846. // if tx != nil {
  3847. // tx.Rollback()
  3848. // }
  3849. // if tx != nil {
  3850. // tx.Close()
  3851. // }
  3852. msg := geterrmsg(err.Error())
  3853. outentry["error_msg"] = msg
  3854. error++
  3855. queryData = append(queryData, outentry)
  3856. isdone = true
  3857. break
  3858. } else {
  3859. if len(returnmsgmap1) > 0 {
  3860. if va, ok := returnmsgmap1[0]["msg"]; ok && va != "" {
  3861. // if tx != nil {
  3862. // tx.Rollback()
  3863. // }
  3864. // if tx != nil {
  3865. // tx.Close()
  3866. // }
  3867. msg := geterrmsg(va.(string))
  3868. outentry["error_msg"] = msg
  3869. error++
  3870. queryData = append(queryData, outentry)
  3871. isdone = true
  3872. break
  3873. }
  3874. }
  3875. isdone = false
  3876. }
  3877. }
  3878. }
  3879. if !errExist {
  3880. dataexcel := make(map[string]interface{}, 0)
  3881. if _, ok := outentry["栏舍名称"]; ok {
  3882. dataexcel["barname"] = outentry["栏舍名称"]
  3883. }
  3884. if _, ok := outentry["实际牛头数"]; ok {
  3885. dataexcel["ccount"] = outentry["实际牛头数"]
  3886. }
  3887. if _, ok := outentry["系数(%)"]; ok {
  3888. dataexcel["ratio"] = outentry["系数(%)"]
  3889. }
  3890. if _, ok := outentry["配方模板"]; ok {
  3891. dataexcel["ftname"] = outentry["配方模板"]
  3892. }
  3893. if _, ok := outentry["补料配方"]; ok {
  3894. dataexcel["ptsfname"] = outentry["补料配方"]
  3895. }
  3896. if _, ok := outentry["第一班比例(%)"]; ok {
  3897. dataexcel["1"] = outentry["第一班比例(%)"]
  3898. }
  3899. if _, ok := outentry["第二班比例(%)"]; ok {
  3900. dataexcel["2"] = outentry["第二班比例(%)"]
  3901. }
  3902. if _, ok := outentry["第三班比例(%)"]; ok {
  3903. dataexcel["3"] = outentry["第三班比例(%)"]
  3904. }
  3905. if _, ok := outentry["第四班比例(%)"]; ok {
  3906. dataexcel["4"] = outentry["第四班比例(%)"]
  3907. }
  3908. exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3909. if err != nil {
  3910. logs.Error(err)
  3911. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3912. return
  3913. }
  3914. if !exist {
  3915. _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
  3916. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
  3917. if err != nil {
  3918. logs.Error(err)
  3919. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3920. return
  3921. }
  3922. }
  3923. var feedpargs []interface{}
  3924. upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
  3925. feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
  3926. if _, ok := dataexcel["ftname"]; ok {
  3927. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ftname"])
  3928. upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
  3929. upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
  3930. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01)) `
  3931. feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  3932. } else {
  3933. upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
  3934. }
  3935. if _, ok := dataexcel["ptsfname"]; ok {
  3936. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ptsfname"])
  3937. upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
  3938. upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
  3939. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))`
  3940. feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
  3941. } else {
  3942. upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
  3943. }
  3944. upFeedpSql += " where barname = ? and pastureid = ? "
  3945. feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
  3946. _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
  3947. if err != nil {
  3948. logs.Error(err)
  3949. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3950. return
  3951. }
  3952. exist1, err := tx.SQL(` select id from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
  3953. if err != nil {
  3954. logs.Error(err)
  3955. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3956. return
  3957. }
  3958. if !exist1 {
  3959. _, err := tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
  3960. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  3961. if err != nil {
  3962. logs.Error(err)
  3963. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3964. return
  3965. }
  3966. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,2,0,0,0,-1,-1) `,
  3967. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  3968. if err != nil {
  3969. logs.Error(err)
  3970. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3971. return
  3972. }
  3973. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,3,0,0,0,-1,-1) `,
  3974. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  3975. if err != nil {
  3976. logs.Error(err)
  3977. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3978. return
  3979. }
  3980. _, err = tx.SQL(` insert into fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where bname = ? and pastureid = ? ),?,4,0,0,0,-1,-1) `,
  3981. pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
  3982. if err != nil {
  3983. logs.Error(err)
  3984. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3985. return
  3986. }
  3987. }
  3988. upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  3989. where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  3990. ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  3991. and pastureid = ? and times = ?`
  3992. var fpdargs1 []interface{}
  3993. fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
  3994. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  3995. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
  3996. _, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
  3997. if err != nil {
  3998. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  3999. return
  4000. }
  4001. // upFpdSql := ` update fpdetail set tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
  4002. // where ftid = (select id from feedtemplet where tname = ? and pastureid = ? )) * (?*(?*0.01))) ,cowcount = ? ,
  4003. // ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? ) where barname = ?
  4004. // and pastureid = ? and times = ?`
  4005. var fpdargs2 []interface{}
  4006. fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
  4007. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4008. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
  4009. _, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
  4010. if err != nil {
  4011. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4012. return
  4013. }
  4014. var fpdargs3 []interface{}
  4015. fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
  4016. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4017. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
  4018. _, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
  4019. if err != nil {
  4020. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4021. return
  4022. }
  4023. var fpdargs4 []interface{}
  4024. fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
  4025. dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
  4026. dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
  4027. _, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
  4028. if err != nil {
  4029. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4030. return
  4031. }
  4032. // _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ? and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
  4033. newList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,id,ptid,weight,times from fpdetail where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Query().List()
  4034. if err != nil {
  4035. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  4036. return
  4037. }
  4038. // oldFpdList, err := tx.SQL(` select fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight from fpdetail fpd
  4039. // join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
  4040. upFpdetailList := make([]*upFpdetail, 0)
  4041. for _, newfpd := range newList {
  4042. for _, oldfpd := range oldFpdList {
  4043. if oldfpd["id"].(int64) == newfpd["id"].(int64) {
  4044. var oldweight, newweight float64
  4045. if oldfpd["weight"] != nil {
  4046. oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
  4047. }
  4048. if newfpd["weight"] != nil {
  4049. newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
  4050. }
  4051. fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
  4052. upFpdetailList = append(upFpdetailList, &upFpdetail{
  4053. Old: oldweight,
  4054. New: newweight,
  4055. Times: newfpd["times"].(int64),
  4056. Ptid: newfpd["ptid"].(int64),
  4057. Fweight: fweight,
  4058. Id: oldfpd["id"].(int64),
  4059. })
  4060. break
  4061. }
  4062. }
  4063. }
  4064. updateFpdetailByBar(pastureid, dataexcel["barname"].(string), upFpdetailList)
  4065. }
  4066. }
  4067. if !isdone {
  4068. ok++
  4069. isdone = true
  4070. }
  4071. }
  4072. data := make(map[string]interface{})
  4073. data["result"] = queryData
  4074. data["success"] = ok
  4075. data["err_count"] = error
  4076. appG.Response(http.StatusOK, e.SUCCESS, data)
  4077. }
  4078. type upFpdetail struct {
  4079. Old float64
  4080. New float64
  4081. Times int64
  4082. Ptid int64
  4083. Fweight float64
  4084. Id int64
  4085. // Ptsid string
  4086. }
  4087. func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
  4088. tx := restful.Engine.NewSession()
  4089. defer tx.Close()
  4090. tx.Begin()
  4091. for _, data := range dataList {
  4092. // select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  4093. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
  4094. // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
  4095. // UNION
  4096. // fpdDataList, err := tx.SQL(` select * from (
  4097. // SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
  4098. // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
  4099. // WHERE fpdetail.pastureid = ? and barname = ? and times = ? ) t
  4100. // order by t.barname,t.times`, pastureid, barname, data.Times).Query().List()
  4101. // if err != nil {
  4102. // tx.Rollback()
  4103. // logs.Error(err)
  4104. // }
  4105. // for _, fpd := range fpdDataList {
  4106. // ptid, err := strconv.ParseInt(fpd["ptid"].(string), 10, 64)
  4107. // if fpd["times"].(int64) == data.Times && (ptid == data.Ptid) {
  4108. fttype := -1
  4109. if data.Ptid != -1 {
  4110. fttype = 1
  4111. }
  4112. var fweight float64
  4113. var lweight float64
  4114. lpplandtl1List := make([]*lpplandtlInfo, 0)
  4115. err := tx.SQL(`select lppland.*,lpp.maxweight from lpplan lpp
  4116. join lpplandtl1 lppland on lpp.id = lppland.lppid where lppland.fpdid =?
  4117. and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
  4118. data.Id, fttype, pastureid, data.Times).Find(&lpplandtl1List)
  4119. if err != nil {
  4120. tx.Rollback()
  4121. logs.Error(err)
  4122. return err
  4123. }
  4124. weight := data.Fweight
  4125. // weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
  4126. var w float64
  4127. var status int
  4128. if data.New < data.Old {
  4129. if weight >= 0 {
  4130. continue
  4131. }
  4132. w = weight
  4133. status = 0
  4134. } else {
  4135. // if weight-(data.New-data.Old) > 0 {
  4136. // continue
  4137. // }
  4138. w = data.New - data.Old
  4139. status = 1
  4140. }
  4141. // if weight < oldweight {
  4142. // if weight >= 0 {
  4143. // return
  4144. // }
  4145. // w = weight
  4146. // status = 0
  4147. // } else {
  4148. // if oldweight > 0 {
  4149. // return
  4150. // }
  4151. // w = weight
  4152. // status = 1
  4153. // }
  4154. // for _, lppland := range lpplandtl1List {
  4155. // lweight += lppland.Lweight
  4156. // }
  4157. for _, lppland := range lpplandtl1List {
  4158. var lppdata lpplandtlInfo
  4159. tx.SQL(`select sum(lweight) as lweight from lpplandtl1 lpp where lppid = ? and lpp.pastureid = ? `,
  4160. lppland.Lppid, pastureid).GetFirst(&lppdata)
  4161. if err != nil {
  4162. tx.Rollback()
  4163. logs.Error(err)
  4164. return err
  4165. }
  4166. lweight = lppdata.Lweight
  4167. if status == 1 {
  4168. // if w <= lppland.Lweight {
  4169. if lppland.Maxweight <= lweight {
  4170. continue
  4171. }
  4172. if w+lweight <= lppland.Maxweight {
  4173. lppland.Lweight += w
  4174. lweight += w
  4175. fweight += w
  4176. w = 0
  4177. } else {
  4178. w = w - (lppland.Maxweight - lweight)
  4179. n := (lppland.Maxweight - lweight)
  4180. lppland.Lweight = lppland.Lweight + n
  4181. lweight += n
  4182. fweight += n
  4183. }
  4184. } else {
  4185. if lppland.Lweight == 0 {
  4186. continue
  4187. }
  4188. if w+lppland.Lweight >= 0 {
  4189. lppland.Lweight = lppland.Lweight + w
  4190. lweight = lweight + w
  4191. fweight = fweight + w
  4192. w = 0
  4193. } else {
  4194. w = w + lppland.Lweight
  4195. lweight = lweight - lppland.Lweight
  4196. fweight = fweight - lppland.Lweight
  4197. lppland.Lweight = 0
  4198. }
  4199. }
  4200. _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
  4201. if err != nil {
  4202. tx.Rollback()
  4203. logs.Error(err)
  4204. return err
  4205. }
  4206. break
  4207. }
  4208. _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
  4209. ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4210. WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, data.Id).Execute()
  4211. if err != nil {
  4212. tx.Rollback()
  4213. logs.Error(err)
  4214. return err
  4215. }
  4216. // if w == 0 {
  4217. // break
  4218. // }
  4219. // }
  4220. }
  4221. err := tx.Commit()
  4222. if err != nil {
  4223. logs.Error(err)
  4224. tx.Rollback()
  4225. return err
  4226. }
  4227. return nil
  4228. }
  4229. func DeleteFTdetail(c *gin.Context) {
  4230. appG := app.Gin{C: c}
  4231. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4232. fsion := gofasion.NewFasion(string(dataByte))
  4233. parammaps := fsion.Get("parammaps")
  4234. pastureid := parammaps.Get("pastureid").ValueStr()
  4235. ftid := parammaps.Get("ftid").ValueStr()
  4236. tx := restful.Engine.NewSession()
  4237. defer tx.Close()
  4238. tx.Begin()
  4239. _, err := tx.SQL(`delete from ftdetail where ftid = ? and pastureid = ? `, ftid, pastureid).Execute()
  4240. if err != nil {
  4241. tx.Rollback()
  4242. logs.Error(err)
  4243. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4244. return
  4245. }
  4246. if parammaps.Get("type").ValueStr() == "1" {
  4247. _, err := tx.SQL(`UPDATE feedp fp
  4248. set
  4249. fp.ftweight= IFNULL(IF(
  4250. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4251. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4252. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4253. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4254. ),0),fp.feedweight = IFNULL(IF(
  4255. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4256. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4257. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4258. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ftid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4259. ),0) +ifnull(fp.supplyweight,0)
  4260. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4261. if err != nil {
  4262. tx.Rollback()
  4263. logs.Error(err)
  4264. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4265. return
  4266. }
  4267. // UPDATE fpdetail SET ptuse=0 ,weight = 0
  4268. _, err = tx.SQL(`
  4269. UPDATE fpdetail fpd
  4270. INNER JOIN feedp fp
  4271. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4272. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4273. ptuse= 0
  4274. WHERE fp.pastureid = ? AND fp.ftid =?`, pastureid, ftid).Execute()
  4275. if err != nil {
  4276. tx.Rollback()
  4277. logs.Error(err)
  4278. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4279. return
  4280. }
  4281. } else {
  4282. _, err := tx.SQL(`UPDATE feedp fp
  4283. SET
  4284. fp.supplyweight= IFNULL(IF(
  4285. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4286. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4287. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4288. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4289. ),0),fp.feedweight = IFNULL(IF(
  4290. (SELECT sysopt.inforvalue FROM sysopt WHERE sysopt.pastureid= fp.pastureid AND sysopt.inforname='isLockCount')=0,
  4291. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid ),0)*ccountratio,
  4292. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=0),0)*ccountratio +
  4293. IFNULL((SELECT SUM(fweight) FROM ftdetail WHERE ftdetail.ftid =fp.ptsfid AND ftdetail.pastureid=fp.pastureid AND ftdetail.islockcount=1),0)*ccount
  4294. ),0) + ifnull(fp.supplyweight,0)
  4295. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4296. if err != nil {
  4297. tx.Rollback()
  4298. logs.Error(err)
  4299. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4300. return
  4301. }
  4302. // ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
  4303. _, err = tx.SQL(`
  4304. UPDATE fpdetail fpd
  4305. INNER JOIN feedp fp
  4306. ON fpd.barid = fp.barid AND fpd.pastureid = fp.pastureid
  4307. SET fpd.weight = fp.feedweight*fpd.tratio/100,
  4308. ptsrate = 0
  4309. WHERE fp.pastureid = ? AND fp.ptsfid =?`, pastureid, ftid).Execute()
  4310. if err != nil {
  4311. tx.Rollback()
  4312. logs.Error(err)
  4313. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4314. return
  4315. }
  4316. }
  4317. _, err = tx.SQL(` update lpplandtl1 set lweight = 0 where lppid in(select id from lpplan where ftid = ? and pastureid = ? )`, ftid, pastureid).Execute()
  4318. if err != nil {
  4319. tx.Rollback()
  4320. logs.Error(err)
  4321. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4322. return
  4323. }
  4324. err = tx.Commit()
  4325. if err != nil {
  4326. tx.Rollback()
  4327. logs.Error(err)
  4328. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4329. return
  4330. }
  4331. appG.Response(http.StatusOK, e.SUCCESS, true)
  4332. }
  4333. func DeleteSpillageAll(c *gin.Context) {
  4334. appG := app.Gin{C: c}
  4335. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4336. fsion := gofasion.NewFasion(string(dataByte))
  4337. parammaps := fsion.Get("parammaps")
  4338. pastureid := parammaps.Get("pastureid").ValueStr()
  4339. times := parammaps.Get("times").ValueStr()
  4340. tx := restful.Engine.NewSession()
  4341. defer tx.Close()
  4342. lpplandtl1List, err := tx.SQL(` select lppland.* from lpplan lpp join lpplandtl1 lppland on lppland.lppid = lpp.id where lpp.times = ? `, times).Query().List()
  4343. if err != nil {
  4344. logs.Error(err)
  4345. appG.Response(http.StatusOK, e.ERROR, false)
  4346. return
  4347. }
  4348. now := time.Now()
  4349. for _, item := range lpplandtl1List {
  4350. go func(item map[string]interface{}) {
  4351. _, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
  4352. background,cowcount,ccountradio,lweighthis,createdate)
  4353. values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
  4354. item["pastureid"], item["lppid"], item["barid"],
  4355. item["barname"], item["fpdid"], item["fttype"],
  4356. item["lweight"], item["sort"], item["tmrid"],
  4357. item["tmrname"], item["background"], item["cowcount"],
  4358. item["ccountradio"], item["lweighthis"], now).Execute()
  4359. if err != nil {
  4360. logs.Error(err)
  4361. appG.Response(http.StatusOK, e.ERROR, false)
  4362. return
  4363. }
  4364. }(item)
  4365. }
  4366. tx.Begin()
  4367. _, err = tx.SQL(` delete from lpplandtl1 where pastureid = ? and lppid in(select id from lpplan where pastureid = ? and times = ?) `, pastureid, pastureid, times).Execute()
  4368. if err != nil {
  4369. tx.Rollback()
  4370. logs.Error(err)
  4371. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4372. return
  4373. }
  4374. _, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
  4375. WHERE pastureid=? and times = ? `, pastureid, times).Execute()
  4376. if err != nil {
  4377. tx.Rollback()
  4378. logs.Error(err)
  4379. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4380. return
  4381. }
  4382. err = tx.Commit()
  4383. if err != nil {
  4384. tx.Rollback()
  4385. logs.Error(err)
  4386. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4387. return
  4388. }
  4389. appG.Response(http.StatusOK, e.SUCCESS, true)
  4390. }
  4391. func GetTMRListEnableTypeAll(c *gin.Context) {
  4392. appG := app.Gin{C: c}
  4393. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4394. fsion := gofasion.NewFasion(string(dataByte))
  4395. parammaps := fsion.Get("parammaps")
  4396. pastureid := parammaps.Get("pastureid").ValueStr()
  4397. tx := restful.Engine.NewSession()
  4398. defer tx.Close()
  4399. dataList, err := tx.SQL(`SELECT
  4400. eqcode,
  4401. tname,
  4402. datacaptureno,
  4403. trim(tclassid) tclassid,
  4404. concat(tname,' / ',eqcode) tmrmix,
  4405. d.label tclassname,
  4406. maxstirfeed,
  4407. remark,
  4408. tmr.enable,
  4409. TRIM(tmr.id) id,
  4410. TRIM(tmr.pastureid)pastureid
  4411. FROM
  4412. tmr
  4413. left join dictlist d on d.pid = 16 and d.value = tmr.tclassid
  4414. WHERE tmr.pastureid = ? and tmr.enable=1 and tclassid in (1,3)
  4415. ORDER BY id DESC`, pastureid).Query().List()
  4416. if err != nil {
  4417. logs.Error(err)
  4418. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4419. return
  4420. }
  4421. sysoptData, err := tx.SQL(`select inforvalue from sysopt where inforname = 'anyCar' and pastureid = ? `, pastureid).Query().List()
  4422. if err != nil {
  4423. logs.Error(err)
  4424. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4425. return
  4426. }
  4427. var carNum int64
  4428. for _, sysopt := range sysoptData {
  4429. if sysopt["inforvalue"] == nil {
  4430. carNum = 1
  4431. } else {
  4432. carNum, _ = strconv.ParseInt(sysopt["inforvalue"].(string), 10, 64)
  4433. }
  4434. }
  4435. id := 200
  4436. n := 0
  4437. for i := carNum; i > 0; i-- {
  4438. id++
  4439. n++
  4440. data := make(map[string]interface{}, 0)
  4441. data["eqcode"] = fmt.Sprintf("任意车%d", n)
  4442. data["tname"] = fmt.Sprintf("任意车%d", n)
  4443. data["datacaptureno"] = -2
  4444. data["tclassid"] = -2
  4445. data["tmrmix"] = fmt.Sprintf("任意车%d", n)
  4446. data["tclassname"] = fmt.Sprintf("任意车%d", n)
  4447. data["maxstirfeed"] = 100000
  4448. data["remark"] = fmt.Sprintf("任意车%d", n)
  4449. data["enable"] = 1
  4450. data["id"] = fmt.Sprintf("%d", id)
  4451. data["pastureid"] = pastureid
  4452. dataList = append(dataList, data)
  4453. }
  4454. // UNION ALL
  4455. // SELECT '任意车','任意车','-2',-2,'任意车','任意车',100000,'任意车',1,-2,?
  4456. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4457. }
  4458. func GetFeedpHistory(c *gin.Context) {
  4459. appG := app.Gin{C: c}
  4460. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4461. fsion := gofasion.NewFasion(string(dataByte))
  4462. // parammaps := fsion.Get("parammaps")
  4463. barid := fsion.Get("barid").ValueStr()
  4464. startDate := fsion.Get("startDate").ValueStr()
  4465. endDate := fsion.Get("endDate").ValueStr()
  4466. tx := restful.Engine.NewSession()
  4467. defer tx.Close()
  4468. feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from feedphistory where barid = ?
  4469. and createdate between ? and ? order by createdate desc `, barid, startDate, endDate).Query().List()
  4470. if err != nil {
  4471. logs.Error(err)
  4472. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4473. return
  4474. }
  4475. fpdList, err := tx.SQL(` select times,tratio,weight, DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate from fpdetailhistory where barid = ?
  4476. and createdate between ? and ? order by createdate desc, times asc`, barid, startDate, endDate).Query().List()
  4477. if err != nil {
  4478. logs.Error(err)
  4479. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4480. return
  4481. }
  4482. for _, feedp := range feedpList {
  4483. fmt.Println(feedp)
  4484. for i, fpd := range fpdList {
  4485. if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4486. for k, fpd2 := range fpdList {
  4487. if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4488. if fpd["weight"].(string) != fpd2["weight"].(string) {
  4489. fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4490. }
  4491. break
  4492. }
  4493. }
  4494. fpd["barid"] = feedp["barid"]
  4495. fpd["barname"] = feedp["barname"]
  4496. fpd["ccount"] = feedp["ccount"]
  4497. fpd["ratio"] = feedp["ratio"]
  4498. fpd["ccountratio"] = feedp["ccountratio"]
  4499. fpd["ftid"] = feedp["ftid"]
  4500. fpd["ftname"] = feedp["ftname"]
  4501. }
  4502. }
  4503. }
  4504. appG.Response(http.StatusOK, e.SUCCESS, fpdList)
  4505. }
  4506. // func GetLpplandtl1History(c *gin.Context) {
  4507. // appG := app.Gin{C: c}
  4508. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4509. // fsion := gofasion.NewFasion(string(dataByte))
  4510. // // parammaps := fsion.Get("parammaps")
  4511. // barid := fsion.Get("barid").ValueStr()
  4512. // startDate := fsion.Get("startDate").ValueStr()
  4513. // endDate := fsion.Get("endDate").ValueStr()
  4514. // tx := restful.Engine.NewSession()
  4515. // defer tx.Close()
  4516. // // feedpList, err := tx.SQL(` select lpp.times, DATE_FORMAT(lh.createdate,'%Y-%m-%d %H:%i:%s') as createdate
  4517. // // from lpplandtl1history lh join lpplan lpp on lpp.id = lh.lppid where lh.barid = ?
  4518. // // and lh.createdate between ? and ? order by lh.createdate desc lpp.times `, barid, startDate, endDate).Query().List()
  4519. // // if err != nil {
  4520. // // logs.Error(err)
  4521. // // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4522. // // return
  4523. // // }
  4524. // // for _, feedp := range feedpList {
  4525. // // fmt.Println(feedp)
  4526. // // for i, fpd := range fpdList {
  4527. // // if feedp["createdate"].(string) == fpd["createdate"].(string) {
  4528. // // for k, fpd2 := range fpdList {
  4529. // // if k > i && fpd["times"].(int64) == fpd2["times"].(int64) {
  4530. // // if fpd["weight"].(string) != fpd2["weight"].(string) {
  4531. // // fpd["weight"] = fmt.Sprintf("%v/%v", fpd2["weight"], fpd["weight"])
  4532. // // }
  4533. // // break
  4534. // // }
  4535. // // }
  4536. // // fpd["barid"] = feedp["barid"]
  4537. // // fpd["barname"] = feedp["barname"]
  4538. // // fpd["ccount"] = feedp["ccount"]
  4539. // // fpd["ratio"] = feedp["ratio"]
  4540. // // fpd["ccountratio"] = feedp["ccountratio"]
  4541. // // fpd["ftid"] = feedp["ftid"]
  4542. // // fpd["ftname"] = feedp["ftname"]
  4543. // // }
  4544. // // }
  4545. // // }
  4546. // appG.Response(http.StatusOK, e.SUCCESS, nil)
  4547. // }
  4548. func GetRemind(c *gin.Context) {
  4549. appG := app.Gin{C: c}
  4550. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4551. fsion := gofasion.NewFasion(string(dataByte))
  4552. parammaps := fsion.Get("parammaps")
  4553. pastureid := parammaps.Get("pastureid").ValueStr()
  4554. tx := restful.Engine.NewSession()
  4555. defer tx.Close()
  4556. dataList, err := tx.SQL("select * from remind where pastureid = ? ", pastureid).Query().List()
  4557. if err != nil {
  4558. logs.Error(err)
  4559. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4560. return
  4561. }
  4562. // pastureid = "3"
  4563. resp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%s", pastureid))
  4564. if err != nil {
  4565. logs.Error(err)
  4566. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4567. return
  4568. }
  4569. defer resp.Body.Close()
  4570. buf := bytes.NewBuffer(make([]byte, 0, 512))
  4571. buf.ReadFrom(resp.Body)
  4572. fmt.Println(string(buf.Bytes()))
  4573. respMap := make(map[string]interface{}, 0)
  4574. err = json.Unmarshal(buf.Bytes(), &respMap)
  4575. if err != nil {
  4576. logs.Error(err)
  4577. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4578. return
  4579. }
  4580. for _, data := range dataList {
  4581. r := make(map[string]interface{}, 0)
  4582. r["sys_name"] = ""
  4583. r["service_id"] = ""
  4584. r["pasture_id"] = ""
  4585. r["type_name"] = ""
  4586. r["remind_type_id"] = ""
  4587. r["remind_type"] = ""
  4588. r["push_date"] = ""
  4589. r["push_time"] = ""
  4590. r["interval_time"] = ""
  4591. r["push_limit"] = ""
  4592. r["template_id"] = ""
  4593. r["roles_id"] = ""
  4594. r["users_id"] = ""
  4595. r["date_type"] = ""
  4596. r["cycle_type"] = ""
  4597. data["data"] = r
  4598. for _, resp := range respMap["data"].([]interface{}) {
  4599. resp1 := resp.(map[string]interface{})
  4600. if data["id"].(int64) == int64(resp1["service_id"].(float64)) {
  4601. if resp1["push_time"] == nil {
  4602. resp1["push_time"] = ""
  4603. }
  4604. data["data"] = resp1
  4605. break
  4606. }
  4607. }
  4608. }
  4609. appG.Response(http.StatusOK, e.SUCCESS, dataList)
  4610. }
  4611. type NoticeMsgtype struct {
  4612. SysName string `json:"sys_name"`
  4613. PastureId int64 `json:"pasture_id"`
  4614. ServiceId int64 `json:"service_id"`
  4615. TypeName string `json:"type_name"`
  4616. RemindType int64 `json:"remind_type"`
  4617. PushDate int64 `json:"push_date"`
  4618. PushTime string `json:"push_time"`
  4619. IntervalTime int64 `json:"interval_time"`
  4620. PushLimit int64 `json:"push_limit"`
  4621. TemplateId string `json:"template_id"`
  4622. UsersId string `json:"users_id"`
  4623. DateType int64 `json:"date_type"`
  4624. CycleType int64 `json:"cycle_type"`
  4625. DelayTime int64 `json:"delay_time"`
  4626. Status int64 `json:"status"`
  4627. }
  4628. func UpdateRemind(c *gin.Context) {
  4629. appG := app.Gin{C: c}
  4630. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  4631. parammaps := gofasion.NewFasion(string(dataByte))
  4632. // parammaps := fsion.Get("parammaps")
  4633. // user := parammaps.Get("user").ValueStr()
  4634. id := parammaps.Get("id").ValueInt64()
  4635. noticeMsgtype := new(NoticeMsgtype)
  4636. noticeMsgtype.SysName = parammaps.Get("sys_name").ValueStr()
  4637. noticeMsgtype.ServiceId = id
  4638. noticeMsgtype.PastureId = parammaps.Get("pastureid").ValueInt64()
  4639. noticeMsgtype.TypeName = parammaps.Get("type_name").ValueStr()
  4640. // noticeMsgtype.RemindTypeId = parammaps.Get("remind_type_id").ValueInt64()
  4641. noticeMsgtype.RemindType = parammaps.Get("remind_type").ValueInt64()
  4642. noticeMsgtype.PushDate = parammaps.Get("push_date").ValueInt64()
  4643. noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
  4644. noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
  4645. noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
  4646. noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
  4647. // noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
  4648. noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
  4649. noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
  4650. noticeMsgtype.DelayTime = parammaps.Get("delay_time").ValueInt64()
  4651. noticeMsgtype.Status = parammaps.Get("status").ValueInt64()
  4652. userList := parammaps.Get("user").Array()
  4653. var userstr []string
  4654. for _, user := range userList {
  4655. userstr = append(userstr, user.ValueStr())
  4656. }
  4657. tx := restful.Engine.NewSession()
  4658. defer tx.Close()
  4659. _, err := tx.SQL(` update remind set user = ? where id = ? and pastureid = ? `, strings.Join(userstr, ","), id, noticeMsgtype.PastureId).Execute()
  4660. if err != nil {
  4661. logs.Error(err)
  4662. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4663. return
  4664. }
  4665. // var jsonStr = []byte(noticeMsgtype
  4666. noticeMsgtypebyte, err := json.Marshal(noticeMsgtype)
  4667. req, err := http.NewRequest("POST", "http://tmrwatch.cn/notice/msgtype", bytes.NewBuffer(noticeMsgtypebyte))
  4668. req.Header.Set("Content-Type", "application/json")
  4669. client := &http.Client{}
  4670. resp, err := client.Do(req)
  4671. if err != nil {
  4672. logs.Error(err)
  4673. }
  4674. defer resp.Body.Close()
  4675. body, _ := ioutil.ReadAll(resp.Body)
  4676. fmt.Println("response Body:", string(body))
  4677. getresp, err := http.Get(fmt.Sprintf("http://tmrwatch.cn/notice/msgtype?sys_name=tmrwatch&pasture_id=%d&service_id=%d", noticeMsgtype.PastureId, id))
  4678. if err != nil {
  4679. logs.Error(err)
  4680. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4681. return
  4682. }
  4683. defer getresp.Body.Close()
  4684. buf := bytes.NewBuffer(make([]byte, 0, 512))
  4685. buf.ReadFrom(getresp.Body)
  4686. fmt.Println(string(buf.Bytes()))
  4687. respMap := make(map[string]interface{}, 0)
  4688. err = json.Unmarshal(buf.Bytes(), &respMap)
  4689. if err != nil {
  4690. logs.Error(err)
  4691. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4692. return
  4693. }
  4694. for _, resp := range respMap["data"].([]interface{}) {
  4695. resp1 := resp.(map[string]interface{})
  4696. _, err := tx.SQL(` update remind set service_id = ? where id = ? and pastureid = ? `, resp1["service_id"], id, noticeMsgtype.PastureId).Execute()
  4697. if err != nil {
  4698. logs.Error(err)
  4699. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  4700. return
  4701. }
  4702. }
  4703. appG.Response(http.StatusOK, e.SUCCESS, true)
  4704. }