chart_info.go 164 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294
  1. package data
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_api/models"
  6. "eta/eta_api/models/company"
  7. "eta/eta_api/models/data_manage"
  8. "eta/eta_api/models/system"
  9. "eta/eta_api/services/alarm_msg"
  10. "eta/eta_api/services/data/data_manage_permission"
  11. "eta/eta_api/utils"
  12. "fmt"
  13. "math"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/shopspring/decimal"
  19. )
  20. func ChartInfoRefreshV1(chartInfoId int) (err error) {
  21. var errmsg string
  22. defer func() {
  23. if err != nil {
  24. go alarm_msg.SendAlarmMsg("ChartInfoRefresh:"+errmsg, 3)
  25. //go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "ChartInfoRefresh:"+errmsg, utils.EmailSendToUsers)
  26. fmt.Println("ChartInfoRefresh Err:" + errmsg)
  27. }
  28. }()
  29. baseEdbInfoArr, calculateInfoArr, err := data_manage.GetChartInfoRefreshData(chartInfoId)
  30. if err != nil {
  31. errmsg = "获取需要刷新的指标失败:Err:" + err.Error()
  32. return
  33. }
  34. newBaseEdbInfoArr := make([]*data_manage.EdbInfo, 0)
  35. baseMap := make(map[int]*data_manage.EdbInfo)
  36. for _, bv := range baseEdbInfoArr {
  37. // 如果不是普通指标,那么过滤
  38. if bv.EdbInfoType != 0 {
  39. continue
  40. }
  41. if _, ok := baseMap[bv.EdbInfoId]; !ok {
  42. newBaseEdbInfoArr = append(newBaseEdbInfoArr, bv)
  43. }
  44. baseMap[bv.EdbInfoId] = bv
  45. }
  46. fmt.Println("calculateInfoArr:", len(calculateInfoArr))
  47. newCalculateInfoArr := make([]*data_manage.EdbInfo, 0)
  48. calculateMap := make(map[int]*data_manage.EdbInfo)
  49. var calculateArr []int
  50. for _, bv := range calculateInfoArr {
  51. if _, ok := calculateMap[bv.EdbInfoId]; !ok {
  52. newCalculateInfoArr = append(newCalculateInfoArr, bv)
  53. calculateArr = append(calculateArr, bv.EdbInfoId)
  54. }
  55. calculateMap[bv.EdbInfoId] = bv
  56. }
  57. sort.Ints(calculateArr)
  58. // 刷新相关基础指标
  59. for _, bv := range newBaseEdbInfoArr {
  60. err, errmsg = refreshBaseEdbInfo(bv)
  61. if err != nil {
  62. return
  63. }
  64. }
  65. // 刷新相关计算指标
  66. for _, v := range calculateArr {
  67. edbInfo := calculateMap[v]
  68. if edbInfo == nil || edbInfo.EdbInfoId <= 0 {
  69. return err
  70. }
  71. err, errmsg = refreshCalculateEdbInfo(edbInfo)
  72. if err != nil {
  73. return
  74. }
  75. }
  76. return err
  77. }
  78. // BatchChartInfoRefresh 图表批量刷新
  79. func BatchChartInfoRefresh(chartInfoList []*data_manage.ChartInfo) (err error) {
  80. if len(chartInfoList) <= 0 {
  81. return
  82. }
  83. chartInfoIdSlice := make([]string, 0)
  84. for _, chartInfo := range chartInfoList {
  85. chartInfoIdSlice = append(chartInfoIdSlice, strconv.Itoa(chartInfo.ChartInfoId))
  86. }
  87. var errmsg string
  88. defer func() {
  89. if err != nil {
  90. go alarm_msg.SendAlarmMsg("ChartInfoRefresh:"+errmsg, 3)
  91. //go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "ChartInfoRefresh:"+errmsg, utils.EmailSendToUsers)
  92. fmt.Println("ChartInfoRefresh Err:" + errmsg)
  93. }
  94. }()
  95. baseEdbInfoArr, calculateInfoArr, err := data_manage.GetChartInfoRefreshDataByChartInfoIdSlice(chartInfoIdSlice)
  96. if err != nil {
  97. errmsg = "获取需要刷新的指标失败:Err:" + err.Error()
  98. return
  99. }
  100. //基础指标去重
  101. newBaseEdbInfoArr := make([]*data_manage.EdbInfo, 0)
  102. baseMap := make(map[int]*data_manage.EdbInfo)
  103. for _, bv := range baseEdbInfoArr {
  104. fmt.Println(bv.UniqueCode)
  105. if _, ok := baseMap[bv.EdbInfoId]; !ok {
  106. newBaseEdbInfoArr = append(newBaseEdbInfoArr, bv)
  107. }
  108. baseMap[bv.EdbInfoId] = bv
  109. }
  110. fmt.Println("calculateInfoArr:", len(calculateInfoArr))
  111. //计算指标去重
  112. newCalculateInfoArr := make([]*data_manage.EdbInfo, 0)
  113. calculateMap := make(map[int]*data_manage.EdbInfo)
  114. var calculateArr []int
  115. for _, bv := range calculateInfoArr {
  116. if _, ok := calculateMap[bv.EdbInfoId]; !ok {
  117. newCalculateInfoArr = append(newCalculateInfoArr, bv)
  118. calculateArr = append(calculateArr, bv.EdbInfoId)
  119. }
  120. calculateMap[bv.EdbInfoId] = bv
  121. }
  122. sort.Ints(calculateArr)
  123. // 刷新相关基础指标
  124. for _, bv := range newBaseEdbInfoArr {
  125. err, errmsg = refreshBaseEdbInfo(bv)
  126. if err != nil {
  127. return
  128. }
  129. }
  130. // 刷新相关计算指标
  131. for _, v := range calculateArr {
  132. edbInfo := calculateMap[v]
  133. if edbInfo == nil || edbInfo.EdbInfoId <= 0 {
  134. return err
  135. }
  136. err, errmsg = refreshCalculateEdbInfo(edbInfo)
  137. if err != nil {
  138. return
  139. }
  140. }
  141. return err
  142. }
  143. // refreshBaseEdbInfo 刷新基础指标
  144. func refreshBaseEdbInfo(bv *data_manage.EdbInfo) (err error, errMsg string) {
  145. source := bv.Source
  146. subSource := bv.SubSource
  147. edbInfoId := bv.EdbInfoId
  148. edbCode := bv.EdbCode
  149. //startDate := bv.StartDate
  150. frequency := bv.Frequency
  151. if bv.StartDate == "0000-00-00" {
  152. return
  153. }
  154. sTime, err := time.Parse(utils.FormatDate, bv.EndDate)
  155. if err != nil {
  156. return
  157. }
  158. var limitDay int
  159. startDate := ""
  160. switch frequency {
  161. case "日度":
  162. limitDay = utils.DATA_START_REFRESH_LIMIT
  163. case "周度":
  164. limitDay = utils.DATA_START_REFRESH_LIMIT * 7
  165. case "月度":
  166. limitDay = utils.DATA_START_REFRESH_LIMIT * 30
  167. case "季度":
  168. limitDay = utils.DATA_START_REFRESH_LIMIT * 90
  169. case "年度":
  170. limitDay = utils.DATA_START_REFRESH_LIMIT * 365
  171. default:
  172. limitDay = utils.DATA_START_REFRESH_LIMIT
  173. }
  174. startDate = sTime.AddDate(0, 0, -limitDay).Format(utils.FormatDate)
  175. fmt.Println("source:", source)
  176. respItem, err := RefreshEdbData(edbInfoId, source, subSource, edbCode, startDate)
  177. if err != nil {
  178. errMsg = errors.New("RefreshEdbData Err:" + err.Error()).Error()
  179. return
  180. }
  181. if respItem.Ret != 200 {
  182. errMsg = errors.New(respItem.ErrMsg + ";EdbCode:" + edbCode).Error()
  183. return
  184. }
  185. maxAndMinItem, err := data_manage.GetEdbInfoMaxAndMinInfo(source, subSource, edbCode)
  186. if err != nil {
  187. return
  188. }
  189. if maxAndMinItem != nil {
  190. err = data_manage.ModifyEdbInfoMaxAndMinInfo(edbInfoId, maxAndMinItem)
  191. if err != nil {
  192. return
  193. }
  194. }
  195. return
  196. }
  197. // refreshCalculateEdbInfo 刷新计算指标
  198. func refreshCalculateEdbInfo(edbInfo *data_manage.EdbInfo) (err error, errMsg string) {
  199. startDate := edbInfo.StartDate
  200. source := edbInfo.Source
  201. if source == utils.DATA_SOURCE_CALCULATE {
  202. startDate = edbInfo.StartDate
  203. sTime, tmpErr := time.Parse(utils.FormatDate, edbInfo.EndDate)
  204. if tmpErr != nil {
  205. err = tmpErr
  206. return
  207. }
  208. startDate = sTime.Format(utils.FormatDate)
  209. }
  210. result, err := RefreshEdbCalculateData(edbInfo.EdbInfoId, edbInfo.EdbCode, startDate)
  211. if err != nil {
  212. fmt.Println(edbInfo.EdbInfoId, "RefreshEdbCalculateData err", time.Now())
  213. errMsg = "RefreshEdbCalculateData Err:" + err.Error()
  214. return
  215. }
  216. if result.Ret != 200 {
  217. fmt.Println(edbInfo.EdbInfoId, "RefreshEdbCalculateData err;msg:", result.Msg, ";errMsg:", result.ErrMsg)
  218. errMsg = fmt.Sprint(edbInfo.EdbInfoId, "RefreshEdbCalculateData err;msg:", result.Msg, ";errMsg:", result.ErrMsg)
  219. err = errors.New("刷新失败")
  220. return
  221. }
  222. return
  223. }
  224. type ChartInfoReq struct {
  225. ChartInfoId int `description:"图表id,新增时传0"`
  226. }
  227. // DeleteChartInfoDataRedis 清除图表缓存
  228. func DeleteChartInfoDataRedis(bodyByte []byte) (err error) {
  229. var req ChartInfoReq
  230. err = json.Unmarshal(bodyByte, &req)
  231. if err != nil {
  232. return
  233. }
  234. if req.ChartInfoId > 0 {
  235. err = utils.Rc.Delete(GetChartInfoDataKey(req.ChartInfoId))
  236. }
  237. return
  238. }
  239. // DeleteChartClassifyRedis 清除图表分类缓存
  240. func DeleteChartClassifyRedis(bodyByte []byte) (err error) {
  241. err = utils.Rc.Delete(utils.CACHE_CHART_CLASSIFY)
  242. return
  243. }
  244. // GetChartInfoDataKey 获取图表缓存的key
  245. func GetChartInfoDataKey(chartInfoId int) string {
  246. key := fmt.Sprint(utils.CACHE_CHART_INFO_DATA, chartInfoId)
  247. return key
  248. }
  249. // CheckOpChartPermission 判断图表操作权限
  250. func CheckOpChartPermission(sysUser *system.Admin, createUserId int, haveOperaAuth bool) (ok bool) {
  251. // 没有数据权限,那么直接返回
  252. if !haveOperaAuth {
  253. return
  254. }
  255. if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
  256. ok = true
  257. }
  258. // 如果图表创建人与当前操作人相同的话,那么就是允许操作
  259. if ok == false && createUserId == sysUser.AdminId {
  260. ok = true
  261. }
  262. // 如果图表权限id 是 1 ,那么允许编辑
  263. if ok == false && sysUser.ChartPermission == 1 {
  264. ok = true
  265. }
  266. return
  267. }
  268. // GetChartEdbData 获取图表的指标数据
  269. func GetChartEdbData(chartInfoId, chartType int, calendar, startDate, endDate string, mappingList []*data_manage.ChartEdbInfoMapping, extraConfigStr string, seasonExtraConfig string) (edbList []*data_manage.ChartEdbInfoMapping, xEdbIdValue []int, yDataList []data_manage.YData, dataResp interface{}, err error, errMsg string) {
  270. edbList = make([]*data_manage.ChartEdbInfoMapping, 0)
  271. xEdbIdValue = make([]int, 0)
  272. yDataList = make([]data_manage.YData, 0)
  273. var extraConfig interface{}
  274. switch chartType {
  275. case 6:
  276. var tmpConfig data_manage.ChartTimeCombineExtraConf
  277. if extraConfigStr != `` {
  278. err = json.Unmarshal([]byte(extraConfigStr), &tmpConfig)
  279. if err != nil {
  280. errMsg = "雷达图配置异常"
  281. err = errors.New(errMsg)
  282. return
  283. }
  284. }
  285. extraConfig = tmpConfig
  286. case 7: // 柱形图
  287. var barConfig data_manage.BarChartInfoReq
  288. if extraConfigStr == `` {
  289. errMsg = "柱方图未配置"
  290. err = errors.New(errMsg)
  291. return
  292. }
  293. err = json.Unmarshal([]byte(extraConfigStr), &barConfig)
  294. if err != nil {
  295. errMsg = "柱方图配置异常"
  296. err = errors.New(errMsg)
  297. return
  298. }
  299. extraConfig = barConfig
  300. case 10: // 截面散点图
  301. var tmpExtraConfig data_manage.SectionScatterReq
  302. if extraConfigStr == `` {
  303. errMsg = "截面散点图未配置"
  304. err = errors.New(errMsg)
  305. return
  306. }
  307. err = json.Unmarshal([]byte(extraConfigStr), &tmpExtraConfig)
  308. if err != nil {
  309. errMsg = "截面散点配置异常"
  310. err = errors.New(errMsg)
  311. return
  312. }
  313. extraConfig = tmpExtraConfig
  314. case utils.CHART_TYPE_RADAR:
  315. var barConfig data_manage.RadarChartInfoReq
  316. if extraConfigStr == `` {
  317. errMsg = "雷达图未配置"
  318. err = errors.New(errMsg)
  319. return
  320. }
  321. err = json.Unmarshal([]byte(extraConfigStr), &barConfig)
  322. if err != nil {
  323. errMsg = "雷达图配置异常"
  324. err = errors.New(errMsg)
  325. return
  326. }
  327. extraConfig = barConfig
  328. case utils.CHART_TYPE_SECTION_COMBINE:
  329. // 预览和详情都走这个接口
  330. var sectionExtraConfig data_manage.ChartSectionAllExtraConf
  331. if extraConfigStr == `` {
  332. errMsg = "截面组合图未配置"
  333. err = errors.New(errMsg)
  334. return
  335. }
  336. if chartInfoId > 0 {
  337. var sectionExtraConfigTmp data_manage.ChartSectionExtraConf
  338. err = json.Unmarshal([]byte(extraConfigStr), &sectionExtraConfigTmp)
  339. if err != nil {
  340. errMsg = "截面组合图配置异常"
  341. err = errors.New(errMsg)
  342. return
  343. }
  344. sectionExtraConfig.XDataList = sectionExtraConfigTmp.XDataList
  345. sectionExtraConfig.BaseChartSeriesName = sectionExtraConfigTmp.BaseChartSeriesName
  346. sectionExtraConfig.UnitList = sectionExtraConfigTmp.UnitList
  347. sectionExtraConfig.DateConfList = sectionExtraConfigTmp.DateConfList
  348. sectionExtraConfig.IsHeap = sectionExtraConfigTmp.IsHeap
  349. sectionExtraConfig.SortType = sectionExtraConfigTmp.SortType
  350. // 查询所有的seriesEdb
  351. seriesEdbList, e := data_manage.GetChartSeriesEdbByChartInfoId(chartInfoId)
  352. if e != nil {
  353. errMsg = "查询seriesEdb失败"
  354. err = errors.New(errMsg + e.Error())
  355. return
  356. }
  357. // todo 是否有必要返回单位信息
  358. // 组装成map
  359. seriesEdbMap := make(map[int][]*data_manage.ChartSectionSeriesEdbConf)
  360. for _, v := range seriesEdbList {
  361. var dateConf *data_manage.ChartSectionSeriesDateConfItem
  362. if v.DateConf != "" {
  363. err = json.Unmarshal([]byte(v.DateConf), &dateConf)
  364. if err != nil {
  365. errMsg = "截面组合图配置异常"
  366. err = errors.New(errMsg + e.Error())
  367. return
  368. }
  369. }
  370. tmp := &data_manage.ChartSectionSeriesEdbConf{
  371. ChartSeriesEdbMappingId: v.ChartSeriesEdbMappingId,
  372. ChartSeriesId: v.ChartSeriesId,
  373. //ChartInfoId: v.ChartInfoId,
  374. EdbInfoId: v.EdbInfoId,
  375. DateConf: dateConf,
  376. EdbName: "",
  377. EdbNameEn: "",
  378. Unit: "",
  379. UnitEn: "",
  380. DateConfName: v.DateConfName,
  381. DateConfType: v.DateConfType,
  382. }
  383. seriesEdbMap[v.ChartSeriesId] = append(seriesEdbMap[v.ChartSeriesId], tmp)
  384. }
  385. //查询series
  386. seriesListTmp, e := data_manage.GetChartSeriesByChartInfoId(chartInfoId)
  387. if e != nil {
  388. errMsg = "查询series失败"
  389. err = errors.New(errMsg + e.Error())
  390. return
  391. }
  392. seriesList := make([]*data_manage.ChartSectionSeriesItem, 0)
  393. for _, v := range seriesListTmp {
  394. tmpSeries := &data_manage.ChartSectionSeriesItem{
  395. ChartSeriesId: v.ChartSeriesId,
  396. SeriesName: v.SeriesName,
  397. SeriesNameEn: v.SeriesNameEn,
  398. ChartStyle: v.ChartStyle,
  399. ChartColor: v.ChartColor,
  400. ChartWidth: v.ChartWidth,
  401. IsPoint: v.IsPoint,
  402. IsNumber: v.IsNumber,
  403. IsAxis: v.IsAxis,
  404. MaxData: v.MaxData,
  405. MinData: v.MinData,
  406. //IsOrder: false,
  407. EdbInfoList: nil,
  408. DataList: nil,
  409. }
  410. edbInfoList, ok := seriesEdbMap[v.ChartSeriesId]
  411. if ok {
  412. tmpSeries.EdbInfoList = edbInfoList
  413. }
  414. seriesList = append(seriesList, tmpSeries)
  415. }
  416. sectionExtraConfig.SeriesList = seriesList
  417. } else {
  418. err = json.Unmarshal([]byte(extraConfigStr), &sectionExtraConfig)
  419. if err != nil {
  420. errMsg = "截面组合图配置异常"
  421. err = errors.New(errMsg)
  422. return
  423. }
  424. }
  425. //校验引用日期名称是否重复
  426. dateNameMap := make(map[string]int)
  427. dateNameEnMap := make(map[string]int)
  428. for _, v := range sectionExtraConfig.DateConfList {
  429. if _, ok := dateNameMap[v.DateConfName]; ok {
  430. errMsg = "截面组合图引用日期名称设置重复"
  431. err = errors.New(errMsg + v.DateConfName)
  432. return
  433. }
  434. if _, ok := dateNameEnMap[v.DateConfNameEn]; ok {
  435. errMsg = "截面组合图引用日期名称设置重复"
  436. err = errors.New(errMsg + v.DateConfNameEn)
  437. return
  438. }
  439. if v.DateConfName != "" {
  440. dateNameMap[v.DateConfName] = 1
  441. }
  442. if v.DateConfNameEn != "" {
  443. dateNameEnMap[v.DateConfNameEn] = 1
  444. }
  445. }
  446. //检查系列名称是否重复
  447. seriesNameMap := make(map[string]int)
  448. seriesNameEnMap := make(map[string]int)
  449. for _, v := range sectionExtraConfig.SeriesList {
  450. if _, ok := seriesNameMap[v.SeriesName]; ok {
  451. errMsg = "截面组合图系列名称设置重复"
  452. err = errors.New(errMsg + v.SeriesName)
  453. return
  454. }
  455. if _, ok := seriesNameEnMap[v.SeriesNameEn]; ok {
  456. errMsg = "截面组合图系列名称设置重复"
  457. err = errors.New(errMsg + v.SeriesNameEn)
  458. return
  459. }
  460. if v.SeriesName != "" {
  461. seriesNameMap[v.SeriesName] = 1
  462. }
  463. if v.SeriesNameEn != "" {
  464. seriesNameEnMap[v.SeriesNameEn] = 1
  465. }
  466. }
  467. // 检查基准系列是否设置
  468. if sectionExtraConfig.BaseChartSeriesName == "" {
  469. errMsg = "截面组合图基准系列名称未设置"
  470. err = errors.New(errMsg)
  471. return
  472. }
  473. //todo 如果是详情接口,应该要从其他表里查询配置
  474. extraConfig = sectionExtraConfig
  475. default:
  476. xEdbIdValue = make([]int, 0)
  477. yDataList = make([]data_manage.YData, 0)
  478. }
  479. // 指标对应的所有数据
  480. edbDataListMap, edbList, err := getEdbDataMapList(chartInfoId, chartType, calendar, startDate, endDate, mappingList, seasonExtraConfig)
  481. if err != nil {
  482. return
  483. }
  484. // 特殊图形数据处理
  485. switch chartType {
  486. case 6: //时序组合图
  487. //判断是否堆积
  488. timeConf := extraConfig.(data_manage.ChartTimeCombineExtraConf)
  489. if extraConfigStr == "" { //历史数据,默认开启堆积
  490. timeConf = data_manage.ChartTimeCombineExtraConf{
  491. IsHeap: 1,
  492. }
  493. }
  494. dataResp = data_manage.ChartTimeCombineDataResp{IsHeap: timeConf.IsHeap}
  495. case 2: // 季节性图
  496. if seasonExtraConfig != "" {
  497. // 季节性图计算不管图上数据时间,拿所有数据
  498. _, tempEdbList, e := getEdbDataMapListForSeason(chartInfoId, chartType, calendar, "1990-01-01", "", mappingList, seasonExtraConfig)
  499. if e != nil {
  500. err = e
  501. return
  502. }
  503. dataResp, err = SeasonChartData(tempEdbList, seasonExtraConfig)
  504. } else {
  505. // 兼容无配置的老图
  506. dataResp = new(data_manage.SeasonChartResp)
  507. }
  508. case 7: // 柱形图
  509. barChartConf := extraConfig.(data_manage.BarChartInfoReq)
  510. xEdbIdValue, yDataList, err = BarChartData(mappingList, edbDataListMap, barChartConf.DateList, barChartConf.Sort)
  511. for k := range yDataList {
  512. yDataList[k].Unit = barChartConf.Unit
  513. yDataList[k].UnitEn = barChartConf.UnitEn
  514. }
  515. for _, v := range edbList {
  516. // 指标别名
  517. if barChartConf.EdbInfoIdList != nil && len(barChartConf.EdbInfoIdList) > 0 {
  518. for _, reqEdb := range barChartConf.EdbInfoIdList {
  519. if v.EdbInfoId == reqEdb.EdbInfoId {
  520. v.EdbAliasName = reqEdb.Name
  521. }
  522. }
  523. }
  524. }
  525. case 10: // 截面散点图
  526. sectionScatterConf := extraConfig.(data_manage.SectionScatterReq)
  527. xEdbIdValue, dataResp, err = GetSectionScatterChartData(chartInfoId, mappingList, edbDataListMap, sectionScatterConf)
  528. var tmpExtraConfig data_manage.SectionScatterReq
  529. if extraConfigStr == `` {
  530. errMsg = "截面散点图未配置"
  531. err = errors.New(errMsg)
  532. return
  533. }
  534. err = json.Unmarshal([]byte(extraConfigStr), &tmpExtraConfig)
  535. if err != nil {
  536. errMsg = "截面散点配置异常"
  537. err = errors.New(errMsg)
  538. return
  539. }
  540. // 这个数据没有必要返回给前端
  541. for _, v := range edbList {
  542. v.DataList = nil
  543. }
  544. case utils.CHART_TYPE_SECTION_COMBINE: // 截面组合图
  545. sectionConf := extraConfig.(data_manage.ChartSectionAllExtraConf)
  546. var chartInfo *data_manage.ChartInfo
  547. if chartInfoId > 0 {
  548. chartInfo, err = data_manage.GetChartInfoById(chartInfoId)
  549. if err != nil {
  550. errMsg = "获取图表信息失败"
  551. return
  552. }
  553. }
  554. xEdbIdValue, dataResp, err = GetChartSectionCombineData(chartInfo, mappingList, edbDataListMap, sectionConf)
  555. // 这个数据没有必要返回给前端
  556. for _, v := range edbList {
  557. v.DataList = nil
  558. }
  559. case utils.CHART_TYPE_RADAR: //雷达图
  560. radarConf := extraConfig.(data_manage.RadarChartInfoReq)
  561. xEdbIdValue, dataResp, err = RadarChartData(mappingList, edbDataListMap, radarConf)
  562. }
  563. return
  564. }
  565. // GetEdbDataMapList 获取指标最后的基础数据
  566. func GetEdbDataMapList(chartInfoId, chartType int, calendar, startDate, endDate string, mappingList []*data_manage.ChartEdbInfoMapping, seasonExtra string) (edbDataListMap map[int][]*data_manage.EdbDataList, edbList []*data_manage.ChartEdbInfoMapping, err error) {
  567. edbDataListMap, edbList, err = getEdbDataMapList(chartInfoId, chartType, calendar, startDate, endDate, mappingList, seasonExtra)
  568. return
  569. }
  570. // getEdbDataMapList 获取指标最后的基础数据
  571. func getEdbDataMapList(chartInfoId, chartType int, calendar, startDate, endDate string, mappingList []*data_manage.ChartEdbInfoMapping, seasonExtraConfig string) (edbDataListMap map[int][]*data_manage.EdbDataList, edbList []*data_manage.ChartEdbInfoMapping, err error) {
  572. // 指标对应的所有数据
  573. edbDataListMap = make(map[int][]*data_manage.EdbDataList)
  574. for _, v := range mappingList {
  575. //fmt.Println("v:", v.EdbInfoId)
  576. item := new(data_manage.ChartEdbInfoMapping)
  577. item.EdbInfoId = v.EdbInfoId
  578. item.SourceName = v.SourceName
  579. item.Source = v.Source
  580. item.EdbCode = v.EdbCode
  581. item.EdbName = v.EdbName
  582. item.EdbNameEn = v.EdbNameEn
  583. item.Frequency = v.Frequency
  584. item.EdbType = v.EdbType
  585. item.FrequencyEn = GetFrequencyEn(v.Frequency)
  586. if v.Unit != `无` {
  587. item.Unit = v.Unit
  588. }
  589. item.UnitEn = v.UnitEn
  590. item.StartDate = v.StartDate
  591. item.EndDate = v.EndDate
  592. item.ModifyTime = v.ModifyTime
  593. item.EdbInfoCategoryType = v.EdbInfoCategoryType
  594. item.PredictChartColor = v.PredictChartColor
  595. item.ClassifyId = v.ClassifyId
  596. if chartInfoId <= 0 {
  597. item.IsAxis = 1
  598. item.LeadValue = 0
  599. item.LeadUnit = ""
  600. item.ChartEdbMappingId = 0
  601. item.ChartInfoId = 0
  602. item.IsOrder = false
  603. item.EdbInfoType = 1
  604. item.ChartStyle = ""
  605. item.ChartColor = ""
  606. item.ChartWidth = 0
  607. item.ChartScale = 0
  608. item.MaxData = v.MaxValue
  609. item.MinData = v.MinValue
  610. } else {
  611. item.IsAxis = v.IsAxis
  612. item.EdbInfoType = v.EdbInfoType
  613. item.LeadValue = v.LeadValue
  614. item.LeadUnit = v.LeadUnit
  615. item.LeadUnitEn = GetLeadUnitEn(v.LeadUnit)
  616. item.ChartEdbMappingId = v.ChartEdbMappingId
  617. item.ChartInfoId = v.ChartInfoId
  618. item.ChartStyle = v.ChartStyle
  619. item.ChartColor = v.ChartColor
  620. item.ChartWidth = v.ChartWidth
  621. item.ChartScale = v.ChartScale
  622. item.IsOrder = v.IsOrder
  623. item.MaxData = v.MaxData
  624. item.MinData = v.MinData
  625. }
  626. item.LatestValue = v.LatestValue
  627. item.LatestDate = v.LatestDate
  628. item.UniqueCode = v.UniqueCode
  629. item.MoveLatestDate = v.LatestDate
  630. item.EdbAliasName = v.EdbAliasName
  631. item.IsConvert = v.IsConvert
  632. item.ConvertType = v.ConvertType
  633. item.ConvertValue = v.ConvertValue
  634. item.ConvertUnit = v.ConvertUnit
  635. item.ConvertEnUnit = v.ConvertEnUnit
  636. item.IsJoinPermission = v.IsJoinPermission
  637. var startDateReal string
  638. var diffSeconds int64
  639. if chartType == 2 { //季节性图
  640. startDateReal = startDate
  641. if len(mappingList) > 1 {
  642. item.IsAxis = v.IsAxis
  643. }
  644. } else {
  645. if v.EdbInfoType == 0 && v.LeadUnit != "" && v.LeadValue > 0 { //领先指标
  646. var startTimeRealTemp time.Time
  647. startDateParse, _ := time.Parse(utils.FormatDate, startDate)
  648. switch v.LeadUnit {
  649. case "天":
  650. startTimeRealTemp = startDateParse.AddDate(0, 0, -v.LeadValue)
  651. case "月":
  652. startTimeRealTemp = startDateParse.AddDate(0, -v.LeadValue, 0)
  653. case "季":
  654. startTimeRealTemp = startDateParse.AddDate(0, -3*v.LeadValue, 0)
  655. case "周":
  656. startTimeRealTemp = startDateParse.AddDate(0, 0, -7*v.LeadValue)
  657. case "年":
  658. startTimeRealTemp = startDateParse.AddDate(-v.LeadValue, 0, 0)
  659. }
  660. if startTimeRealTemp.Before(startDateParse) {
  661. startDateReal = startTimeRealTemp.Format(utils.FormatDate)
  662. diffSeconds = (int64(startTimeRealTemp.UnixNano()) - int64(startDateParse.UnixNano())) / 1e6
  663. } else {
  664. startDateReal = startDate
  665. diffSeconds = 0
  666. }
  667. // 预测指标的开始日期也要偏移
  668. {
  669. day, tmpErr := utils.GetDaysBetween2Date(utils.FormatDate, startDate, startDateReal)
  670. if tmpErr != nil {
  671. err = tmpErr
  672. return
  673. }
  674. moveLatestDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, item.MoveLatestDate, time.Local)
  675. if tmpErr != nil {
  676. err = tmpErr
  677. return
  678. }
  679. item.MoveLatestDate = moveLatestDateTime.AddDate(0, 0, day).Format(utils.FormatDate)
  680. }
  681. } else {
  682. startDateReal = startDate
  683. }
  684. }
  685. //fmt.Println("line 1011 chart:", v.Source, v.EdbInfoId, startDateReal, endDate)
  686. calendarPreYear := 0
  687. if calendar == "农历" {
  688. newStartDateReal, err := time.Parse(utils.FormatDate, startDateReal)
  689. if err != nil {
  690. fmt.Println("time.Parse:" + err.Error())
  691. }
  692. calendarPreYear = newStartDateReal.Year() - 1
  693. newStartDateReal = newStartDateReal.AddDate(-1, 0, 0)
  694. startDateReal = newStartDateReal.Format(utils.FormatDate)
  695. }
  696. dataList := make([]*data_manage.EdbDataList, 0)
  697. //fmt.Println("chart:", v.Source, v.EdbInfoId, startDateReal, endDate)
  698. //fmt.Println("calendarPreYear:", calendarPreYear)
  699. //var newEdbInfo *data_manage.EdbInfo
  700. switch v.EdbInfoCategoryType {
  701. case 0:
  702. dataList, err = data_manage.GetEdbDataList(v.Source, v.SubSource, v.EdbInfoId, startDateReal, endDate)
  703. case 1:
  704. _, dataList, _, _, err, _ = GetPredictDataListByPredictEdbInfoId(v.EdbInfoId, startDateReal, endDate, true)
  705. default:
  706. err = errors.New(fmt.Sprint("获取失败,指标类型异常", v.EdbInfoCategoryType))
  707. }
  708. if err != nil {
  709. return
  710. }
  711. if v.IsConvert == 1 {
  712. switch v.ConvertType {
  713. case 1:
  714. for i, data := range dataList {
  715. dataList[i].Value = data.Value * v.ConvertValue
  716. }
  717. //item.MaxData = item.MaxData * v.ConvertValue
  718. //item.MinData = item.MinData * v.ConvertValue
  719. case 2:
  720. for i, data := range dataList {
  721. dataList[i].Value = data.Value / v.ConvertValue
  722. }
  723. //item.MaxData = item.MaxData / v.ConvertValue
  724. //item.MinData = item.MinData / v.ConvertValue
  725. case 3:
  726. for i, data := range dataList {
  727. if data.Value <= 0 {
  728. err = errors.New("数据中含有负数或0,无法对数运算")
  729. return
  730. }
  731. dataList[i].Value = math.Log(data.Value) / math.Log(v.ConvertValue)
  732. }
  733. //item.MaxData = math.Log(item.MaxData) / math.Log(v.ConvertValue)
  734. //item.MinData = math.Log(item.MinData) / math.Log(v.ConvertValue)
  735. }
  736. }
  737. edbDataListMap[v.EdbInfoId] = dataList
  738. if diffSeconds != 0 && v.EdbInfoType == 0 {
  739. dataListLen := len(dataList)
  740. for i := 0; i < dataListLen; i++ {
  741. dataList[i].DataTimestamp = dataList[i].DataTimestamp - diffSeconds
  742. }
  743. }
  744. if chartType == 2 && item.IsAxis == 1 {
  745. latestDate, tmpErr := time.Parse(utils.FormatDate, v.LatestDate)
  746. if tmpErr != nil {
  747. //item.DataList = dataList
  748. item.IsNullData = true
  749. edbList = append(edbList, item)
  750. continue
  751. err = errors.New(fmt.Sprint("获取最后实际数据的日期失败,Err:" + tmpErr.Error() + ";LatestDate:" + v.LatestDate))
  752. return
  753. }
  754. if calendar == "农历" {
  755. if len(dataList) <= 0 {
  756. result := new(data_manage.EdbDataResult)
  757. item.DataList = result
  758. } else {
  759. result, tmpErr := data_manage.AddCalculateQuarterV6(dataList)
  760. if tmpErr != nil {
  761. err = errors.New("获取农历数据失败,Err:" + tmpErr.Error())
  762. return
  763. }
  764. quarterDataList, tErr := GetSeasonEdbInfoDataListByXDateNong(result, latestDate, seasonExtraConfig, calendarPreYear)
  765. if tErr != nil {
  766. err = errors.New("获取季节性图表数据失败,Err:" + tErr.Error())
  767. return
  768. }
  769. item.DataList = quarterDataList
  770. }
  771. } else {
  772. quarterDataList, tErr := GetSeasonEdbInfoDataListByXDate(dataList, latestDate, seasonExtraConfig)
  773. if tErr != nil {
  774. err = errors.New("获取季节性图表数据失败,Err:" + tErr.Error())
  775. return
  776. }
  777. item.DataList = quarterDataList
  778. }
  779. } else if chartType == 2 && item.IsAxis == 0 {
  780. // 右轴数据处理
  781. xStartDate := "01-01"
  782. jumpYear := 0
  783. var seasonExtra data_manage.SeasonExtraItem
  784. if seasonExtraConfig != "" {
  785. err = json.Unmarshal([]byte(seasonExtraConfig), &seasonExtra)
  786. if err != nil {
  787. return
  788. }
  789. }
  790. if seasonExtra.XStartDate != "" {
  791. xStartDate = seasonExtra.XStartDate
  792. jumpYear = seasonExtra.JumpYear
  793. }
  794. length := len(dataList)
  795. if length == 0 {
  796. return
  797. }
  798. latestDate, tmpErr := time.Parse(utils.FormatDate, v.LatestDate)
  799. if tmpErr != nil {
  800. //item.DataList = dataList
  801. item.IsNullData = true
  802. edbList = append(edbList, item)
  803. continue
  804. err = errors.New(fmt.Sprint("获取最后实际数据的日期失败,Err:" + tmpErr.Error() + ";LatestDate:" + v.LatestDate))
  805. return
  806. }
  807. var rightAxisDate time.Time
  808. if jumpYear == 1 {
  809. latestDate = latestDate.AddDate(-1, 0, 0)
  810. }
  811. latestDateStr := fmt.Sprintf("%d-%s", latestDate.Year(), xStartDate)
  812. rightAxisDate, err = time.Parse(utils.FormatDate, latestDateStr)
  813. if err != nil {
  814. return
  815. }
  816. nowYear := time.Now().Year()
  817. newDataList := make([]*data_manage.EdbDataList, 0)
  818. for _, v := range dataList {
  819. dataTime, e := time.Parse(utils.FormatDate, v.DataTime)
  820. if e != nil {
  821. err = errors.New("季节性图处理右轴指标数据转换日期失败,Err:" + e.Error())
  822. return
  823. }
  824. dataTimeT, _ := time.Parse(utils.FormatDate, v.DataTime)
  825. year := dataTimeT.Year()
  826. newItemDate := dataTimeT.AddDate(nowYear-year, 0, 0)
  827. v.DataTimestamp = newItemDate.UnixNano() / 1e6
  828. if dataTime.Equal(rightAxisDate) || dataTime.After(rightAxisDate) {
  829. newDataList = append(newDataList, v)
  830. }
  831. }
  832. item.DataList = newDataList
  833. } else if chartType == 7 || chartType == utils.CHART_TYPE_RADAR { //柱方图
  834. //item.DataList = dataList
  835. } else {
  836. item.DataList = dataList
  837. }
  838. edbList = append(edbList, item)
  839. }
  840. return
  841. }
  842. // GetSeasonEdbInfoDataListByXDate 季节性图的指标数据根据横轴展示
  843. func GetSeasonEdbInfoDataListByXDate(dataList []*data_manage.EdbDataList, latestDate time.Time, seasonExtraConfig string) (quarterDataListSort data_manage.QuarterDataList, err error) {
  844. xStartDate := "01-01"
  845. xEndDate := "12-31"
  846. jumpYear := 0
  847. legends := make([]data_manage.SeasonChartLegend, 0)
  848. var seasonExtra data_manage.SeasonExtraItem
  849. if seasonExtraConfig != "" {
  850. err = json.Unmarshal([]byte(seasonExtraConfig), &seasonExtra)
  851. if err != nil {
  852. return
  853. }
  854. }
  855. if seasonExtra.XStartDate != "" {
  856. xStartDate = seasonExtra.XStartDate
  857. xEndDate = seasonExtra.XEndDate
  858. jumpYear = seasonExtra.JumpYear
  859. legends = seasonExtra.ChartLegend
  860. }
  861. length := len(dataList)
  862. if length == 0 {
  863. return
  864. }
  865. legendMap := make(map[string]string, 0)
  866. if len(legends) > 0 {
  867. for _, v := range legends {
  868. legendMap[v.Name] = v.Value
  869. }
  870. }
  871. latestDateStr := latestDate.Format(utils.FormatDate)
  872. //判断横轴的两个时间之间是不是跨年了,如果跨年了,则横轴截止年份比起始年份+1,如果不跨年,截止年份等于起始年份
  873. //根据数据确定最早的年份,和最近年份
  874. //根据横轴的日期,汇总所有的年份
  875. startDate := dataList[0].DataTime
  876. startDateT, tmpErr := time.Parse(utils.FormatDate, startDate)
  877. if tmpErr != nil {
  878. err = tmpErr
  879. return
  880. }
  881. startYear := startDateT.Year()
  882. //获取数据的最新日期
  883. lastDate := dataList[length-1].DataTime
  884. lastDateT, tmpErr := time.Parse(utils.FormatDate, lastDate)
  885. if tmpErr != nil {
  886. err = tmpErr
  887. return
  888. }
  889. endYear := lastDateT.Year()
  890. nowYear := time.Now().Year()
  891. chartLegendMaxYear := 0
  892. dataMap := make(map[string]data_manage.QuarterXDateItem, 0)
  893. quarterDataList := make([]*data_manage.QuarterData, 0)
  894. quarterMap := make(map[string][]*data_manage.EdbDataList, 0)
  895. //整理出日期
  896. idx := 1
  897. chartLegendMap := make(map[string]int, 0)
  898. for currentStartYear := startYear; currentStartYear <= endYear; currentStartYear++ {
  899. startStr := fmt.Sprintf("%d-%s", currentStartYear, xStartDate)
  900. currentEndYear := currentStartYear
  901. if jumpYear == 1 {
  902. currentEndYear = currentStartYear + 1
  903. }
  904. endStr := fmt.Sprintf("%d-%s", currentEndYear, xEndDate)
  905. name := fmt.Sprintf("%s_%s", startStr, endStr)
  906. showName := fmt.Sprintf("%d_%d", currentStartYear, currentEndYear)
  907. startT, tEr := time.Parse(utils.FormatDate, startStr)
  908. if tEr != nil {
  909. err = tEr
  910. return
  911. }
  912. endT, tEr := time.Parse(utils.FormatDate, endStr)
  913. if tEr != nil {
  914. err = tEr
  915. return
  916. }
  917. if lastDateT.Before(startT) {
  918. //如果最新的日期在起始日之前,则跳出循环
  919. break
  920. }
  921. if endT.Year() > nowYear {
  922. //如果最新的日期比真实年份要大,则数据全部按照最大的年份补齐
  923. nowYear = endT.Year()
  924. }
  925. item := data_manage.QuarterXDateItem{
  926. StartDate: startT,
  927. EndDate: endT,
  928. ShowName: showName,
  929. }
  930. chartLegendMaxYear = endT.Year()
  931. dataMap[name] = item
  932. chartLegendMap[name] = idx
  933. idx++
  934. fmt.Println("年份" + showName + "日期" + startStr + " " + endStr)
  935. if lastDateT.Before(endT) {
  936. //如果最新的日期在起始日之前,则跳出循环
  937. break
  938. }
  939. }
  940. lenYear := len(dataMap)
  941. if chartLegendMaxYear > endYear {
  942. chartLegendMaxYear = endYear
  943. }
  944. for k, v := range dataMap {
  945. if i, ok := chartLegendMap[k]; ok {
  946. //v.ChartLegend = strconv.Itoa(endYear - lenYear + i)
  947. v.ChartLegend = strconv.Itoa(chartLegendMaxYear - lenYear + i)
  948. }
  949. dataMap[k] = v
  950. }
  951. for _, v := range dataList {
  952. dataTimeT, _ := time.Parse(utils.FormatDate, v.DataTime)
  953. year := dataTimeT.Year()
  954. newItemDate := dataTimeT.AddDate(nowYear-year, 0, 0)
  955. for k, dateItem := range dataMap {
  956. tmpVal := data_manage.EdbDataList{
  957. EdbDataId: v.EdbDataId,
  958. EdbInfoId: v.EdbInfoId,
  959. DataTime: v.DataTime,
  960. DataTimestamp: v.DataTimestamp,
  961. Value: v.Value,
  962. }
  963. if (dateItem.StartDate.Before(dataTimeT) && dateItem.EndDate.After(dataTimeT)) || dateItem.StartDate == dataTimeT || dateItem.EndDate == dataTimeT {
  964. if jumpYear == 1 {
  965. //计算前一年最大的日期, 只补齐数据到去年
  966. beforeYearMaxDate := fmt.Sprintf("%d-12-31", dateItem.StartDate.Year())
  967. beforeYearMaxDateT, _ := time.Parse(utils.FormatDate, beforeYearMaxDate)
  968. if dataTimeT.Before(beforeYearMaxDateT) || dataTimeT == beforeYearMaxDateT {
  969. newItemDate = dataTimeT.AddDate(nowYear-year-1, 0, 0)
  970. } else {
  971. newItemDate = dataTimeT.AddDate(nowYear-year, 0, 0)
  972. }
  973. } else {
  974. newItemDate = dataTimeT.AddDate(nowYear-year, 0, 0)
  975. }
  976. timestamp := newItemDate.UnixNano() / 1e6
  977. tmpVal.DataTimestamp = timestamp
  978. tmpV := &tmpVal
  979. if findVal, ok := quarterMap[k]; !ok {
  980. findVal = append(findVal, tmpV)
  981. quarterMap[k] = findVal
  982. } else {
  983. findVal = append(findVal, tmpV)
  984. quarterMap[k] = findVal
  985. }
  986. if v.DataTime == latestDateStr {
  987. dateItem.CuttingDataTimestamp = timestamp
  988. dataMap[k] = dateItem
  989. }
  990. //break
  991. }
  992. }
  993. }
  994. for k, v := range dataMap {
  995. itemList := quarterMap[k]
  996. /*if len(itemList) == 0 {
  997. continue
  998. }*/
  999. quarterItem := new(data_manage.QuarterData)
  1000. quarterItem.Years = v.ShowName
  1001. quarterItem.ChartLegend = v.ChartLegend
  1002. if le, ok := legendMap[v.ShowName]; ok {
  1003. if le != strconv.Itoa(v.StartDate.Year()) && le != strconv.Itoa(v.EndDate.Year()) {
  1004. quarterItem.ChartLegend = le
  1005. }
  1006. }
  1007. quarterItem.DataList = itemList
  1008. quarterItem.CuttingDataTimestamp = v.CuttingDataTimestamp
  1009. //如果等于最后的实际日期,那么将切割时间戳记录
  1010. if quarterItem.CuttingDataTimestamp == 0 {
  1011. //如果大于最后的实际日期,那么第一个点就是切割的时间戳
  1012. if latestDate.Before(v.StartDate) && len(itemList) > 0 {
  1013. quarterItem.CuttingDataTimestamp = itemList[0].DataTimestamp - 100
  1014. }
  1015. }
  1016. quarterDataList = append(quarterDataList, quarterItem)
  1017. }
  1018. if len(quarterDataList) > 0 {
  1019. quarterDataListSort = quarterDataList
  1020. sort.Sort(quarterDataListSort)
  1021. }
  1022. return
  1023. }
  1024. // GetSeasonEdbInfoDataListByXDateNong 季节性图的指标数据根据横轴选择农历时展示
  1025. func GetSeasonEdbInfoDataListByXDateNong(result *data_manage.EdbDataResult, latestDate time.Time, seasonExtraConfig string, calendarPreYear int) (quarterDataListSort data_manage.QuarterDataList, err error) {
  1026. xStartDate := "01-01"
  1027. xEndDate := "12-31"
  1028. jumpYear := 0
  1029. legends := make([]data_manage.SeasonChartLegend, 0)
  1030. var seasonExtra data_manage.SeasonExtraItem
  1031. if seasonExtraConfig != "" {
  1032. err = json.Unmarshal([]byte(seasonExtraConfig), &seasonExtra)
  1033. if err != nil {
  1034. return
  1035. }
  1036. }
  1037. if seasonExtra.XStartDate != "" {
  1038. xStartDate = seasonExtra.XStartDate
  1039. xEndDate = seasonExtra.XEndDate
  1040. jumpYear = seasonExtra.JumpYear
  1041. legends = seasonExtra.ChartLegend
  1042. }
  1043. length := len(result.List)
  1044. if length == 0 {
  1045. return
  1046. }
  1047. legendMap := make(map[string]string, 0)
  1048. if len(legends) > 0 {
  1049. for _, v := range legends {
  1050. legendMap[v.Name] = v.Value
  1051. }
  1052. }
  1053. latestDateYear := latestDate.Year()
  1054. //判断横轴的两个时间之间是不是跨年了,如果跨年了,则横轴截止年份比起始年份+1,如果不跨年,截止年份等于起始年份
  1055. //根据数据确定最早的年份,和最近年份
  1056. //根据横轴的日期,汇总所有的年份
  1057. startYear := result.List[0].Year
  1058. /*if jumpYear == 1 {
  1059. if startYear != calendarPreYear {
  1060. startYear = startYear - 1
  1061. }
  1062. }*/
  1063. itemLength := len(result.List[length-1].Items)
  1064. //获取数据的最新日期
  1065. lastDate := result.List[length-1].Items[itemLength-1].DataTime
  1066. maxY := result.List[length-1].Year
  1067. lastDateT, tmpErr := time.Parse(utils.FormatDate, lastDate)
  1068. if tmpErr != nil {
  1069. err = tmpErr
  1070. return
  1071. }
  1072. endYear := lastDateT.Year()
  1073. nowYear := time.Now().Year()
  1074. chartLegendMaxYear := 0
  1075. dataMap := make(map[string]data_manage.QuarterXDateItem, 0)
  1076. quarterDataList := make([]*data_manage.QuarterData, 0)
  1077. resultData := make([]*data_manage.QuarterData, 0)
  1078. quarterMap := make(map[string][]*data_manage.EdbDataList, 0)
  1079. //整理出日期
  1080. var startTmpT, endTmpT time.Time
  1081. idx := 1
  1082. chartLegendMap := make(map[string]int, 0)
  1083. for currentStartYear := startYear; currentStartYear <= endYear; currentStartYear++ {
  1084. startStr := fmt.Sprintf("%d-%s", currentStartYear, xStartDate)
  1085. currentEndYear := currentStartYear
  1086. if jumpYear == 1 {
  1087. currentEndYear = currentStartYear + 1
  1088. }
  1089. endStr := fmt.Sprintf("%d-%s", currentEndYear, xEndDate)
  1090. showName := fmt.Sprintf("%d_%d", currentStartYear, currentEndYear)
  1091. startT, tEr := time.Parse(utils.FormatDate, startStr)
  1092. if tEr != nil {
  1093. err = tEr
  1094. return
  1095. }
  1096. endT, tEr := time.Parse(utils.FormatDate, endStr)
  1097. if tEr != nil {
  1098. err = tEr
  1099. return
  1100. }
  1101. if lastDateT.Before(startT) {
  1102. //如果最新的日期在起始日之前,则跳出循环
  1103. break
  1104. }
  1105. if endT.Year() > nowYear {
  1106. //如果最新的日期比真实年份要大,则数据全部按照最大的年份补齐
  1107. nowYear = endT.Year()
  1108. }
  1109. item := data_manage.QuarterXDateItem{
  1110. StartDate: startT,
  1111. EndDate: endT,
  1112. ShowName: showName,
  1113. }
  1114. chartLegendMaxYear = endT.Year()
  1115. dataMap[showName] = item
  1116. fmt.Println("年份" + showName + "日期" + startStr + " " + endStr)
  1117. startTmpT = startT
  1118. endTmpT = endT
  1119. chartLegendMap[showName] = idx
  1120. idx++
  1121. if lastDateT.Before(endT) {
  1122. //如果最新的日期在起始日之前,则跳出循环
  1123. break
  1124. }
  1125. }
  1126. lenYear := len(dataMap)
  1127. if chartLegendMaxYear > endYear {
  1128. chartLegendMaxYear = endYear
  1129. }
  1130. for k, v := range dataMap {
  1131. if i, ok := chartLegendMap[k]; ok {
  1132. //v.ChartLegend = strconv.Itoa(endYear - lenYear + i)
  1133. v.ChartLegend = strconv.Itoa(chartLegendMaxYear - lenYear + i)
  1134. }
  1135. dataMap[k] = v
  1136. }
  1137. yearDataListMap := make(map[int]*data_manage.EdbDataItems, 0)
  1138. for _, lv := range result.List {
  1139. yearDataListMap[lv.Year] = lv
  1140. }
  1141. //判断哪些点应该落在同一条时间线上
  1142. /*maxY := lastDateT.Year()
  1143. changeFlag := false
  1144. if lastDateT.Month() >= 11 {
  1145. maxY = maxY + 1
  1146. }
  1147. if maxY < nowYear {
  1148. changeFlag = true
  1149. maxY = nowYear
  1150. }*/
  1151. /*endTmp := fmt.Sprintf("%d-%s", maxY, xEndDate)
  1152. endTmpT, _ := time.Parse(utils.FormatDate, endTmp)
  1153. minY := maxY
  1154. if jumpYear == 1 {
  1155. minY = maxY - 1
  1156. }
  1157. startTmp := fmt.Sprintf("%d-%s", minY, xStartDate)
  1158. startTmpT, _ := time.Parse(utils.FormatDate, startTmp)*/
  1159. fmt.Println("横轴截取日" + startTmpT.Format(utils.FormatDate) + " " + endTmpT.Format(utils.FormatDate))
  1160. fmt.Printf("lastDateT.Year() 为%d \n", lastDateT.Year())
  1161. fmt.Printf("maxY 为%d \n", maxY)
  1162. for name, dateItem := range dataMap {
  1163. tY := dateItem.EndDate.Year()
  1164. if lastDateT.Month() >= 11 {
  1165. if maxY > endTmpT.Year() {
  1166. tY = tY + 1
  1167. }
  1168. }
  1169. lv, ok1 := yearDataListMap[tY]
  1170. fmt.Printf("name %s yearDataListMap[%d]\n", name, tY)
  1171. if !ok1 {
  1172. continue
  1173. }
  1174. for _, item := range lv.Items {
  1175. tmpVal := data_manage.EdbDataList{
  1176. EdbDataId: item.EdbDataId,
  1177. EdbInfoId: item.EdbInfoId,
  1178. DataTime: item.DataTime,
  1179. DataTimestamp: item.DataTimestamp,
  1180. Value: item.Value,
  1181. }
  1182. dataTimeT, _ := time.Parse(utils.FormatDate, item.DataTime)
  1183. year := dataTimeT.Year()
  1184. newItemDate := dataTimeT.AddDate(nowYear-year, 0, 0)
  1185. timestamp := newItemDate.UnixNano() / 1e6
  1186. tmpVal.DataTimestamp = timestamp
  1187. if (startTmpT.Before(dataTimeT) && endTmpT.After(dataTimeT)) || startTmpT == dataTimeT || endTmpT == dataTimeT {
  1188. tmpV := &tmpVal
  1189. if findVal, ok := quarterMap[name]; !ok {
  1190. findVal = append(findVal, tmpV)
  1191. quarterMap[name] = findVal
  1192. } else {
  1193. findVal = append(findVal, tmpV)
  1194. quarterMap[name] = findVal
  1195. }
  1196. if lv.Year >= latestDateYear {
  1197. // 切割的日期时间字符串
  1198. cuttingDataTimeStr := latestDate.AddDate(0, 0, lv.BetweenDay).Format(utils.FormatDate)
  1199. if item.DataTime == cuttingDataTimeStr {
  1200. dateItem.CuttingDataTimestamp = tmpVal.DataTimestamp
  1201. dataMap[name] = dateItem
  1202. }
  1203. }
  1204. }
  1205. }
  1206. }
  1207. for k, v := range dataMap {
  1208. itemList := quarterMap[k]
  1209. /*if len(itemList) == 0 {
  1210. continue
  1211. }*/
  1212. quarterItem := new(data_manage.QuarterData)
  1213. quarterItem.Years = v.ShowName
  1214. quarterItem.ChartLegend = v.ChartLegend
  1215. if le, ok := legendMap[v.ShowName]; ok {
  1216. if le != strconv.Itoa(v.StartDate.Year()) && le != strconv.Itoa(v.EndDate.Year()) {
  1217. quarterItem.ChartLegend = le
  1218. }
  1219. }
  1220. quarterItem.DataList = itemList
  1221. quarterItem.CuttingDataTimestamp = v.CuttingDataTimestamp
  1222. //如果等于最后的实际日期,那么将切割时间戳记录
  1223. if quarterItem.CuttingDataTimestamp == 0 {
  1224. //如果大于最后的实际日期,那么第一个点就是切割的时间戳
  1225. if latestDate.Before(v.StartDate) && len(itemList) > 0 {
  1226. quarterItem.CuttingDataTimestamp = itemList[0].DataTimestamp - 100
  1227. }
  1228. }
  1229. quarterDataList = append(quarterDataList, quarterItem)
  1230. }
  1231. if result.List[0].Year != calendarPreYear {
  1232. itemList := make([]*data_manage.EdbDataList, 0)
  1233. items := new(data_manage.QuarterData)
  1234. //items.Year = calendarPreYear
  1235. items.DataList = itemList
  1236. newResult := make([]*data_manage.QuarterData, 0)
  1237. newResult = append(newResult, items)
  1238. newResult = append(newResult, quarterDataList...)
  1239. resultData = newResult
  1240. } else {
  1241. resultData = quarterDataList
  1242. }
  1243. if len(quarterDataList) > 0 {
  1244. quarterDataListSort = resultData
  1245. sort.Sort(quarterDataListSort)
  1246. }
  1247. return
  1248. }
  1249. // BarChartData 柱方图的数据处理
  1250. func BarChartData(mappingList []*data_manage.ChartEdbInfoMapping, edbDataListMap map[int][]*data_manage.EdbDataList, barChartInfoDateList []data_manage.BarChartInfoDateReq, barChartInfoSort data_manage.BarChartInfoSortReq) (edbIdList []int, yDataList []data_manage.YData, err error) {
  1251. // 指标数据数组(10086:{"2022-12-02":100.01,"2022-12-01":102.3})
  1252. edbDataMap := make(map[int]map[string]float64)
  1253. for edbInfoId, edbDataList := range edbDataListMap {
  1254. edbDateData := make(map[string]float64)
  1255. for _, edbData := range edbDataList {
  1256. edbDateData[edbData.DataTime] = edbData.Value
  1257. }
  1258. edbDataMap[edbInfoId] = edbDateData
  1259. }
  1260. // edbIdList 指标展示顺序;x轴的指标顺序
  1261. edbIdList = make([]int, 0)
  1262. //Sort int `description:"排序类型,0:默认,1:升序,2:降序"`
  1263. dateData := make(map[int]float64)
  1264. if barChartInfoSort.Sort == 0 {
  1265. for _, v := range mappingList {
  1266. edbIdList = append(edbIdList, v.EdbInfoId)
  1267. }
  1268. } else {
  1269. lenBarChartInfoDateList := len(barChartInfoDateList)
  1270. if barChartInfoSort.DateIndex >= lenBarChartInfoDateList {
  1271. err = errors.New("排序日期异常")
  1272. return
  1273. }
  1274. notDataEdbIdList := make([]int, 0) //没有数据的指标id
  1275. // 日期配置
  1276. barChartInfoDate := barChartInfoDateList[barChartInfoSort.DateIndex]
  1277. for edbInfoId, dataList := range edbDataListMap {
  1278. if len(dataList) <= 0 {
  1279. // 没有数据的指标id
  1280. notDataEdbIdList = append(notDataEdbIdList, edbInfoId)
  1281. continue
  1282. }
  1283. findDate := barChartInfoDate.Date
  1284. switch barChartInfoDate.Type {
  1285. case 1: //最新值
  1286. findDate = dataList[len(dataList)-1].DataTime
  1287. case 2: //近期几天
  1288. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[len(dataList)-1].DataTime, time.Local)
  1289. if tmpErr != nil {
  1290. err = tmpErr
  1291. return
  1292. }
  1293. findDateTime = findDateTime.AddDate(0, 0, -barChartInfoDate.Value)
  1294. lenData := len(dataList) - 1
  1295. for i := lenData; i >= 0; i-- {
  1296. currDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[i].DataTime, time.Local)
  1297. if tmpErr != nil {
  1298. err = tmpErr
  1299. return
  1300. }
  1301. if currDateTime.Equal(findDateTime) || currDateTime.Before(findDateTime) {
  1302. findDate = dataList[i].DataTime
  1303. break
  1304. }
  1305. }
  1306. case 3: // 固定日期
  1307. //最早的日期
  1308. minDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  1309. if tmpErr != nil {
  1310. err = tmpErr
  1311. return
  1312. }
  1313. //寻找固定日期的数据
  1314. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, barChartInfoDate.Date, time.Local)
  1315. if tmpErr != nil {
  1316. err = tmpErr
  1317. return
  1318. }
  1319. for tmpDateTime := findDateTime; tmpDateTime.After(minDateTime) || tmpDateTime.Equal(minDateTime); tmpDateTime = tmpDateTime.AddDate(0, 0, -1) {
  1320. tmpDate := tmpDateTime.Format(utils.FormatDate)
  1321. if _, ok := edbDataMap[edbInfoId][tmpDate]; ok { //如果能找到数据,那么就返回
  1322. findDate = tmpDate
  1323. break
  1324. }
  1325. }
  1326. default:
  1327. err = errors.New(fmt.Sprint("日期类型异常,Type:", barChartInfoDate.Type))
  1328. return
  1329. }
  1330. if tmpValue, ok := edbDataMap[edbInfoId][findDate]; ok {
  1331. dateData[edbInfoId] = tmpValue
  1332. } else {
  1333. // 没有数据的指标id
  1334. notDataEdbIdList = append(notDataEdbIdList, edbInfoId)
  1335. }
  1336. }
  1337. //Sort int `description:"排序类型,0:默认,1:升序,2:降序"`
  1338. // 排序
  1339. dateDataSort := utils.NewMapSorter(dateData)
  1340. sort.Sort(dateDataSort)
  1341. if barChartInfoSort.Sort == 1 {
  1342. // 先将没有数据的指标id放在最前面
  1343. if len(notDataEdbIdList) > 0 {
  1344. edbIdList = append(edbIdList, notDataEdbIdList...)
  1345. }
  1346. for _, v := range dateDataSort {
  1347. edbIdList = append(edbIdList, v.Key)
  1348. }
  1349. } else {
  1350. for i := len(dateDataSort) - 1; i >= 0; i-- {
  1351. edbIdList = append(edbIdList, dateDataSort[i].Key)
  1352. }
  1353. // 再将没有数据的指标id放在最后面
  1354. if len(notDataEdbIdList) > 0 {
  1355. edbIdList = append(edbIdList, notDataEdbIdList...)
  1356. }
  1357. }
  1358. }
  1359. yDataList = make([]data_manage.YData, 0) //y轴的数据列表
  1360. for _, barChartInfoDate := range barChartInfoDateList {
  1361. var maxDate time.Time
  1362. findDataList := make([]float64, 0) // 当前日期的数据值
  1363. for _, edbInfoId := range edbIdList {
  1364. findDate := barChartInfoDate.Date //需要的日期值
  1365. dataList := edbDataListMap[edbInfoId] //指标的所有数据值
  1366. if len(dataList) <= 0 {
  1367. // 没有数据的指标id
  1368. findDataList = append(findDataList, 0)
  1369. continue
  1370. }
  1371. switch barChartInfoDate.Type {
  1372. case 1: //最新值
  1373. dataList := edbDataListMap[edbInfoId]
  1374. findDate = dataList[len(dataList)-1].DataTime
  1375. case 2: //近期几天
  1376. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[len(dataList)-1].DataTime, time.Local)
  1377. if tmpErr != nil {
  1378. err = tmpErr
  1379. return
  1380. }
  1381. findDateTime = findDateTime.AddDate(0, 0, -barChartInfoDate.Value)
  1382. lenData := len(dataList) - 1
  1383. for i := lenData; i >= 0; i-- {
  1384. currDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[i].DataTime, time.Local)
  1385. if tmpErr != nil {
  1386. err = tmpErr
  1387. return
  1388. }
  1389. if currDateTime.Equal(findDateTime) || currDateTime.Before(findDateTime) {
  1390. findDate = dataList[i].DataTime
  1391. break
  1392. }
  1393. }
  1394. case 3: // 固定日期
  1395. //最早的日期
  1396. minDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  1397. if tmpErr != nil {
  1398. err = tmpErr
  1399. return
  1400. }
  1401. //寻找固定日期的数据
  1402. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, barChartInfoDate.Date, time.Local)
  1403. if tmpErr != nil {
  1404. err = tmpErr
  1405. return
  1406. }
  1407. for tmpDateTime := findDateTime; tmpDateTime.After(minDateTime) || tmpDateTime.Equal(minDateTime); tmpDateTime = tmpDateTime.AddDate(0, 0, -1) {
  1408. tmpDate := tmpDateTime.Format(utils.FormatDate)
  1409. if _, ok := edbDataMap[edbInfoId][tmpDate]; ok { //如果能找到数据,那么就返回
  1410. findDate = tmpDate
  1411. break
  1412. }
  1413. }
  1414. default:
  1415. err = errors.New(fmt.Sprint("日期类型异常,Type:", barChartInfoDate.Type))
  1416. return
  1417. }
  1418. findDateTime, _ := time.ParseInLocation(utils.FormatDate, findDate, time.Local)
  1419. if maxDate.IsZero() {
  1420. maxDate = findDateTime
  1421. } else {
  1422. if findDateTime.After(maxDate) {
  1423. maxDate = findDateTime
  1424. }
  1425. }
  1426. if tmpValue, ok := edbDataMap[edbInfoId][findDate]; ok {
  1427. tmpValue, _ = decimal.NewFromFloat(tmpValue).Round(4).Float64()
  1428. findDataList = append(findDataList, tmpValue)
  1429. } else {
  1430. findDataList = append(findDataList, 0)
  1431. }
  1432. }
  1433. yDate := "0000-00-00"
  1434. if !maxDate.IsZero() {
  1435. yDate = maxDate.Format(utils.FormatDate)
  1436. }
  1437. yDataList = append(yDataList, data_manage.YData{
  1438. Date: yDate,
  1439. Value: findDataList,
  1440. Color: barChartInfoDate.Color,
  1441. Name: barChartInfoDate.Name,
  1442. })
  1443. }
  1444. return
  1445. }
  1446. // ChartInfoRefreshV2 图表刷新
  1447. // @author Roc
  1448. // @datetime 2022-09-16 10:15:38
  1449. // @description 将原来自己写的一套获取所有关联指标,然后刷新指标逻辑 改成 只获取使用的指标id,然后遍历去调用“指标刷新服务”
  1450. func ChartInfoRefreshV2(chartInfoId int) (err error, isAsync bool) {
  1451. var errmsg string
  1452. defer func() {
  1453. if err != nil {
  1454. go alarm_msg.SendAlarmMsg("ChartInfoRefresh:"+errmsg, 3)
  1455. //go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "ChartInfoRefresh:"+errmsg, utils.EmailSendToUsers)
  1456. fmt.Println("ChartInfoRefresh Err:" + errmsg)
  1457. }
  1458. }()
  1459. edbMappingList, err := data_manage.GetChartEdbMappingList(chartInfoId)
  1460. if err != nil {
  1461. errmsg = "获取需要刷新的指标失败:Err:" + err.Error()
  1462. return
  1463. }
  1464. edbIdList := make([]int, 0)
  1465. for _, v := range edbMappingList {
  1466. edbIdList = append(edbIdList, v.EdbInfoId)
  1467. }
  1468. // 批量刷新
  1469. err, isAsync = EdbInfoRefreshAllFromBaseV3(edbIdList, false, false, false)
  1470. if err != nil {
  1471. return
  1472. }
  1473. return
  1474. }
  1475. // BatchChartInfoRefreshV2 图表批量刷新
  1476. // @author Roc
  1477. // @datetime 2022-09-16 10:15:38
  1478. // @description 将原来自己写的一套获取所有关联指标,然后刷新指标逻辑 改成 只获取使用的指标id,然后遍历去调用“指标刷新服务”
  1479. func BatchChartInfoRefreshV2(chartInfoList []*data_manage.ChartInfo, redisKey string) (err error, isAsync bool) {
  1480. if len(chartInfoList) <= 0 {
  1481. return
  1482. }
  1483. chartInfoIdSlice := make([]int, 0)
  1484. for _, chartInfo := range chartInfoList {
  1485. chartInfoIdSlice = append(chartInfoIdSlice, chartInfo.ChartInfoId)
  1486. }
  1487. var errMsg string
  1488. defer func() {
  1489. if err != nil {
  1490. go alarm_msg.SendAlarmMsg("ChartInfoRefresh:"+errMsg, 3)
  1491. //go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "ChartInfoRefresh:"+errmsg, utils.EmailSendToUsers)
  1492. fmt.Println("ChartInfoRefresh Err:" + errMsg)
  1493. }
  1494. }()
  1495. // 是否删除缓存
  1496. isDeleteCache := true
  1497. if redisKey != `` {
  1498. //设置最多10分钟缓存
  1499. utils.Rc.SetNX(redisKey, 1, time.Minute*10)
  1500. defer func() {
  1501. if isDeleteCache {
  1502. utils.Rc.Delete(redisKey)
  1503. }
  1504. }()
  1505. }
  1506. // 获取需要刷新的指标信息
  1507. edbIdList := make([]int, 0)
  1508. edbInfoIdMap := make(map[int]int)
  1509. edbMappingList, err := data_manage.GetChartEdbMappingListByIdList(chartInfoIdSlice)
  1510. for _, v := range edbMappingList {
  1511. if _, ok := edbInfoIdMap[v.EdbInfoId]; !ok {
  1512. edbIdList = append(edbIdList, v.EdbInfoId)
  1513. edbInfoIdMap[v.EdbInfoId] = v.EdbInfoId
  1514. }
  1515. }
  1516. // 获取需要刷新的指标列表
  1517. newBaseEdbInfoArr, newBasePredictEdbInfoArr, newCalculateMap, newPredictCalculateMap, calculateArr, predictCalculateArr := getEdbInfoIdList(edbIdList)
  1518. // 需要刷新的指标数量
  1519. totalEdbInfo := len(newBaseEdbInfoArr) + len(calculateArr) + len(predictCalculateArr)
  1520. if totalEdbInfo > 20 { // 关联指标过多的时候,异步刷新
  1521. isAsync = true
  1522. isDeleteCache = false // 不删除缓存
  1523. //go refreshChartEdbInfo(chartInfoList, redisKey, newBaseEdbInfoArr, newBasePredictEdbInfoArr, newCalculateMap, newPredictCalculateMap, calculateArr, predictCalculateArr)
  1524. // 加入队列刷新
  1525. var refreshItem EdbQueueRefreshReq
  1526. refreshItem.RefreshKey = redisKey
  1527. for _, v := range chartInfoList {
  1528. key := utils.HZ_CHART_LIB_DETAIL + v.UniqueCode
  1529. refreshItem.ItemRefreshKeys = append(refreshItem.ItemRefreshKeys, key)
  1530. // eta平台的缓存,用于Ppt等地方的展示
  1531. refreshItem.ItemRefreshKeys = append(refreshItem.ItemRefreshKeys, GetChartInfoDataKey(v.ChartInfoId))
  1532. }
  1533. refreshItem.BaseEdbInfoArr = newBaseEdbInfoArr
  1534. refreshItem.BasePredictEdbInfoArr = newBasePredictEdbInfoArr
  1535. refreshItem.CalculateMap = newCalculateMap
  1536. refreshItem.PredictCalculateMap = newPredictCalculateMap
  1537. refreshItem.CalculateArr = calculateArr
  1538. refreshItem.PredictCalculateArr = predictCalculateArr
  1539. go PushEdb2Refresh(refreshItem)
  1540. } else {
  1541. err = edbInfoRefreshAll(false, newBaseEdbInfoArr, newBasePredictEdbInfoArr, newCalculateMap, newPredictCalculateMap, calculateArr, predictCalculateArr)
  1542. //清除图表缓存
  1543. for _, v := range chartInfoList {
  1544. key := utils.HZ_CHART_LIB_DETAIL + v.UniqueCode
  1545. _ = utils.Rc.Delete(key)
  1546. // eta平台的缓存,用于Ppt等地方的展示
  1547. _ = utils.Rc.Delete(GetChartInfoDataKey(v.ChartInfoId))
  1548. }
  1549. }
  1550. return
  1551. }
  1552. // refreshChartEdbInfo
  1553. // @Description: 刷新图表中的质保列表
  1554. // @author: Roc
  1555. // @datetime 2023-12-01 16:05:39
  1556. // @param chartInfoList []*data_manage.ChartInfo
  1557. // @param redisKey string
  1558. // @param newBaseEdbInfoArr []*data_manage.EdbInfo
  1559. // @param newBasePredictEdbInfoArr []*data_manage.EdbInfo
  1560. // @param newCalculateMap map[int]*data_manage.EdbInfo
  1561. // @param newPredictCalculateMap map[int]*data_manage.EdbInfo
  1562. // @param calculateArr []int
  1563. // @param predictCalculateArr []int
  1564. func refreshChartEdbInfo(chartInfoList []*data_manage.ChartInfo, redisKey string, newBaseEdbInfoArr, newBasePredictEdbInfoArr []*data_manage.EdbInfo, newCalculateMap, newPredictCalculateMap map[int]*data_manage.EdbInfo, calculateArr, predictCalculateArr []int) {
  1565. edbInfoRefreshAll(false, newBaseEdbInfoArr, newBasePredictEdbInfoArr, newCalculateMap, newPredictCalculateMap, calculateArr, predictCalculateArr)
  1566. //清除图表缓存
  1567. for _, v := range chartInfoList {
  1568. key := utils.HZ_CHART_LIB_DETAIL + v.UniqueCode
  1569. _ = utils.Rc.Delete(key)
  1570. }
  1571. // 如果是有插入redisKey,那么刷新结束后就清除缓存
  1572. if redisKey != `` {
  1573. utils.Rc.Delete(redisKey)
  1574. }
  1575. }
  1576. // GetBatchChartRefreshKey
  1577. // @Description: 获取批量刷新key
  1578. // @author: Roc
  1579. // @datetime 2023-11-30 13:30:26
  1580. // @param source string
  1581. // @param primaryId int
  1582. // @param subId int
  1583. // @return string
  1584. func GetBatchChartRefreshKey(source string, primaryId, subId int) string {
  1585. if source == `` {
  1586. return ``
  1587. }
  1588. return fmt.Sprint("batch_chart_refresh:", source, ":", primaryId, ":", subId)
  1589. }
  1590. // CheckBatchChartRefreshResult
  1591. // @Description: 判断报告中的图表是否刷新完成
  1592. // @author: Roc
  1593. // @datetime 2023-11-30 13:30:26
  1594. // @param source string
  1595. // @param primaryId int
  1596. // @param subId int
  1597. // @return string
  1598. func CheckBatchChartRefreshResult(source string, primaryId, subId int) (refreshResult bool) {
  1599. refreshResult = true
  1600. redisKey := GetBatchChartRefreshKey(source, primaryId, subId)
  1601. if redisKey != `` {
  1602. // 如果找到了key,那么就是还在更新中
  1603. isOk := utils.Rc.IsExist(redisKey)
  1604. if isOk {
  1605. refreshResult = false
  1606. }
  1607. }
  1608. return
  1609. }
  1610. func CheckIsEnChart(chartNameEn string, edbList []*data_manage.ChartEdbInfoMapping, source, chartType int) bool {
  1611. // 相关性图表不判断指标
  1612. if utils.InArrayByInt([]int{utils.CHART_SOURCE_CORRELATION, utils.CHART_SOURCE_ROLLING_CORRELATION, utils.CHART_SOURCE_LINE_EQUATION}, source) && chartNameEn != "" {
  1613. return true
  1614. }
  1615. if chartNameEn != "" && len(edbList) <= 0 {
  1616. return true
  1617. }
  1618. if chartNameEn == "" {
  1619. return false
  1620. }
  1621. // 截面散点图的话,肯定是有英文配置的
  1622. if chartType == utils.CHART_TYPE_SECTION_SCATTER {
  1623. return true
  1624. }
  1625. for _, v := range edbList {
  1626. if v.EdbNameEn == "" {
  1627. return false
  1628. }
  1629. if v.Unit != "无" && v.Unit != "" && v.UnitEn == "" {
  1630. return false
  1631. }
  1632. }
  1633. return true
  1634. }
  1635. func CheckIsEnEdb(edbNameEn, unit, unitEn string) bool {
  1636. if edbNameEn == "" {
  1637. return false
  1638. }
  1639. if unit != "无" && unit != "" && unitEn == "" {
  1640. return false
  1641. }
  1642. return true
  1643. }
  1644. // CheckIsDisableChart 根据指标Id判断是否是禁用图表
  1645. // return int 0:启用,1:禁用
  1646. func CheckIsDisableChart(edbInfoIdArr []int) (isDisable int) {
  1647. crmConfig, err := company.GetConfigDetailByCode("chart_disabled_edb")
  1648. if err != nil {
  1649. return
  1650. }
  1651. //没有配置,立马返回
  1652. if crmConfig.ConfigValue == `` {
  1653. return
  1654. }
  1655. confEdbInfoIdList := strings.Split(crmConfig.ConfigValue, ",")
  1656. for _, edbInfoId := range edbInfoIdArr {
  1657. for _, confEdbInfoId := range confEdbInfoIdList {
  1658. if strconv.Itoa(edbInfoId) == confEdbInfoId {
  1659. isDisable = 1
  1660. return
  1661. }
  1662. }
  1663. }
  1664. return
  1665. }
  1666. // CheckChartExtraConfig 校验图表额外配置的信息,并且获取相关联的指标id
  1667. func CheckChartExtraConfig(chartType int, extraConfigStr string) (edbIdList []int, err error, errMsg string) {
  1668. switch chartType {
  1669. case 10: //截面散点
  1670. var extraConfig data_manage.SectionScatterReq
  1671. err = json.Unmarshal([]byte(extraConfigStr), &extraConfig)
  1672. if err != nil {
  1673. return
  1674. }
  1675. // 判断是否有配置日期序列
  1676. if len(extraConfig.SeriesList) <= 0 {
  1677. errMsg = `请配置序列`
  1678. err = errors.New(errMsg)
  1679. return
  1680. }
  1681. // 判断是否有填写指标
  1682. if len(extraConfig.SeriesList[0].EdbInfoList) <= 0 {
  1683. errMsg = `请选择指标`
  1684. err = errors.New(errMsg)
  1685. return
  1686. }
  1687. // 遍历指标列表获取指标id
  1688. edbIdMap := make(map[int]int)
  1689. for _, v := range extraConfig.SeriesList[0].EdbInfoList {
  1690. // X 轴的指标id
  1691. if _, ok := edbIdMap[v.XEdbInfoId]; !ok {
  1692. edbIdMap[v.XEdbInfoId] = v.XEdbInfoId
  1693. edbIdList = append(edbIdList, v.XEdbInfoId)
  1694. }
  1695. // Y 轴的指标id
  1696. if _, ok := edbIdMap[v.YEdbInfoId]; !ok {
  1697. edbIdMap[v.YEdbInfoId] = v.YEdbInfoId
  1698. edbIdList = append(edbIdList, v.YEdbInfoId)
  1699. }
  1700. }
  1701. case utils.CHART_TYPE_RADAR:
  1702. var extraConfig data_manage.RadarChartInfoReq
  1703. if extraConfigStr == `` {
  1704. errMsg = "雷达图未配置"
  1705. err = errors.New(errMsg)
  1706. return
  1707. }
  1708. err = json.Unmarshal([]byte(extraConfigStr), &extraConfig)
  1709. if err != nil {
  1710. errMsg = "雷达图配置异常"
  1711. err = errors.New(errMsg)
  1712. return
  1713. }
  1714. case utils.CHART_TYPE_SECTION_COMBINE:
  1715. var extraConfig data_manage.ChartSectionAllExtraConf
  1716. if extraConfigStr == `` {
  1717. errMsg = "截面组合图未配置"
  1718. err = errors.New(errMsg)
  1719. return
  1720. }
  1721. err = json.Unmarshal([]byte(extraConfigStr), &extraConfig)
  1722. if err != nil {
  1723. errMsg = "截面组合图配置异常"
  1724. err = errors.New(errMsg + err.Error())
  1725. return
  1726. }
  1727. //校验引用日期名称是否重复
  1728. dateNameMap := make(map[string]int)
  1729. dateNameEnMap := make(map[string]int)
  1730. for _, v := range extraConfig.DateConfList {
  1731. if _, ok := dateNameMap[v.DateConfName]; ok {
  1732. errMsg = "截面组合图引用日期名称设置重复"
  1733. err = errors.New(errMsg + v.DateConfName)
  1734. return
  1735. }
  1736. if _, ok := dateNameEnMap[v.DateConfNameEn]; ok {
  1737. errMsg = "截面组合图引用日期名称设置重复"
  1738. err = errors.New(errMsg + v.DateConfNameEn)
  1739. return
  1740. }
  1741. if v.DateConfName != "" {
  1742. dateNameMap[v.DateConfName] = 1
  1743. }
  1744. if v.DateConfNameEn != "" {
  1745. dateNameEnMap[v.DateConfNameEn] = 1
  1746. }
  1747. }
  1748. //检查系列名称是否重复
  1749. seriesNameMap := make(map[string]int)
  1750. seriesNameEnMap := make(map[string]int)
  1751. for _, v := range extraConfig.SeriesList {
  1752. if _, ok := seriesNameMap[v.SeriesName]; ok {
  1753. errMsg = "截面组合图系列名称设置重复"
  1754. err = errors.New(errMsg + v.SeriesName)
  1755. return
  1756. }
  1757. if _, ok := seriesNameEnMap[v.SeriesNameEn]; ok {
  1758. errMsg = "截面组合图系列名称设置重复"
  1759. err = errors.New(errMsg + v.SeriesNameEn)
  1760. return
  1761. }
  1762. if v.SeriesName != "" {
  1763. seriesNameMap[v.SeriesName] = 1
  1764. }
  1765. if v.SeriesNameEn != "" {
  1766. seriesNameEnMap[v.SeriesNameEn] = 1
  1767. }
  1768. }
  1769. // 检查基准系列是否设置
  1770. if extraConfig.BaseChartSeriesName == "" {
  1771. errMsg = "截面组合图基准系列名称未设置"
  1772. err = errors.New(errMsg)
  1773. return
  1774. }
  1775. //todo 如果是详情接口,应该要从其他表里查询配置
  1776. // 遍历指标列表获取指标id
  1777. edbIdMap := make(map[int]int)
  1778. hasUsed := make(map[string]struct{})
  1779. for _, v := range extraConfig.SeriesList {
  1780. for _, item := range v.EdbInfoList {
  1781. if item.DateConfName != "" && item.DateConfType == 1 {
  1782. hasUsed[item.DateConfName] = struct{}{}
  1783. }
  1784. if _, ok := edbIdMap[item.EdbInfoId]; !ok {
  1785. edbIdMap[item.EdbInfoId] = item.EdbInfoId
  1786. edbIdList = append(edbIdList, item.EdbInfoId)
  1787. }
  1788. }
  1789. }
  1790. // todo 遍历引用日期获取引用日期里的指标ID, 如果引用日期里的指标没有被引用,是否加入映射
  1791. for _, v := range extraConfig.DateConfList {
  1792. if _, ok := hasUsed[v.DateConfName]; !ok {
  1793. continue
  1794. }
  1795. if _, ok := edbIdMap[v.EdbInfoId]; !ok && v.EdbInfoId > 0 {
  1796. edbIdMap[v.EdbInfoId] = v.EdbInfoId
  1797. edbIdList = append(edbIdList, v.EdbInfoId)
  1798. }
  1799. }
  1800. }
  1801. return
  1802. }
  1803. // GetSectionScatterChartData 截面散点图的数据处理
  1804. func GetSectionScatterChartData(chartInfoId int, mappingList []*data_manage.ChartEdbInfoMapping, edbDataListMap map[int][]*data_manage.EdbDataList, extraConfig data_manage.SectionScatterReq) (edbIdList []int, chartDataResp data_manage.SectionScatterInfoResp, err error) {
  1805. // 指标数据数组(10086:{"2022-12-02":100.01,"2022-12-01":102.3})
  1806. edbDataMap := make(map[int]map[string]float64)
  1807. for edbInfoId, edbDataList := range edbDataListMap {
  1808. edbDateData := make(map[string]float64)
  1809. for _, edbData := range edbDataList {
  1810. edbDateData[edbData.DataTime] = edbData.Value
  1811. }
  1812. edbDataMap[edbInfoId] = edbDateData
  1813. }
  1814. // edbIdList 指标展示顺序;x轴的指标顺序
  1815. edbIdList = make([]int, 0)
  1816. edbMappingMap := make(map[int]*data_manage.ChartEdbInfoMapping)
  1817. for _, v := range mappingList {
  1818. edbIdList = append(edbIdList, v.EdbInfoId)
  1819. edbMappingMap[v.EdbInfoId] = v
  1820. }
  1821. //SectionScatterSeriesInfoResp
  1822. dataListResp := make([]data_manage.SectionScatterSeriesItemResp, 0) //y轴的数据列表
  1823. for _, seriesItem := range extraConfig.SeriesList {
  1824. var maxDate time.Time
  1825. // 系列中的指标数据
  1826. tmpSeriesEdbInfoList := make([]data_manage.SectionScatterEdbItemResp, 0)
  1827. var minXVal, maxXVal, minYVal, maxYVal float64
  1828. for _, edbConf := range seriesItem.EdbInfoList {
  1829. tmpItem := data_manage.SectionScatterEdbItemResp{
  1830. IsShow: edbConf.IsShow,
  1831. Name: edbConf.Name,
  1832. NameEn: edbConf.NameEn,
  1833. } //单个坐标点的数据
  1834. //X轴的数据
  1835. {
  1836. edbInfoId := edbConf.XEdbInfoId //X轴的指标
  1837. edbMappingInfo, ok := edbMappingMap[edbInfoId]
  1838. if !ok {
  1839. continue
  1840. }
  1841. findDate := edbConf.XDate //需要的日期值
  1842. dataList := edbDataListMap[edbInfoId] //指标的所有数据值
  1843. if len(dataList) <= 0 {
  1844. // 没有数据的指标id
  1845. //findDataList = append(findDataList, 0)
  1846. continue
  1847. }
  1848. tmpItem.XEdbInfoId = edbInfoId
  1849. tmpItem.XName = edbMappingInfo.EdbName
  1850. tmpItem.XNameEn = edbMappingInfo.EdbNameEn
  1851. switch edbConf.XDateType {
  1852. case 1: //最新值
  1853. findDate = dataList[len(dataList)-1].DataTime
  1854. case 2: //近期几天
  1855. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[len(dataList)-1].DataTime, time.Local)
  1856. if tmpErr != nil {
  1857. err = tmpErr
  1858. return
  1859. }
  1860. findDateTime = findDateTime.AddDate(0, 0, -edbConf.XDateValue)
  1861. lenData := len(dataList) - 1
  1862. for i := lenData; i >= 0; i-- {
  1863. currDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[i].DataTime, time.Local)
  1864. if tmpErr != nil {
  1865. err = tmpErr
  1866. return
  1867. }
  1868. if currDateTime.Equal(findDateTime) || currDateTime.Before(findDateTime) {
  1869. findDate = dataList[i].DataTime
  1870. break
  1871. }
  1872. }
  1873. case 3: // 固定日期
  1874. //最早的日期
  1875. minDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  1876. if tmpErr != nil {
  1877. err = tmpErr
  1878. return
  1879. }
  1880. //寻找固定日期的数据
  1881. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, edbConf.XDate, time.Local)
  1882. if tmpErr != nil {
  1883. err = tmpErr
  1884. return
  1885. }
  1886. for tmpDateTime := findDateTime; tmpDateTime.After(minDateTime) || tmpDateTime.Equal(minDateTime); tmpDateTime = tmpDateTime.AddDate(0, 0, -1) {
  1887. tmpDate := tmpDateTime.Format(utils.FormatDate)
  1888. if _, ok := edbDataMap[edbInfoId][tmpDate]; ok { //如果能找到数据,那么就返回
  1889. findDate = tmpDate
  1890. break
  1891. }
  1892. }
  1893. default:
  1894. err = errors.New(fmt.Sprint("日期类型异常,Type:", edbConf.XDate))
  1895. return
  1896. }
  1897. findDateTime, _ := time.ParseInLocation(utils.FormatDate, findDate, time.Local)
  1898. if maxDate.IsZero() {
  1899. maxDate = findDateTime
  1900. } else {
  1901. if findDateTime.After(maxDate) {
  1902. maxDate = findDateTime
  1903. }
  1904. }
  1905. if tmpValue, ok := edbDataMap[edbInfoId][findDate]; ok {
  1906. tmpItem.XDate = findDate
  1907. tmpItem.XValue = tmpValue
  1908. } else {
  1909. continue
  1910. }
  1911. }
  1912. //Y轴的数据
  1913. {
  1914. edbInfoId := edbConf.YEdbInfoId //Y轴的指标
  1915. edbMappingInfo, ok := edbMappingMap[edbInfoId]
  1916. if !ok {
  1917. continue
  1918. }
  1919. findDate := edbConf.YDate //需要的日期值
  1920. dataList := edbDataListMap[edbInfoId] //指标的所有数据值
  1921. if len(dataList) <= 0 {
  1922. // 没有数据的指标id
  1923. //findDataList = append(findDataList, 0)
  1924. continue
  1925. }
  1926. tmpItem.YEdbInfoId = edbInfoId
  1927. tmpItem.YName = edbMappingInfo.EdbName
  1928. tmpItem.YNameEn = edbMappingInfo.EdbNameEn
  1929. switch edbConf.YDateType {
  1930. case 1: //最新值
  1931. findDate = dataList[len(dataList)-1].DataTime
  1932. case 2: //近期几天
  1933. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[len(dataList)-1].DataTime, time.Local)
  1934. if tmpErr != nil {
  1935. err = tmpErr
  1936. return
  1937. }
  1938. findDateTime = findDateTime.AddDate(0, 0, -edbConf.YDateValue)
  1939. lenData := len(dataList) - 1
  1940. for i := lenData; i >= 0; i-- {
  1941. currDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[i].DataTime, time.Local)
  1942. if tmpErr != nil {
  1943. err = tmpErr
  1944. return
  1945. }
  1946. if currDateTime.Equal(findDateTime) || currDateTime.Before(findDateTime) {
  1947. findDate = dataList[i].DataTime
  1948. break
  1949. }
  1950. }
  1951. case 3: // 固定日期
  1952. //最早的日期
  1953. minDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  1954. if tmpErr != nil {
  1955. err = tmpErr
  1956. return
  1957. }
  1958. //寻找固定日期的数据
  1959. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, edbConf.YDate, time.Local)
  1960. if tmpErr != nil {
  1961. err = tmpErr
  1962. return
  1963. }
  1964. for tmpDateTime := findDateTime; tmpDateTime.After(minDateTime) || tmpDateTime.Equal(minDateTime); tmpDateTime = tmpDateTime.AddDate(0, 0, -1) {
  1965. tmpDate := tmpDateTime.Format(utils.FormatDate)
  1966. if _, ok := edbDataMap[edbInfoId][tmpDate]; ok { //如果能找到数据,那么就返回
  1967. findDate = tmpDate
  1968. break
  1969. }
  1970. }
  1971. default:
  1972. err = errors.New(fmt.Sprint("日期类型异常,Type:", edbConf.YDate))
  1973. return
  1974. }
  1975. findDateTime, _ := time.ParseInLocation(utils.FormatDate, findDate, time.Local)
  1976. if maxDate.IsZero() {
  1977. maxDate = findDateTime
  1978. } else {
  1979. if findDateTime.After(maxDate) {
  1980. maxDate = findDateTime
  1981. }
  1982. }
  1983. if tmpValue, ok := edbDataMap[edbInfoId][findDate]; ok {
  1984. tmpItem.YDate = findDate
  1985. tmpItem.YValue = tmpValue
  1986. } else {
  1987. continue
  1988. }
  1989. }
  1990. // 获取当前系列的X轴的最大最小值
  1991. {
  1992. if tmpItem.XValue < minXVal {
  1993. minXVal = tmpItem.XValue
  1994. }
  1995. if tmpItem.XValue > maxXVal {
  1996. maxXVal = tmpItem.XValue
  1997. }
  1998. if tmpItem.YValue < minYVal {
  1999. minYVal = tmpItem.YValue
  2000. }
  2001. if tmpItem.YValue > maxYVal {
  2002. maxYVal = tmpItem.YValue
  2003. }
  2004. }
  2005. tmpSeriesEdbInfoList = append(tmpSeriesEdbInfoList, tmpItem)
  2006. }
  2007. trendLimitData := make([]data_manage.CoordinatePoint, 0) //趋势线的前后坐标点
  2008. var trendLine, rSquare string
  2009. // 生成线性方程式
  2010. var a, b float64
  2011. {
  2012. coordinateData := make([]utils.Coordinate, 0)
  2013. for _, tmpSeriesEdbInfo := range tmpSeriesEdbInfoList {
  2014. tmpCoordinate1 := utils.Coordinate{
  2015. X: tmpSeriesEdbInfo.XValue,
  2016. Y: tmpSeriesEdbInfo.YValue,
  2017. }
  2018. coordinateData = append(coordinateData, tmpCoordinate1)
  2019. }
  2020. // 只有存在两个坐标点的时候,才能去计算线性方程和R平方
  2021. if len(coordinateData) >= 2 {
  2022. a, b = utils.GetLinearResult(coordinateData)
  2023. if !math.IsNaN(a) && !math.IsNaN(b) {
  2024. if b > 0 {
  2025. trendLine = fmt.Sprintf("y=%sx+%s", utils.SubFloatToString(a, 4), utils.SubFloatToString(b, 4))
  2026. } else {
  2027. trendLine = fmt.Sprintf("y=%sx%s", utils.SubFloatToString(a, 4), utils.SubFloatToString(b, 4))
  2028. }
  2029. minYVal, _ = decimal.NewFromFloat(a).Mul(decimal.NewFromFloat(minXVal)).Add(decimal.NewFromFloat(b)).Round(4).Float64()
  2030. maxYVal, _ = decimal.NewFromFloat(a).Mul(decimal.NewFromFloat(maxXVal)).Add(decimal.NewFromFloat(b)).Round(4).Float64()
  2031. }
  2032. // 计算R平方
  2033. rSquare = fmt.Sprint(utils.CalculationDecisive(coordinateData))
  2034. }
  2035. trendLimitData = append(trendLimitData, data_manage.CoordinatePoint{
  2036. X: minXVal,
  2037. Y: minYVal,
  2038. }, data_manage.CoordinatePoint{
  2039. X: maxXVal,
  2040. Y: maxYVal,
  2041. })
  2042. }
  2043. dataListResp = append(dataListResp, data_manage.SectionScatterSeriesItemResp{
  2044. Name: seriesItem.Name,
  2045. NameEn: seriesItem.NameEn,
  2046. IsNameDefault: seriesItem.IsNameDefault,
  2047. Color: seriesItem.Color,
  2048. EdbInfoList: tmpSeriesEdbInfoList,
  2049. ShowTrendLine: seriesItem.ShowTrendLine,
  2050. ShowFitEquation: seriesItem.ShowFitEquation,
  2051. ShowRSquare: seriesItem.ShowRSquare,
  2052. TrendLine: trendLine,
  2053. RSquare: rSquare,
  2054. TrendLimitData: trendLimitData,
  2055. })
  2056. }
  2057. // 截面散点图点击详情时自动更新系列名
  2058. if len(extraConfig.SeriesList) > 0 {
  2059. // 默认名字的时候才自动更新
  2060. if extraConfig.SeriesList[0].IsNameDefault {
  2061. firstXEdbInfoId := extraConfig.SeriesList[0].EdbInfoList[0].XEdbInfoId
  2062. needUpdate := false
  2063. if v, ok := edbMappingMap[firstXEdbInfoId]; ok {
  2064. extraConfig.SeriesList[0].Name = v.LatestDate
  2065. extraConfig.SeriesList[0].NameEn = v.LatestDate
  2066. dataListResp[0].Name = v.LatestDate
  2067. dataListResp[0].NameEn = v.LatestDate
  2068. needUpdate = true
  2069. }
  2070. extraConfigByte, e := json.Marshal(extraConfig)
  2071. if e != nil {
  2072. errMsg := "截面散点系列更新异常"
  2073. err = errors.New(errMsg)
  2074. return
  2075. }
  2076. extraConfigStr := string(extraConfigByte)
  2077. if needUpdate {
  2078. err = data_manage.EditChartInfoExtraConfig(chartInfoId, extraConfigStr)
  2079. if err != nil {
  2080. errMsg := "截面散点系列更新异常"
  2081. err = errors.New(errMsg)
  2082. return
  2083. }
  2084. }
  2085. }
  2086. }
  2087. chartDataResp = data_manage.SectionScatterInfoResp{
  2088. XName: extraConfig.XName,
  2089. XNameEn: extraConfig.XNameEn,
  2090. XUnitName: extraConfig.XUnitName,
  2091. XUnitNameEn: extraConfig.XUnitNameEn,
  2092. YName: extraConfig.YName,
  2093. YNameEn: extraConfig.YNameEn,
  2094. YUnitName: extraConfig.YUnitName,
  2095. YUnitNameEn: extraConfig.YUnitNameEn,
  2096. XMinValue: extraConfig.XMinValue,
  2097. XMaxValue: extraConfig.XMaxValue,
  2098. YMinValue: extraConfig.YMinValue,
  2099. YMaxValue: extraConfig.YMaxValue,
  2100. DataList: dataListResp,
  2101. }
  2102. return
  2103. }
  2104. // AddChartInfo 添加图表
  2105. func AddChartInfo(req data_manage.AddChartInfoReq, sysUserId int, sysUserRealName, lang string) (chartInfo *data_manage.ChartInfo, err error, errMsg string, isSendEmail bool) {
  2106. isSendEmail = true // 默认错误的时候要发送邮件
  2107. req.ChartName = strings.Trim(req.ChartName, " ")
  2108. if req.ChartName == "" {
  2109. errMsg = "请填写图表名称!"
  2110. err = errors.New(errMsg)
  2111. isSendEmail = false
  2112. return
  2113. }
  2114. if req.ChartClassifyId <= 0 {
  2115. errMsg = "分类参数错误!"
  2116. err = errors.New(errMsg)
  2117. isSendEmail = false
  2118. return
  2119. }
  2120. //if req.ChartThemeId <= 0 {
  2121. // errMsg = "请选择主题"
  2122. // err = errors.New(errMsg)
  2123. // isSendEmail = false
  2124. // return
  2125. //}
  2126. //
  2127. //// 判断主题是否存在
  2128. //_, err = chart_theme.GetChartThemeId(req.ChartThemeId)
  2129. //if err != nil {
  2130. // if utils.IsErrNoRow(err) {
  2131. // errMsg = "主题不存在"
  2132. // err = errors.New(errMsg)
  2133. // return
  2134. // }
  2135. // errMsg = "获取主题信息失败"
  2136. // return
  2137. //}
  2138. chartClassify, err := data_manage.GetChartClassifyById(req.ChartClassifyId)
  2139. if err != nil {
  2140. if utils.IsErrNoRow(err) {
  2141. errMsg = "分类不存在"
  2142. err = errors.New(errMsg)
  2143. return
  2144. }
  2145. errMsg = "获取分类信息失败"
  2146. return
  2147. }
  2148. if chartClassify == nil || chartClassify.ChartClassifyId <= 0 {
  2149. errMsg = "分类不存在"
  2150. err = errors.New(errMsg)
  2151. return
  2152. }
  2153. chartType := req.ChartType
  2154. extraConfig := req.ExtraConfig
  2155. var extraConfigEdbInfoIdArr []int
  2156. extraConfigEdbInfoIdArr, err, errMsg = CheckChartExtraConfig(chartType, extraConfig)
  2157. if err != nil {
  2158. err = errors.New("添加失败:" + err.Error())
  2159. return
  2160. }
  2161. // 季节性图表额外配置信息
  2162. var seasonExtraConfig string
  2163. // 关联指标
  2164. var edbInfoIdArr []int
  2165. chartEdbInfoList := req.ChartEdbInfoList
  2166. if len(chartEdbInfoList) > 0 {
  2167. for _, v := range chartEdbInfoList {
  2168. edbInfoId := v.EdbInfoId
  2169. edbInfo, tmpErr := data_manage.GetEdbInfoById(edbInfoId)
  2170. if tmpErr != nil {
  2171. if utils.IsErrNoRow(tmpErr) {
  2172. errMsg = "指标不存在!"
  2173. err = errors.New("指标不存在,edbInfoId:" + strconv.Itoa(edbInfoId))
  2174. return
  2175. } else {
  2176. errMsg = "获取指标信息失败!"
  2177. err = errors.New("获取图表的指标信息失败,Err:" + tmpErr.Error())
  2178. return
  2179. }
  2180. }
  2181. if edbInfo == nil || edbInfo.EdbInfoId <= 0 {
  2182. errMsg = "指标已被删除,请重新选择!"
  2183. err = errors.New("指标不存在,edbInfoId:" + strconv.Itoa(edbInfoId))
  2184. return
  2185. } else {
  2186. if edbInfo.EdbInfoId <= 0 {
  2187. errMsg = "指标已被删除,请重新选择!"
  2188. err = errors.New("指标不存在,edbInfoId:" + strconv.Itoa(edbInfoId))
  2189. return
  2190. }
  2191. }
  2192. edbInfoIdArr = append(edbInfoIdArr, edbInfoId)
  2193. edbInfo.EdbNameSource = edbInfo.EdbName
  2194. //edbList = append(edbList, edbInfo)
  2195. //新增季节性图表数据计算
  2196. if chartType == 2 {
  2197. existCount, tmpErr := data_manage.GetEdbDataQuarterCount(edbInfoId)
  2198. if tmpErr != nil {
  2199. errMsg = "保存失败"
  2200. err = errors.New("判断季节性图表,指标数据是否存在失败,Err:" + tmpErr.Error())
  2201. return
  2202. }
  2203. if existCount <= 0 {
  2204. go data_manage.AddCalculateQuarter(edbInfoId, edbInfo.Source, edbInfo.EdbCode)
  2205. }
  2206. // 处理季节性图表横轴配置
  2207. {
  2208. if req.SeasonExtraConfig.XEndDate != "" {
  2209. if req.SeasonExtraConfig.XStartDate > req.SeasonExtraConfig.XEndDate && req.SeasonExtraConfig.JumpYear != 1 {
  2210. errMsg = "季节性图表配置信息异常:横坐标日期配置错误"
  2211. err = errors.New("季节性图表配置信息异常: 横坐标日期配置错误")
  2212. return
  2213. }
  2214. seasonExtra, tErr := json.Marshal(req.SeasonExtraConfig)
  2215. if tErr != nil {
  2216. errMsg = "季节性图表配置信息异常"
  2217. err = errors.New("季节性图表配置信息异常,Err:" + tErr.Error())
  2218. return
  2219. }
  2220. seasonExtraConfig = string(seasonExtra)
  2221. }
  2222. }
  2223. }
  2224. }
  2225. } else {
  2226. if extraConfig == `` {
  2227. errMsg = "请选择指标!"
  2228. err = errors.New(errMsg)
  2229. return
  2230. }
  2231. edbInfoIdArr = extraConfigEdbInfoIdArr
  2232. lenEdbInfoIdArr := len(edbInfoIdArr)
  2233. if lenEdbInfoIdArr > 0 {
  2234. tmpEdbList, tmpErr := data_manage.GetEdbInfoByIdList(edbInfoIdArr)
  2235. if tmpErr != nil {
  2236. errMsg = "指标异常!"
  2237. err = errors.New("指标异常!Err:" + tmpErr.Error())
  2238. return
  2239. }
  2240. if len(tmpEdbList) != lenEdbInfoIdArr {
  2241. errMsg = "指标异常!"
  2242. err = errors.New(fmt.Sprint("查找出来的指标数量与选择的指标数量不符!查找出来的指标数量:", len(tmpEdbList), ";用户选择的指标数量:", lenEdbInfoIdArr))
  2243. return
  2244. }
  2245. for _, v := range tmpEdbList {
  2246. chartEdbInfoList = append(chartEdbInfoList, &data_manage.ChartSaveItem{
  2247. EdbInfoId: v.EdbInfoId,
  2248. MaxData: 0,
  2249. MinData: 0,
  2250. IsOrder: false,
  2251. IsAxis: 1,
  2252. EdbInfoType: 1,
  2253. LeadValue: 0,
  2254. LeadUnit: "",
  2255. ChartStyle: "",
  2256. ChartColor: "",
  2257. PredictChartColor: "",
  2258. ChartWidth: 0,
  2259. ChartScale: 0,
  2260. Source: utils.CHART_SOURCE_DEFAULT,
  2261. })
  2262. }
  2263. }
  2264. }
  2265. if len(edbInfoIdArr) <= 0 {
  2266. errMsg = "请选择指标!"
  2267. err = errors.New(errMsg)
  2268. return
  2269. }
  2270. // 图表额外配置
  2271. var allExtraConfig string
  2272. extraConfig, allExtraConfig, err, errMsg = HandleExtraConfig(0, chartType, extraConfig)
  2273. if err != nil {
  2274. if errMsg == `` {
  2275. errMsg = "指标异常!"
  2276. }
  2277. err = errors.New("指标异常!Err:" + err.Error())
  2278. return
  2279. }
  2280. sort.Ints(edbInfoIdArr)
  2281. var edbInfoIdArrStr []string
  2282. for _, v := range edbInfoIdArr {
  2283. edbInfoIdArrStr = append(edbInfoIdArrStr, strconv.Itoa(v))
  2284. }
  2285. edbInfoIdStr := strings.Join(edbInfoIdArrStr, ",")
  2286. //count, err := data_manage.ChartInfoExist("", edbInfoIdStr)
  2287. //if err != nil && err.Error() != utils.ErrNoRow() {
  2288. // br.Msg = "保存失败"
  2289. // br.ErrMsg = "判断图表名称是否存在失败,Err:" + err.Error()
  2290. // return
  2291. //}
  2292. //if count > 0 {
  2293. // br.Msg = "所选指标已存在相同指标"
  2294. // return
  2295. //}
  2296. {
  2297. var count int // 同名指标数量
  2298. //判断图表是否存在
  2299. var condition string
  2300. var pars []interface{}
  2301. // 图表名称在不同图分类下不允许重复 需求调整时间:2022年11月07日09:47:07
  2302. //condition += " AND chart_classify_id=? "
  2303. //pars = append(pars, req.ChartClassifyId)
  2304. switch lang {
  2305. case utils.EnLangVersion:
  2306. condition += " AND chart_name_en = ? AND source = ? "
  2307. default:
  2308. condition += " AND chart_name = ? AND source = ? "
  2309. }
  2310. pars = append(pars, req.ChartName, utils.CHART_SOURCE_DEFAULT)
  2311. count, err = data_manage.GetChartInfoCountByCondition(condition, pars)
  2312. if err != nil {
  2313. errMsg = "判断图表名称是否存在失败"
  2314. err = errors.New("判断图表名称是否存在失败,Err:" + err.Error())
  2315. return
  2316. }
  2317. if count > 0 {
  2318. errMsg = "图表已存在,请重新填写"
  2319. err = errors.New(errMsg)
  2320. isSendEmail = false
  2321. return
  2322. }
  2323. }
  2324. barChartConf := `` //柱方图的配置信息
  2325. if chartType == 7 {
  2326. barChartConfReq := req.BarChartInfo
  2327. if len(barChartConfReq.EdbInfoIdList) <= 0 {
  2328. errMsg = "请选择指标"
  2329. err = errors.New(errMsg)
  2330. isSendEmail = false
  2331. return
  2332. }
  2333. if len(barChartConfReq.DateList) <= 0 {
  2334. errMsg = "请选择日期"
  2335. err = errors.New(errMsg)
  2336. isSendEmail = false
  2337. return
  2338. }
  2339. barChartConfByte, tmpErr := json.Marshal(barChartConfReq)
  2340. if tmpErr != nil {
  2341. errMsg = "柱方图信息异常"
  2342. err = errors.New("柱方图信息异常,Err:" + tmpErr.Error())
  2343. return
  2344. }
  2345. barChartConf = string(barChartConfByte)
  2346. }
  2347. disableVal := CheckIsDisableChart(edbInfoIdArr)
  2348. chartInfo = new(data_manage.ChartInfo)
  2349. chartInfo.ChartName = req.ChartName
  2350. chartInfo.ChartNameEn = req.ChartName
  2351. chartInfo.EdbInfoIds = edbInfoIdStr
  2352. chartInfo.ChartClassifyId = req.ChartClassifyId
  2353. chartInfo.SysUserId = sysUserId
  2354. chartInfo.SysUserRealName = sysUserRealName
  2355. chartInfo.CreateTime = time.Now()
  2356. chartInfo.ModifyTime = time.Now()
  2357. chartInfo.IsSetName = 0
  2358. timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
  2359. chartInfo.UniqueCode = utils.MD5(utils.CHART_PREFIX + "_" + timestamp)
  2360. // todo 判断是否需要重新计算用户的start_date
  2361. if req.DateType > 0 {
  2362. chartInfo.DateType = req.DateType
  2363. } else {
  2364. chartInfo.DateType = 3
  2365. }
  2366. if chartType == 0 {
  2367. chartType = 1
  2368. }
  2369. chartInfo.ChartType = chartType
  2370. calendar := req.Calendar
  2371. if calendar == "" {
  2372. calendar = "公历"
  2373. }
  2374. chartInfo.Calendar = calendar
  2375. chartInfo.StartDate = req.StartDate
  2376. chartInfo.EndDate = req.EndDate
  2377. chartInfo.SeasonStartDate = req.StartDate
  2378. chartInfo.SeasonEndDate = req.EndDate
  2379. chartInfo.LeftMin = req.LeftMin
  2380. chartInfo.LeftMax = req.LeftMax
  2381. chartInfo.RightMin = req.RightMin
  2382. chartInfo.RightMax = req.RightMax
  2383. chartInfo.Right2Min = req.Right2Min
  2384. chartInfo.Right2Max = req.Right2Max
  2385. chartInfo.MinMaxSave = req.MinMaxSave
  2386. chartInfo.Disabled = disableVal
  2387. chartInfo.BarConfig = barChartConf
  2388. chartInfo.ExtraConfig = extraConfig
  2389. chartInfo.SeasonExtraConfig = seasonExtraConfig
  2390. chartInfo.StartYear = req.StartYear
  2391. chartInfo.Source = utils.CHART_SOURCE_DEFAULT
  2392. chartInfo.ChartThemeId = req.ChartThemeId
  2393. chartInfo.SourcesFrom = req.SourcesFrom
  2394. chartInfo.Instructions = req.Instructions
  2395. chartInfo.MarkersLines = req.MarkersLines
  2396. chartInfo.MarkersAreas = req.MarkersAreas
  2397. chartInfo.Unit = req.Unit
  2398. chartInfo.UnitEn = req.UnitEn
  2399. chartInfo.ChartAlias = req.ChartAlias
  2400. newId, err := data_manage.AddChartInfo(chartInfo)
  2401. if err != nil {
  2402. errMsg = `保存失败`
  2403. err = errors.New("保存失败,Err:" + err.Error())
  2404. return
  2405. }
  2406. chartInfo.ChartInfoId = int(newId)
  2407. mapList := make([]*data_manage.ChartEdbMapping, 0)
  2408. for _, v := range chartEdbInfoList {
  2409. mapItem := new(data_manage.ChartEdbMapping)
  2410. mapItem.ChartInfoId = int(newId)
  2411. mapItem.EdbInfoId = v.EdbInfoId
  2412. mapItem.CreateTime = time.Now()
  2413. mapItem.ModifyTime = time.Now()
  2414. edbTimestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
  2415. mapItem.UniqueCode = utils.MD5(fmt.Sprint(utils.CHART_PREFIX, "_", v.EdbInfoId, "_", edbTimestamp))
  2416. mapItem.MaxData = v.MaxData
  2417. mapItem.MinData = v.MinData
  2418. mapItem.IsOrder = v.IsOrder
  2419. mapItem.IsAxis = v.IsAxis
  2420. mapItem.EdbInfoType = v.EdbInfoType
  2421. mapItem.LeadValue = v.LeadValue
  2422. mapItem.LeadUnit = v.LeadUnit
  2423. mapItem.ChartStyle = v.ChartStyle
  2424. mapItem.ChartColor = v.ChartColor
  2425. mapItem.PredictChartColor = v.PredictChartColor
  2426. mapItem.ChartWidth = v.ChartWidth
  2427. mapItem.ChartScale = v.ChartScale
  2428. mapItem.Source = utils.CHART_SOURCE_DEFAULT
  2429. mapItem.EdbAliasName = v.EdbAliasName
  2430. mapItem.IsConvert = v.IsConvert
  2431. mapItem.ConvertType = v.ConvertType
  2432. mapItem.ConvertValue = v.ConvertValue
  2433. mapItem.ConvertUnit = v.ConvertUnit
  2434. mapItem.ConvertEnUnit = v.ConvertEnUnit
  2435. mapList = append(mapList, mapItem)
  2436. }
  2437. err = data_manage.AddChartEdbMapping(mapList)
  2438. if err != nil {
  2439. errMsg = `保存失败`
  2440. err = errors.New("保存失败,Err:" + err.Error())
  2441. return
  2442. }
  2443. if chartType == utils.CHART_TYPE_SECTION_COMBINE {
  2444. err = data_manage.AddChartSeriesAndEdbMapping(allExtraConfig, int(newId))
  2445. if err != nil {
  2446. errMsg = `保存失败`
  2447. err = errors.New("保存失败,Err:" + err.Error())
  2448. return
  2449. }
  2450. }
  2451. // 添加指标引用记录
  2452. _ = SaveChartEdbInfoRelation(edbInfoIdArr, chartInfo)
  2453. //添加es数据
  2454. go EsAddOrEditChartInfo(chartInfo.ChartInfoId)
  2455. return
  2456. }
  2457. // EditChartInfo 编辑图表
  2458. func EditChartInfo(req data_manage.EditChartInfoReq, sysUser *system.Admin, lang string) (chartItem *data_manage.ChartInfo, err error, errMsg string, isSendEmail bool) {
  2459. isSendEmail = true // 默认错误的时候要发送邮件
  2460. req.ChartName = strings.Trim(req.ChartName, " ")
  2461. if req.ChartName == "" {
  2462. errMsg = "请填写图表名称!"
  2463. err = errors.New(errMsg)
  2464. isSendEmail = false
  2465. return
  2466. }
  2467. if req.ChartClassifyId <= 0 {
  2468. errMsg = "分类参数错误!"
  2469. err = errors.New(errMsg)
  2470. isSendEmail = false
  2471. return
  2472. }
  2473. //if req.ChartThemeId <= 0 {
  2474. // errMsg = "请选择主题!"
  2475. // err = errors.New(errMsg)
  2476. // isSendEmail = false
  2477. // return
  2478. //}
  2479. //
  2480. //// 判断主题是否存在
  2481. //_, err = chart_theme.GetChartThemeId(req.ChartThemeId)
  2482. //if err != nil {
  2483. // if utils.IsErrNoRow(err) {
  2484. // errMsg = "主题不存在"
  2485. // err = errors.New(errMsg)
  2486. // return
  2487. // }
  2488. // errMsg = "获取主题信息失败"
  2489. // return
  2490. //}
  2491. chartClassify, err := data_manage.GetChartClassifyById(req.ChartClassifyId)
  2492. if err != nil {
  2493. if utils.IsErrNoRow(err) {
  2494. errMsg = "分类不存在"
  2495. err = errors.New(errMsg)
  2496. return
  2497. }
  2498. errMsg = "获取分类信息失败"
  2499. return
  2500. }
  2501. if chartClassify == nil || chartClassify.ChartClassifyId <= 0 {
  2502. errMsg = "分类不存在"
  2503. err = errors.New(errMsg)
  2504. return
  2505. }
  2506. chartItem, err = data_manage.GetChartInfoById(req.ChartInfoId)
  2507. if err != nil {
  2508. if utils.IsErrNoRow(err) {
  2509. errMsg = "图表已被删除,请刷新页面"
  2510. err = errors.New(errMsg)
  2511. isSendEmail = false
  2512. return
  2513. }
  2514. errMsg = "获取图表信息失败"
  2515. err = errors.New("获取图表信息失败,Err:" + err.Error())
  2516. return
  2517. }
  2518. var extraConfigEdbInfoIdArr []int
  2519. extraConfigEdbInfoIdArr, err, errMsg = CheckChartExtraConfig(req.ChartType, req.ExtraConfig)
  2520. if err != nil {
  2521. err = errors.New("添加失败:" + err.Error())
  2522. return
  2523. }
  2524. // 季节性图表额外配置信息
  2525. var seasonExtraConfig string
  2526. // 图表关联指标id
  2527. chartEdbInfoList := make([]*data_manage.ChartSaveItem, 0)
  2528. // 关联指标
  2529. var edbInfoIdArr []int
  2530. // 非散点截面图的直接通过前端获取,散点截面图需要额外从配置中获取
  2531. if chartItem.ChartType != 10 && chartItem.ChartType != utils.CHART_TYPE_SECTION_COMBINE {
  2532. //edbList := make([]*data_manage.EdbInfo, 0)
  2533. for _, v := range req.ChartEdbInfoList {
  2534. edbInfoId := v.EdbInfoId
  2535. edbInfo, tmpErr := data_manage.GetEdbInfoById(edbInfoId)
  2536. if tmpErr != nil {
  2537. if utils.IsErrNoRow(tmpErr) {
  2538. errMsg = "指标不存在!"
  2539. err = errors.New("指标不存在,edbInfoId:" + strconv.Itoa(edbInfoId))
  2540. return
  2541. } else {
  2542. errMsg = "获取指标信息失败!"
  2543. err = errors.New("获取图表的指标信息失败,Err:" + tmpErr.Error())
  2544. return
  2545. }
  2546. }
  2547. if edbInfo == nil || edbInfo.EdbInfoId <= 0 {
  2548. errMsg = "指标已被删除,请重新选择!"
  2549. err = errors.New("指标不存在,ChartInfoId:" + strconv.Itoa(edbInfoId))
  2550. return
  2551. } else {
  2552. if edbInfo.EdbInfoId <= 0 {
  2553. errMsg = "指标已被删除,请重新选择!"
  2554. err = errors.New("指标不存在,ChartInfoId:" + strconv.Itoa(edbInfoId))
  2555. return
  2556. }
  2557. }
  2558. edbInfoIdArr = append(edbInfoIdArr, edbInfoId)
  2559. edbInfo.EdbNameSource = edbInfo.EdbName
  2560. //edbList = append(edbList, edbInfo)
  2561. //新增季节性图表数据计算
  2562. if req.ChartType == 2 {
  2563. existCount, tmpErr := data_manage.GetEdbDataQuarterCount(edbInfoId)
  2564. if tmpErr != nil {
  2565. errMsg = "保存失败"
  2566. err = errors.New("判断季节性图表,指标数据是否存在失败,Err:" + tmpErr.Error())
  2567. return
  2568. }
  2569. if existCount <= 0 {
  2570. go data_manage.AddCalculateQuarter(edbInfoId, edbInfo.Source, edbInfo.EdbCode)
  2571. }
  2572. // 处理季节性图表横轴配置
  2573. {
  2574. if req.SeasonExtraConfig.XEndDate != "" {
  2575. if req.SeasonExtraConfig.XStartDate > req.SeasonExtraConfig.XEndDate && req.SeasonExtraConfig.JumpYear != 1 {
  2576. errMsg = "季节性图表配置信息异常:横坐标日期配置错误"
  2577. err = errors.New("季节性图表配置信息异常: 横坐标日期配置错误")
  2578. return
  2579. }
  2580. seasonExtra, tErr := json.Marshal(req.SeasonExtraConfig)
  2581. if tErr != nil {
  2582. errMsg = "季节性图表配置信息异常"
  2583. err = errors.New("季节性图表配置信息异常,Err:" + tErr.Error())
  2584. return
  2585. }
  2586. seasonExtraConfig = string(seasonExtra)
  2587. }
  2588. }
  2589. }
  2590. }
  2591. chartEdbInfoList = req.ChartEdbInfoList
  2592. } else {
  2593. if req.ExtraConfig == `` {
  2594. errMsg = "请选择指标!"
  2595. err = errors.New(errMsg)
  2596. isSendEmail = false
  2597. return
  2598. }
  2599. edbInfoIdArr = extraConfigEdbInfoIdArr
  2600. lenEdbInfoIdArr := len(edbInfoIdArr)
  2601. if lenEdbInfoIdArr > 0 {
  2602. tmpEdbList, tmpErr := data_manage.GetEdbInfoByIdList(edbInfoIdArr)
  2603. if tmpErr != nil {
  2604. errMsg = "指标异常!"
  2605. err = errors.New("指标异常!Err:" + tmpErr.Error())
  2606. return
  2607. }
  2608. if len(tmpEdbList) != lenEdbInfoIdArr {
  2609. errMsg = "指标异常!"
  2610. err = errors.New(fmt.Sprint("查找出来的指标数量与选择的指标数量不符!查找出来的指标数量:", len(tmpEdbList), ";用户选择的指标数量:", lenEdbInfoIdArr))
  2611. return
  2612. }
  2613. for _, v := range tmpEdbList {
  2614. chartEdbInfoList = append(chartEdbInfoList, &data_manage.ChartSaveItem{
  2615. EdbInfoId: v.EdbInfoId,
  2616. MaxData: 0,
  2617. MinData: 0,
  2618. IsOrder: false,
  2619. IsAxis: 1,
  2620. EdbInfoType: 1,
  2621. LeadValue: 0,
  2622. LeadUnit: "",
  2623. ChartStyle: "",
  2624. ChartColor: "",
  2625. PredictChartColor: "",
  2626. ChartWidth: 0,
  2627. Source: utils.CHART_SOURCE_DEFAULT,
  2628. })
  2629. }
  2630. }
  2631. }
  2632. if len(edbInfoIdArr) <= 0 {
  2633. errMsg = "请选择指标!"
  2634. err = errors.New(errMsg)
  2635. isSendEmail = false
  2636. return
  2637. }
  2638. // 图表额外配置
  2639. extraConfig, allExtraConfig, err, errMsg := HandleExtraConfig(req.ChartInfoId, req.ChartType, req.ExtraConfig)
  2640. if err != nil {
  2641. if errMsg == `` {
  2642. errMsg = "指标异常!"
  2643. }
  2644. err = errors.New("指标异常!Err:" + err.Error())
  2645. return
  2646. }
  2647. req.ExtraConfig = extraConfig
  2648. // 权限
  2649. var haveOperaAuth bool
  2650. {
  2651. // 已授权分类id
  2652. permissionChartIdList, permissionClassifyIdList, tmpErr := data_manage_permission.GetUserChartAndClassifyPermissionList(sysUser.AdminId, chartItem.ChartInfoId, chartItem.ChartClassifyId)
  2653. if tmpErr != nil {
  2654. if errMsg == `` {
  2655. errMsg = "获取失败!"
  2656. }
  2657. err = errors.New("获取已授权分类id数据失败,Err:" + tmpErr.Error())
  2658. return
  2659. }
  2660. haveOperaAuth = data_manage_permission.CheckChartPermissionByPermissionIdList(chartItem.IsJoinPermission, chartClassify.IsJoinPermission, chartItem.ChartInfoId, chartItem.ChartClassifyId, permissionChartIdList, permissionClassifyIdList)
  2661. }
  2662. //图表操作权限
  2663. ok := CheckOpChartPermission(sysUser, chartItem.SysUserId, haveOperaAuth)
  2664. if !ok {
  2665. errMsg = "没有该图表的操作权限"
  2666. err = errors.New(errMsg)
  2667. isSendEmail = false
  2668. return
  2669. }
  2670. var calendar string
  2671. var dateType int
  2672. dateType = req.DateType
  2673. if req.ChartType != chartItem.ChartType {
  2674. if chartItem.ChartType != 2 && chartItem.Calendar == "" { //非季节性图
  2675. calendar = "公历"
  2676. }
  2677. if chartItem.ChartType == 2 && chartItem.DateType <= 0 {
  2678. dateType = 3
  2679. }
  2680. } else {
  2681. calendar = req.Calendar
  2682. }
  2683. sort.Ints(edbInfoIdArr)
  2684. var edbInfoIdArrStr []string
  2685. for _, v := range edbInfoIdArr {
  2686. edbInfoIdArrStr = append(edbInfoIdArrStr, strconv.Itoa(v))
  2687. }
  2688. edbInfoIdStr := strings.Join(edbInfoIdArrStr, ",")
  2689. //mappingCondition := ` AND chart_info_id<> ` + strconv.Itoa(req.ChartInfoId)
  2690. //count, err := data_manage.ChartInfoExist(mappingCondition, edbInfoIdStr)
  2691. //if err != nil && err.Error() != utils.ErrNoRow() {
  2692. // br.Msg = "保存失败"
  2693. // br.ErrMsg = "判断图表名称是否存在失败,Err:" + err.Error()
  2694. // return
  2695. //}
  2696. //if count > 0 {
  2697. // br.Msg = "所选指标已存在相同指标"
  2698. // return
  2699. //}
  2700. // 判断图表是否存在
  2701. {
  2702. var count int
  2703. var condition string
  2704. var pars []interface{}
  2705. condition += " AND chart_info_id<>? "
  2706. pars = append(pars, req.ChartInfoId)
  2707. // 图表名称在不同图分类下不允许重复 需求调整时间:2022年11月07日09:47:07
  2708. //condition += " AND chart_classify_id=? "
  2709. //pars = append(pars, req.ChartClassifyId)
  2710. switch lang {
  2711. case utils.EnLangVersion:
  2712. condition += " AND chart_name_en = ? AND source = ? "
  2713. default:
  2714. condition += " AND chart_name = ? AND source = ? "
  2715. }
  2716. pars = append(pars, req.ChartName, utils.CHART_SOURCE_DEFAULT)
  2717. count, err = data_manage.GetChartInfoCountByCondition(condition, pars)
  2718. if err != nil {
  2719. errMsg = "判断图表名称是否存在失败"
  2720. err = errors.New("判断图表名称是否存在失败,Err:" + err.Error())
  2721. return
  2722. }
  2723. if count > 0 {
  2724. errMsg = "图表已存在,请重新填写"
  2725. err = errors.New(errMsg)
  2726. isSendEmail = false
  2727. return
  2728. }
  2729. }
  2730. barChartConf := `` //柱方图的配置信息
  2731. if req.ChartType == 7 {
  2732. barChartConfReq := req.BarChartInfo
  2733. if len(barChartConfReq.EdbInfoIdList) <= 0 {
  2734. errMsg = "请选择指标"
  2735. err = errors.New(errMsg)
  2736. isSendEmail = false
  2737. return
  2738. }
  2739. if len(barChartConfReq.DateList) <= 0 {
  2740. errMsg = "请选择日期"
  2741. err = errors.New(errMsg)
  2742. isSendEmail = false
  2743. return
  2744. }
  2745. barChartConfByte, tmpErr := json.Marshal(barChartConfReq)
  2746. if tmpErr != nil {
  2747. errMsg = "柱方图信息异常"
  2748. err = errors.New("柱方图信息异常,Err:" + tmpErr.Error())
  2749. return
  2750. }
  2751. barChartConf = string(barChartConfByte)
  2752. }
  2753. // 图表启用与否
  2754. disableVal := CheckIsDisableChart(edbInfoIdArr)
  2755. switch lang {
  2756. case utils.EnLangVersion:
  2757. req.ChartNameEn = req.ChartName
  2758. req.ChartName = chartItem.ChartName
  2759. if req.UnitEn == `` {
  2760. req.UnitEn = req.Unit
  2761. }
  2762. req.Unit = chartItem.Unit
  2763. default:
  2764. req.ChartNameEn = chartItem.ChartNameEn
  2765. req.UnitEn = chartItem.UnitEn
  2766. }
  2767. err = data_manage.EditChartInfoAndMapping(&req, edbInfoIdStr, calendar, dateType, disableVal, barChartConf, chartEdbInfoList, seasonExtraConfig)
  2768. if err != nil {
  2769. errMsg = "保存失败"
  2770. err = errors.New("保存失败,Err:" + err.Error())
  2771. return
  2772. }
  2773. resp := new(data_manage.AddChartInfoResp)
  2774. resp.ChartInfoId = chartItem.ChartInfoId
  2775. resp.UniqueCode = chartItem.UniqueCode
  2776. resp.ChartType = req.ChartType
  2777. if chartItem.ChartType == utils.CHART_TYPE_SECTION_COMBINE {
  2778. err = data_manage.EditChartSeriesAndEdbMapping(allExtraConfig, chartItem.ChartInfoId)
  2779. if err != nil {
  2780. errMsg = "保存失败"
  2781. err = errors.New("保存失败,Err:" + err.Error())
  2782. return
  2783. }
  2784. }
  2785. // todo 添加指标引用记录
  2786. _ = SaveChartEdbInfoRelation(edbInfoIdArr, chartItem)
  2787. //添加es数据
  2788. go EsAddOrEditChartInfo(chartItem.ChartInfoId)
  2789. //修改my eta es数据
  2790. go EsAddOrEditMyChartInfoByChartInfoId(chartItem.ChartInfoId)
  2791. return
  2792. }
  2793. // GetEdbSourceByEdbInfoIdList 获取关联指标的来源
  2794. func GetEdbSourceByEdbInfoIdList(chartEdbInfoMappingList []*data_manage.ChartEdbInfoMapping) (sourceNameList, sourceNameEnList []string) {
  2795. sourceNameList = make([]string, 0)
  2796. sourceNameEnList = make([]string, 0)
  2797. sourceMap := make(map[int]string)
  2798. for _, v := range chartEdbInfoMappingList {
  2799. // 指标类型:1:基础指标,2:计算指标
  2800. if v.EdbType == 2 || v.EdbInfoCategoryType == 1 {
  2801. //sourceMap[0] = "弘则研究"
  2802. baseEdbInfoArr, _, _ := data_manage.GetRefreshEdbInfoFromBase(v.EdbInfoId, v.Source)
  2803. for _, baseEdbInfo := range baseEdbInfoArr {
  2804. if baseEdbInfo.EdbInfoType == 0 { //普通指标才参与,预测指标不参与
  2805. sourceMap[baseEdbInfo.Source] = baseEdbInfo.SourceName
  2806. }
  2807. }
  2808. } else {
  2809. sourceMap[v.Source] = v.SourceName
  2810. }
  2811. }
  2812. for source, sourceName := range sourceMap {
  2813. if utils.InArrayByInt([]int{utils.DATA_SOURCE_MANUAL, utils.DATA_SOURCE_MYSTEEL_CHEMICAL}, source) {
  2814. continue
  2815. }
  2816. sourceNameList = append(sourceNameList, sourceName)
  2817. sourceNameEn, ok := utils.DataSourceEnMap[source]
  2818. if !ok {
  2819. sourceNameEn = sourceName
  2820. }
  2821. sourceNameEnList = append(sourceNameEnList, sourceNameEn)
  2822. }
  2823. //sourceNameList = append(sourceNameList, utils.ChartDefaultNameCn)
  2824. //sourceNameEnList = append(sourceNameEnList, utils.ChartDefaultNameEn)
  2825. // 图表来源
  2826. conf, e := models.GetBusinessConf()
  2827. if e != nil {
  2828. return
  2829. }
  2830. if conf[models.BusinessConfCompanyName] != "" {
  2831. sourceNameList = append(sourceNameList, conf[models.BusinessConfCompanyName])
  2832. sourceNameEnList = append(sourceNameEnList, conf[models.BusinessConfCompanyName])
  2833. }
  2834. return
  2835. }
  2836. // RadarChartData 雷达图的数据处理
  2837. func RadarChartData(mappingList []*data_manage.ChartEdbInfoMapping, edbDataListMap map[int][]*data_manage.EdbDataList, extraConfig data_manage.RadarChartInfoReq) (edbIdList []int, chartDataResp data_manage.RadarChartInfoResp, err error) {
  2838. // 指标数据数组(10086:{"2022-12-02":100.01,"2022-12-01":102.3})
  2839. edbDataMap := make(map[int]map[string]float64)
  2840. for edbInfoId, edbDataList := range edbDataListMap {
  2841. edbDateData := make(map[string]float64)
  2842. for _, edbData := range edbDataList {
  2843. edbDateData[edbData.DataTime] = edbData.Value
  2844. }
  2845. edbDataMap[edbInfoId] = edbDateData
  2846. }
  2847. // edbIdList 指标展示顺序;x轴的指标顺序
  2848. edbIdList = make([]int, 0)
  2849. for _, v := range mappingList {
  2850. edbIdList = append(edbIdList, v.EdbInfoId)
  2851. }
  2852. chartDateList := extraConfig.DateList
  2853. yDataList := make([]data_manage.RadarYData, 0) //y轴的数据列表
  2854. for _, chartDate := range chartDateList {
  2855. var maxDate time.Time
  2856. findDataList := make([]float64, 0) // 当前日期的数据值
  2857. for _, edbInfoId := range edbIdList {
  2858. findDate := chartDate.Date //需要的日期值
  2859. dataList := edbDataListMap[edbInfoId] //指标的所有数据值
  2860. if len(dataList) <= 0 {
  2861. // 没有数据的指标id
  2862. findDataList = append(findDataList, 0)
  2863. continue
  2864. }
  2865. switch chartDate.Type {
  2866. case 1: //最新值
  2867. findDate = dataList[len(dataList)-1].DataTime
  2868. case 2: //近期几天
  2869. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[len(dataList)-1].DataTime, time.Local)
  2870. if tmpErr != nil {
  2871. err = tmpErr
  2872. return
  2873. }
  2874. findDateTime = findDateTime.AddDate(0, 0, -chartDate.Value)
  2875. lenData := len(dataList) - 1
  2876. for i := lenData; i >= 0; i-- {
  2877. currDateTime, e := time.ParseInLocation(utils.FormatDate, dataList[i].DataTime, time.Local)
  2878. if e != nil {
  2879. err = e
  2880. return
  2881. }
  2882. if currDateTime.Equal(findDateTime) || currDateTime.Before(findDateTime) {
  2883. findDate = dataList[i].DataTime
  2884. break
  2885. }
  2886. }
  2887. case 3: // 固定日期
  2888. //最早的日期
  2889. minDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  2890. if tmpErr != nil {
  2891. err = tmpErr
  2892. return
  2893. }
  2894. //寻找固定日期的数据
  2895. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, chartDate.Date, time.Local)
  2896. if tmpErr != nil {
  2897. err = tmpErr
  2898. return
  2899. }
  2900. for tmpDateTime := findDateTime; tmpDateTime.After(minDateTime) || tmpDateTime.Equal(minDateTime); tmpDateTime = tmpDateTime.AddDate(0, 0, -1) {
  2901. tmpDate := tmpDateTime.Format(utils.FormatDate)
  2902. if _, ok := edbDataMap[edbInfoId][tmpDate]; ok { //如果能找到数据,那么就返回
  2903. findDate = tmpDate
  2904. break
  2905. }
  2906. }
  2907. default:
  2908. err = errors.New(fmt.Sprint("日期类型异常,Type:", chartDate.Type))
  2909. return
  2910. }
  2911. findDateTime, _ := time.ParseInLocation(utils.FormatDate, findDate, time.Local)
  2912. if maxDate.IsZero() {
  2913. maxDate = findDateTime
  2914. } else {
  2915. if findDateTime.After(maxDate) {
  2916. maxDate = findDateTime
  2917. }
  2918. }
  2919. if tmpValue, ok := edbDataMap[edbInfoId][findDate]; ok {
  2920. tmpValue, _ = decimal.NewFromFloat(tmpValue).Round(4).Float64()
  2921. findDataList = append(findDataList, tmpValue)
  2922. } else {
  2923. findDataList = append(findDataList, 0)
  2924. }
  2925. }
  2926. yDate := "0000-00-00"
  2927. if !maxDate.IsZero() {
  2928. yDate = maxDate.Format(utils.FormatDate)
  2929. }
  2930. yDataList = append(yDataList, data_manage.RadarYData{
  2931. Date: yDate,
  2932. Value: findDataList,
  2933. Color: chartDate.Color,
  2934. Name: chartDate.Name,
  2935. })
  2936. }
  2937. chartDataResp = data_manage.RadarChartInfoResp{
  2938. YDataList: yDataList,
  2939. XEdbIdValue: edbIdList,
  2940. }
  2941. return
  2942. }
  2943. // GetChartConvertEdbData 获取图表数据转换的指标数据
  2944. func GetChartConvertEdbData(chartInfoId, chartType int, calendar, startDate, endDate string, mappingList []*data_manage.ChartEdbInfoMapping, extraConfigStr string, seasonExtraConfig string, isAxis int) (edbList []*data_manage.ChartEdbInfoMapping, xEdbIdValue []int, yDataList []data_manage.YData, dataResp interface{}, err error, errMsg string) {
  2945. edbList = make([]*data_manage.ChartEdbInfoMapping, 0)
  2946. xEdbIdValue = make([]int, 0)
  2947. yDataList = make([]data_manage.YData, 0)
  2948. var extraConfig interface{}
  2949. switch chartType {
  2950. case 7: // 柱形图
  2951. var barConfig data_manage.BarChartInfoReq
  2952. if extraConfigStr == `` {
  2953. errMsg = "柱方图未配置"
  2954. err = errors.New(errMsg)
  2955. return
  2956. }
  2957. err = json.Unmarshal([]byte(extraConfigStr), &barConfig)
  2958. if err != nil {
  2959. errMsg = "柱方图配置异常"
  2960. err = errors.New(errMsg)
  2961. return
  2962. }
  2963. extraConfig = barConfig
  2964. case 10: // 截面散点图
  2965. var tmpExtraConfig data_manage.SectionScatterReq
  2966. if extraConfigStr == `` {
  2967. errMsg = "截面散点图未配置"
  2968. err = errors.New(errMsg)
  2969. return
  2970. }
  2971. err = json.Unmarshal([]byte(extraConfigStr), &tmpExtraConfig)
  2972. if err != nil {
  2973. errMsg = "截面散点配置异常"
  2974. err = errors.New(errMsg)
  2975. return
  2976. }
  2977. extraConfig = tmpExtraConfig
  2978. case utils.CHART_TYPE_RADAR:
  2979. var barConfig data_manage.RadarChartInfoReq
  2980. if extraConfigStr == `` {
  2981. errMsg = "雷达图未配置"
  2982. err = errors.New(errMsg)
  2983. return
  2984. }
  2985. err = json.Unmarshal([]byte(extraConfigStr), &barConfig)
  2986. if err != nil {
  2987. errMsg = "雷达图配置异常"
  2988. err = errors.New(errMsg)
  2989. return
  2990. }
  2991. extraConfig = barConfig
  2992. default:
  2993. xEdbIdValue = make([]int, 0)
  2994. yDataList = make([]data_manage.YData, 0)
  2995. }
  2996. // 指标对应的所有数据
  2997. edbDataListMap, edbList, err := getEdbConvertDataMapList(chartInfoId, chartType, calendar, startDate, endDate, mappingList, seasonExtraConfig, isAxis)
  2998. if err != nil {
  2999. return
  3000. }
  3001. // 特殊图形数据处理
  3002. switch chartType {
  3003. case 2: // 季节性图
  3004. if seasonExtraConfig != "" {
  3005. // 季节性图计算不管图上数据时间,拿所有数据
  3006. _, tempEdbList, e := getEdbDataMapList(chartInfoId, chartType, calendar, "1990-01-01", "", mappingList, seasonExtraConfig)
  3007. if e != nil {
  3008. err = e
  3009. return
  3010. }
  3011. dataResp, err = SeasonChartData(tempEdbList, seasonExtraConfig)
  3012. } else {
  3013. // 兼容无配置的老图
  3014. dataResp = new(data_manage.SeasonChartResp)
  3015. }
  3016. case 7: // 柱形图
  3017. barChartConf := extraConfig.(data_manage.BarChartInfoReq)
  3018. xEdbIdValue, yDataList, err = BarChartData(mappingList, edbDataListMap, barChartConf.DateList, barChartConf.Sort)
  3019. for k := range yDataList {
  3020. yDataList[k].Unit = barChartConf.Unit
  3021. yDataList[k].UnitEn = barChartConf.UnitEn
  3022. }
  3023. for _, v := range edbList {
  3024. // 指标别名
  3025. if barChartConf.EdbInfoIdList != nil && len(barChartConf.EdbInfoIdList) > 0 {
  3026. for _, reqEdb := range barChartConf.EdbInfoIdList {
  3027. if v.EdbInfoId == reqEdb.EdbInfoId {
  3028. v.EdbAliasName = reqEdb.Name
  3029. }
  3030. }
  3031. }
  3032. }
  3033. case 10: // 截面散点图
  3034. sectionScatterConf := extraConfig.(data_manage.SectionScatterReq)
  3035. xEdbIdValue, dataResp, err = GetSectionScatterChartData(chartInfoId, mappingList, edbDataListMap, sectionScatterConf)
  3036. var tmpExtraConfig data_manage.SectionScatterReq
  3037. if extraConfigStr == `` {
  3038. errMsg = "截面散点图未配置"
  3039. err = errors.New(errMsg)
  3040. return
  3041. }
  3042. err = json.Unmarshal([]byte(extraConfigStr), &tmpExtraConfig)
  3043. if err != nil {
  3044. errMsg = "截面散点配置异常"
  3045. err = errors.New(errMsg)
  3046. return
  3047. }
  3048. // 这个数据没有必要返回给前端
  3049. for _, v := range edbList {
  3050. v.DataList = nil
  3051. }
  3052. case utils.CHART_TYPE_RADAR: //雷达图
  3053. radarConf := extraConfig.(data_manage.RadarChartInfoReq)
  3054. xEdbIdValue, dataResp, err = RadarChartData(mappingList, edbDataListMap, radarConf)
  3055. }
  3056. return
  3057. }
  3058. func getEdbConvertDataMapList(chartInfoId, chartType int, calendar, startDate, endDate string, mappingList []*data_manage.ChartEdbInfoMapping, seasonExtraConfig string, isAxis int) (edbDataListMap map[int][]*data_manage.EdbDataList, edbList []*data_manage.ChartEdbInfoMapping, err error) {
  3059. // 指标对应的所有数据
  3060. edbDataListMap = make(map[int][]*data_manage.EdbDataList)
  3061. for _, v := range mappingList {
  3062. //fmt.Println("v:", v.EdbInfoId)
  3063. item := new(data_manage.ChartEdbInfoMapping)
  3064. item.EdbInfoId = v.EdbInfoId
  3065. item.SourceName = v.SourceName
  3066. item.Source = v.Source
  3067. item.EdbCode = v.EdbCode
  3068. item.EdbName = v.EdbName
  3069. item.EdbNameEn = v.EdbNameEn
  3070. item.Frequency = v.Frequency
  3071. item.EdbType = v.EdbType
  3072. item.FrequencyEn = GetFrequencyEn(v.Frequency)
  3073. if v.Unit != `无` {
  3074. item.Unit = v.Unit
  3075. }
  3076. item.UnitEn = v.UnitEn
  3077. item.StartDate = v.StartDate
  3078. item.EndDate = v.EndDate
  3079. item.ModifyTime = v.ModifyTime
  3080. item.EdbInfoCategoryType = v.EdbInfoCategoryType
  3081. item.PredictChartColor = v.PredictChartColor
  3082. item.ClassifyId = v.ClassifyId
  3083. if chartInfoId <= 0 {
  3084. item.IsAxis = 1
  3085. item.LeadValue = 0
  3086. item.LeadUnit = ""
  3087. item.ChartEdbMappingId = 0
  3088. item.ChartInfoId = 0
  3089. item.IsOrder = false
  3090. item.EdbInfoType = 1
  3091. item.ChartStyle = ""
  3092. item.ChartColor = ""
  3093. item.ChartWidth = 0
  3094. item.MaxData = v.MaxValue
  3095. item.MinData = v.MinValue
  3096. } else {
  3097. item.IsAxis = v.IsAxis
  3098. item.EdbInfoType = v.EdbInfoType
  3099. item.LeadValue = v.LeadValue
  3100. item.LeadUnit = v.LeadUnit
  3101. item.LeadUnitEn = GetLeadUnitEn(v.LeadUnit)
  3102. item.ChartEdbMappingId = v.ChartEdbMappingId
  3103. item.ChartInfoId = v.ChartInfoId
  3104. item.ChartStyle = v.ChartStyle
  3105. item.ChartColor = v.ChartColor
  3106. item.ChartWidth = v.ChartWidth
  3107. item.IsOrder = v.IsOrder
  3108. item.MaxData = v.MaxData
  3109. item.MinData = v.MinData
  3110. }
  3111. item.LatestValue = v.LatestValue
  3112. item.LatestDate = v.LatestDate
  3113. item.UniqueCode = v.UniqueCode
  3114. item.MoveLatestDate = v.LatestDate
  3115. item.EdbAliasName = v.EdbAliasName
  3116. item.IsConvert = v.IsConvert
  3117. item.ConvertType = v.ConvertType
  3118. item.ConvertValue = v.ConvertValue
  3119. item.ConvertUnit = v.ConvertUnit
  3120. item.ConvertEnUnit = v.ConvertEnUnit
  3121. var startDateReal string
  3122. var diffSeconds int64
  3123. if chartType == 2 { //季节性图
  3124. startDateReal = startDate
  3125. if len(mappingList) > 1 {
  3126. item.IsAxis = v.IsAxis
  3127. }
  3128. } else {
  3129. if v.EdbInfoType == 0 && v.LeadUnit != "" && v.LeadValue > 0 { //领先指标
  3130. var startTimeRealTemp time.Time
  3131. startDateParse, _ := time.Parse(utils.FormatDate, startDate)
  3132. switch v.LeadUnit {
  3133. case "天":
  3134. startTimeRealTemp = startDateParse.AddDate(0, 0, -v.LeadValue)
  3135. case "月":
  3136. startTimeRealTemp = startDateParse.AddDate(0, -v.LeadValue, 0)
  3137. case "季":
  3138. startTimeRealTemp = startDateParse.AddDate(0, -3*v.LeadValue, 0)
  3139. case "周":
  3140. startTimeRealTemp = startDateParse.AddDate(0, 0, -7*v.LeadValue)
  3141. case "年":
  3142. startTimeRealTemp = startDateParse.AddDate(-v.LeadValue, 0, 0)
  3143. }
  3144. if startTimeRealTemp.Before(startDateParse) {
  3145. startDateReal = startTimeRealTemp.Format(utils.FormatDate)
  3146. diffSeconds = (int64(startTimeRealTemp.UnixNano()) - int64(startDateParse.UnixNano())) / 1e6
  3147. } else {
  3148. startDateReal = startDate
  3149. diffSeconds = 0
  3150. }
  3151. // 预测指标的开始日期也要偏移
  3152. {
  3153. day, tmpErr := utils.GetDaysBetween2Date(utils.FormatDate, startDate, startDateReal)
  3154. if tmpErr != nil {
  3155. err = tmpErr
  3156. return
  3157. }
  3158. moveLatestDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, item.MoveLatestDate, time.Local)
  3159. if tmpErr != nil {
  3160. err = tmpErr
  3161. return
  3162. }
  3163. item.MoveLatestDate = moveLatestDateTime.AddDate(0, 0, day).Format(utils.FormatDate)
  3164. }
  3165. } else {
  3166. startDateReal = startDate
  3167. }
  3168. }
  3169. //fmt.Println("line 1011 chart:", v.Source, v.EdbInfoId, startDateReal, endDate)
  3170. calendarPreYear := 0
  3171. if calendar == "农历" {
  3172. newStartDateReal, err := time.Parse(utils.FormatDate, startDateReal)
  3173. if err != nil {
  3174. fmt.Println("time.Parse:" + err.Error())
  3175. }
  3176. calendarPreYear = newStartDateReal.Year() - 1
  3177. newStartDateReal = newStartDateReal.AddDate(-1, 0, 0)
  3178. startDateReal = newStartDateReal.Format(utils.FormatDate)
  3179. }
  3180. dataList := make([]*data_manage.EdbDataList, 0)
  3181. //fmt.Println("chart:", v.Source, v.EdbInfoId, startDateReal, endDate)
  3182. //fmt.Println("calendarPreYear:", calendarPreYear)
  3183. //var newEdbInfo *data_manage.EdbInfo
  3184. switch v.EdbInfoCategoryType {
  3185. case 0:
  3186. dataList, err = data_manage.GetEdbDataList(v.Source, v.SubSource, v.EdbInfoId, startDateReal, endDate)
  3187. case 1:
  3188. _, dataList, _, _, err, _ = GetPredictDataListByPredictEdbInfoId(v.EdbInfoId, startDateReal, endDate, true)
  3189. default:
  3190. err = errors.New(fmt.Sprint("获取失败,指标类型异常", v.EdbInfoCategoryType))
  3191. }
  3192. if err != nil {
  3193. return
  3194. }
  3195. if v.IsConvert == 1 {
  3196. switch v.ConvertType {
  3197. case 1:
  3198. for i, data := range dataList {
  3199. dataList[i].Value = data.Value * v.ConvertValue
  3200. }
  3201. item.MaxData = item.MaxData * v.ConvertValue
  3202. item.MinData = item.MinData * v.ConvertValue
  3203. case 2:
  3204. for i, data := range dataList {
  3205. dataList[i].Value = data.Value / v.ConvertValue
  3206. }
  3207. item.MaxData = item.MaxData / v.ConvertValue
  3208. item.MinData = item.MinData / v.ConvertValue
  3209. case 3:
  3210. for i, data := range dataList {
  3211. dataList[i].Value = math.Log(data.Value) / math.Log(v.ConvertValue)
  3212. }
  3213. item.MaxData = math.Log(item.MaxData) / math.Log(v.ConvertValue)
  3214. item.MinData = math.Log(item.MinData) / math.Log(v.ConvertValue)
  3215. }
  3216. }
  3217. edbDataListMap[v.EdbInfoId] = dataList
  3218. if diffSeconds != 0 && v.EdbInfoType == 0 {
  3219. dataListLen := len(dataList)
  3220. for i := 0; i < dataListLen; i++ {
  3221. dataList[i].DataTimestamp = dataList[i].DataTimestamp - diffSeconds
  3222. }
  3223. }
  3224. if chartType == 2 && isAxis == 1 {
  3225. latestDate, tmpErr := time.Parse(utils.FormatDate, v.LatestDate)
  3226. if tmpErr != nil {
  3227. //item.DataList = dataList
  3228. item.IsNullData = true
  3229. edbList = append(edbList, item)
  3230. continue
  3231. err = errors.New(fmt.Sprint("获取最后实际数据的日期失败,Err:" + tmpErr.Error() + ";LatestDate:" + v.LatestDate))
  3232. return
  3233. }
  3234. if calendar == "农历" {
  3235. if len(dataList) <= 0 {
  3236. result := new(data_manage.EdbDataResult)
  3237. item.DataList = result
  3238. } else {
  3239. result, tmpErr := data_manage.AddCalculateQuarterV6(dataList)
  3240. if tmpErr != nil {
  3241. err = errors.New("获取农历数据失败,Err:" + tmpErr.Error())
  3242. return
  3243. }
  3244. quarterDataList, tErr := GetSeasonEdbInfoDataListByXDateNong(result, latestDate, seasonExtraConfig, calendarPreYear)
  3245. if tErr != nil {
  3246. err = errors.New("获取季节性图表数据失败,Err:" + tErr.Error())
  3247. return
  3248. }
  3249. item.DataList = quarterDataList
  3250. }
  3251. } else {
  3252. quarterDataList, tErr := GetSeasonEdbInfoDataListByXDate(dataList, latestDate, seasonExtraConfig)
  3253. if tErr != nil {
  3254. err = errors.New("获取季节性图表数据失败,Err:" + tErr.Error())
  3255. return
  3256. }
  3257. item.DataList = quarterDataList
  3258. }
  3259. } else if chartType == 2 && isAxis == 0 {
  3260. // 右轴数据处理,只要最新一年
  3261. latestDate, tmpErr := time.Parse(utils.FormatDate, v.LatestDate)
  3262. if tmpErr != nil {
  3263. //item.DataList = dataList
  3264. item.IsNullData = true
  3265. edbList = append(edbList, item)
  3266. continue
  3267. err = errors.New(fmt.Sprint("获取最后实际数据的日期失败,Err:" + tmpErr.Error() + ";LatestDate:" + v.LatestDate))
  3268. return
  3269. }
  3270. newDataList := make([]*data_manage.EdbDataList, 0)
  3271. for _, v := range dataList {
  3272. dataTime, e := time.Parse(utils.FormatDate, v.DataTime)
  3273. if e != nil {
  3274. err = errors.New("季节性图处理右轴指标数据转换日期失败,Err:" + e.Error())
  3275. return
  3276. }
  3277. if dataTime.Year() == latestDate.Year() {
  3278. newDataList = append(newDataList, v)
  3279. }
  3280. }
  3281. item.DataList = newDataList
  3282. } else if chartType == 7 || chartType == utils.CHART_TYPE_RADAR { //柱方图
  3283. //item.DataList = dataList
  3284. } else {
  3285. item.DataList = dataList
  3286. }
  3287. edbList = append(edbList, item)
  3288. }
  3289. return
  3290. }
  3291. // GetChartEdbDataV2 获取图表的指标数据
  3292. func GetChartEdbDataV2(chartInfoId, chartType int, calendar, startDate, endDate string, mappingList []*data_manage.ChartEdbInfoMapping, extraConfigStr string, seasonExtraConfig string, chartInfoData ChartInfoDataShow) (edbList []*data_manage.ChartEdbInfoMapping, xEdbIdValue []int, yDataList []data_manage.YData, dataResp interface{}, err error, errMsg string) {
  3293. edbList = make([]*data_manage.ChartEdbInfoMapping, 0)
  3294. xEdbIdValue = make([]int, 0)
  3295. yDataList = make([]data_manage.YData, 0)
  3296. var extraConfig interface{}
  3297. switch chartType {
  3298. case 6:
  3299. var tmpConfig data_manage.ChartTimeCombineExtraConf
  3300. if extraConfigStr != `` {
  3301. err = json.Unmarshal([]byte(extraConfigStr), &tmpConfig)
  3302. if err != nil {
  3303. errMsg = "雷达图配置异常"
  3304. err = errors.New(errMsg)
  3305. return
  3306. }
  3307. }
  3308. extraConfig = tmpConfig
  3309. case 7: // 柱形图
  3310. var barConfig data_manage.BarChartInfoReq
  3311. if extraConfigStr == `` {
  3312. errMsg = "柱方图未配置"
  3313. err = errors.New(errMsg)
  3314. return
  3315. }
  3316. err = json.Unmarshal([]byte(extraConfigStr), &barConfig)
  3317. if err != nil {
  3318. errMsg = "柱方图配置异常"
  3319. err = errors.New(errMsg)
  3320. return
  3321. }
  3322. extraConfig = barConfig
  3323. case 10: // 截面散点图
  3324. var tmpExtraConfig data_manage.SectionScatterReq
  3325. if extraConfigStr == `` {
  3326. errMsg = "截面散点图未配置"
  3327. err = errors.New(errMsg)
  3328. return
  3329. }
  3330. err = json.Unmarshal([]byte(extraConfigStr), &tmpExtraConfig)
  3331. if err != nil {
  3332. errMsg = "截面散点配置异常"
  3333. err = errors.New(errMsg)
  3334. return
  3335. }
  3336. extraConfig = tmpExtraConfig
  3337. case utils.CHART_TYPE_RADAR:
  3338. var barConfig data_manage.RadarChartInfoReq
  3339. if extraConfigStr == `` {
  3340. errMsg = "雷达图未配置"
  3341. err = errors.New(errMsg)
  3342. return
  3343. }
  3344. err = json.Unmarshal([]byte(extraConfigStr), &barConfig)
  3345. if err != nil {
  3346. errMsg = "雷达图配置异常"
  3347. err = errors.New(errMsg)
  3348. return
  3349. }
  3350. extraConfig = barConfig
  3351. case utils.CHART_TYPE_SECTION_COMBINE:
  3352. // 预览和详情都走这个接口
  3353. var sectionExtraConfig data_manage.ChartSectionAllExtraConf
  3354. if extraConfigStr == `` {
  3355. errMsg = "截面组合图未配置"
  3356. err = errors.New(errMsg)
  3357. return
  3358. }
  3359. if chartInfoId > 0 {
  3360. var sectionExtraConfigTmp data_manage.ChartSectionExtraConf
  3361. err = json.Unmarshal([]byte(extraConfigStr), &sectionExtraConfigTmp)
  3362. if err != nil {
  3363. errMsg = "截面组合图配置异常"
  3364. err = errors.New(errMsg)
  3365. return
  3366. }
  3367. sectionExtraConfig.XDataList = sectionExtraConfigTmp.XDataList
  3368. sectionExtraConfig.BaseChartSeriesName = sectionExtraConfigTmp.BaseChartSeriesName
  3369. sectionExtraConfig.UnitList = sectionExtraConfigTmp.UnitList
  3370. sectionExtraConfig.DateConfList = sectionExtraConfigTmp.DateConfList
  3371. sectionExtraConfig.IsHeap = sectionExtraConfigTmp.IsHeap
  3372. sectionExtraConfig.SortType = sectionExtraConfigTmp.SortType
  3373. // 查询所有的seriesEdb
  3374. seriesEdbList, e := data_manage.GetChartSeriesEdbByChartInfoId(chartInfoId)
  3375. if e != nil {
  3376. errMsg = "查询seriesEdb失败"
  3377. err = errors.New(errMsg + e.Error())
  3378. return
  3379. }
  3380. // todo 是否有必要返回单位信息
  3381. // 组装成map
  3382. seriesEdbMap := make(map[int][]*data_manage.ChartSectionSeriesEdbConf)
  3383. for _, v := range seriesEdbList {
  3384. var dateConf *data_manage.ChartSectionSeriesDateConfItem
  3385. if v.DateConf != "" {
  3386. err = json.Unmarshal([]byte(v.DateConf), &dateConf)
  3387. if err != nil {
  3388. errMsg = "截面组合图配置异常"
  3389. err = errors.New(errMsg + e.Error())
  3390. return
  3391. }
  3392. }
  3393. tmp := &data_manage.ChartSectionSeriesEdbConf{
  3394. ChartSeriesEdbMappingId: v.ChartSeriesEdbMappingId,
  3395. ChartSeriesId: v.ChartSeriesId,
  3396. //ChartInfoId: v.ChartInfoId,
  3397. EdbInfoId: v.EdbInfoId,
  3398. DateConf: dateConf,
  3399. EdbName: "",
  3400. EdbNameEn: "",
  3401. Unit: "",
  3402. UnitEn: "",
  3403. DateConfName: v.DateConfName,
  3404. DateConfType: v.DateConfType,
  3405. }
  3406. seriesEdbMap[v.ChartSeriesId] = append(seriesEdbMap[v.ChartSeriesId], tmp)
  3407. }
  3408. //查询series
  3409. seriesListTmp, e := data_manage.GetChartSeriesByChartInfoId(chartInfoId)
  3410. if e != nil {
  3411. errMsg = "查询series失败"
  3412. err = errors.New(errMsg + e.Error())
  3413. return
  3414. }
  3415. seriesList := make([]*data_manage.ChartSectionSeriesItem, 0)
  3416. for _, v := range seriesListTmp {
  3417. tmpSeries := &data_manage.ChartSectionSeriesItem{
  3418. ChartSeriesId: v.ChartSeriesId,
  3419. SeriesName: v.SeriesName,
  3420. SeriesNameEn: v.SeriesNameEn,
  3421. ChartStyle: v.ChartStyle,
  3422. ChartColor: v.ChartColor,
  3423. ChartWidth: v.ChartWidth,
  3424. IsPoint: v.IsPoint,
  3425. IsNumber: v.IsNumber,
  3426. IsAxis: v.IsAxis,
  3427. MaxData: v.MaxData,
  3428. MinData: v.MinData,
  3429. //IsOrder: false,
  3430. EdbInfoList: nil,
  3431. DataList: nil,
  3432. }
  3433. edbInfoList, ok := seriesEdbMap[v.ChartSeriesId]
  3434. if ok {
  3435. tmpSeries.EdbInfoList = edbInfoList
  3436. }
  3437. seriesList = append(seriesList, tmpSeries)
  3438. }
  3439. sectionExtraConfig.SeriesList = seriesList
  3440. } else {
  3441. err = json.Unmarshal([]byte(extraConfigStr), &sectionExtraConfig)
  3442. if err != nil {
  3443. errMsg = "截面组合图配置异常"
  3444. err = errors.New(errMsg)
  3445. return
  3446. }
  3447. }
  3448. //校验引用日期名称是否重复
  3449. dateNameMap := make(map[string]int)
  3450. dateNameEnMap := make(map[string]int)
  3451. for _, v := range sectionExtraConfig.DateConfList {
  3452. if _, ok := dateNameMap[v.DateConfName]; ok {
  3453. errMsg = "截面组合图引用日期名称设置重复"
  3454. err = errors.New(errMsg + v.DateConfName)
  3455. return
  3456. }
  3457. if _, ok := dateNameEnMap[v.DateConfNameEn]; ok {
  3458. errMsg = "截面组合图引用日期名称设置重复"
  3459. err = errors.New(errMsg + v.DateConfNameEn)
  3460. return
  3461. }
  3462. if v.DateConfName != "" {
  3463. dateNameMap[v.DateConfName] = 1
  3464. }
  3465. if v.DateConfNameEn != "" {
  3466. dateNameEnMap[v.DateConfNameEn] = 1
  3467. }
  3468. }
  3469. //检查系列名称是否重复
  3470. seriesNameMap := make(map[string]int)
  3471. seriesNameEnMap := make(map[string]int)
  3472. for _, v := range sectionExtraConfig.SeriesList {
  3473. if _, ok := seriesNameMap[v.SeriesName]; ok {
  3474. errMsg = "截面组合图系列名称设置重复"
  3475. err = errors.New(errMsg + v.SeriesName)
  3476. return
  3477. }
  3478. if _, ok := seriesNameEnMap[v.SeriesNameEn]; ok {
  3479. errMsg = "截面组合图系列名称设置重复"
  3480. err = errors.New(errMsg + v.SeriesNameEn)
  3481. return
  3482. }
  3483. if v.SeriesName != "" {
  3484. seriesNameMap[v.SeriesName] = 1
  3485. }
  3486. if v.SeriesNameEn != "" {
  3487. seriesNameEnMap[v.SeriesNameEn] = 1
  3488. }
  3489. }
  3490. // 检查基准系列是否设置
  3491. if sectionExtraConfig.BaseChartSeriesName == "" {
  3492. errMsg = "截面组合图基准系列名称未设置"
  3493. err = errors.New(errMsg)
  3494. return
  3495. }
  3496. //todo 如果是详情接口,应该要从其他表里查询配置
  3497. extraConfig = sectionExtraConfig
  3498. default:
  3499. xEdbIdValue = make([]int, 0)
  3500. yDataList = make([]data_manage.YData, 0)
  3501. }
  3502. // 指标对应的所有数据
  3503. edbDataListMap, edbList, err := chartInfoData.GetEdbDataMapList(chartInfoId, chartType, calendar, startDate, endDate, mappingList, seasonExtraConfig)
  3504. if err != nil {
  3505. return
  3506. }
  3507. // 特殊图形数据处理
  3508. switch chartType {
  3509. case 6: //时序组合图
  3510. //判断是否堆积
  3511. timeConf := extraConfig.(data_manage.ChartTimeCombineExtraConf)
  3512. if extraConfigStr == "" { //历史数据,默认开启堆积
  3513. timeConf = data_manage.ChartTimeCombineExtraConf{
  3514. IsHeap: 1,
  3515. }
  3516. }
  3517. dataResp = data_manage.ChartTimeCombineDataResp{IsHeap: timeConf.IsHeap}
  3518. case 2: // 季节性图
  3519. if seasonExtraConfig != "" {
  3520. // 季节性图计算不管图上数据时间,拿所有数据
  3521. _, tempEdbList, e := getEdbDataMapListForSeason(chartInfoId, chartType, calendar, "1990-01-01", "", mappingList, seasonExtraConfig)
  3522. if e != nil {
  3523. err = e
  3524. return
  3525. }
  3526. dataResp, err = SeasonChartData(tempEdbList, seasonExtraConfig)
  3527. } else {
  3528. // 兼容无配置的老图
  3529. dataResp = new(data_manage.SeasonChartResp)
  3530. }
  3531. case 7: // 柱形图
  3532. barChartConf := extraConfig.(data_manage.BarChartInfoReq)
  3533. xEdbIdValue, yDataList, err = BarChartData(mappingList, edbDataListMap, barChartConf.DateList, barChartConf.Sort)
  3534. for k := range yDataList {
  3535. yDataList[k].Unit = barChartConf.Unit
  3536. yDataList[k].UnitEn = barChartConf.UnitEn
  3537. }
  3538. for _, v := range edbList {
  3539. // 指标别名
  3540. if barChartConf.EdbInfoIdList != nil && len(barChartConf.EdbInfoIdList) > 0 {
  3541. for _, reqEdb := range barChartConf.EdbInfoIdList {
  3542. if v.EdbInfoId == reqEdb.EdbInfoId {
  3543. v.EdbAliasName = reqEdb.Name
  3544. }
  3545. }
  3546. }
  3547. }
  3548. case 10: // 截面散点图
  3549. sectionScatterConf := extraConfig.(data_manage.SectionScatterReq)
  3550. xEdbIdValue, dataResp, err = GetSectionScatterChartData(chartInfoId, mappingList, edbDataListMap, sectionScatterConf)
  3551. var tmpExtraConfig data_manage.SectionScatterReq
  3552. if extraConfigStr == `` {
  3553. errMsg = "截面散点图未配置"
  3554. err = errors.New(errMsg)
  3555. return
  3556. }
  3557. err = json.Unmarshal([]byte(extraConfigStr), &tmpExtraConfig)
  3558. if err != nil {
  3559. errMsg = "截面散点配置异常"
  3560. err = errors.New(errMsg)
  3561. return
  3562. }
  3563. // 这个数据没有必要返回给前端
  3564. for _, v := range edbList {
  3565. v.DataList = nil
  3566. }
  3567. case utils.CHART_TYPE_SECTION_COMBINE: // 截面组合图
  3568. sectionConf := extraConfig.(data_manage.ChartSectionAllExtraConf)
  3569. var chartInfo *data_manage.ChartInfo
  3570. if chartInfoId > 0 {
  3571. chartInfo, err = data_manage.GetChartInfoById(chartInfoId)
  3572. if err != nil {
  3573. errMsg = "获取图表信息失败"
  3574. return
  3575. }
  3576. }
  3577. xEdbIdValue, dataResp, err = GetChartSectionCombineData(chartInfo, mappingList, edbDataListMap, sectionConf)
  3578. // 这个数据没有必要返回给前端
  3579. for _, v := range edbList {
  3580. v.DataList = nil
  3581. }
  3582. case utils.CHART_TYPE_RADAR: //雷达图
  3583. radarConf := extraConfig.(data_manage.RadarChartInfoReq)
  3584. xEdbIdValue, dataResp, err = RadarChartData(mappingList, edbDataListMap, radarConf)
  3585. }
  3586. return
  3587. }
  3588. // SeasonChartData 季节性图的数据处理
  3589. func SeasonChartData(dataList []*data_manage.ChartEdbInfoMapping, seasonExtraConfig string) (dataResp data_manage.SeasonChartResp, err error) {
  3590. var seasonConfig data_manage.SeasonExtraItem
  3591. err = json.Unmarshal([]byte(seasonExtraConfig), &seasonConfig)
  3592. if err != nil {
  3593. err = errors.New("季节性图配置异常, Err:" + err.Error())
  3594. return
  3595. }
  3596. for _, mappingItem := range dataList {
  3597. if mappingItem.IsAxis == 0 {
  3598. continue
  3599. }
  3600. quarterDataList, ok := mappingItem.DataList.(data_manage.QuarterDataList)
  3601. if !ok {
  3602. continue
  3603. }
  3604. // 上下限区间
  3605. if seasonConfig.MaxMinLimits.Year > 0 {
  3606. startYear := time.Now().AddDate(-seasonConfig.MaxMinLimits.Year, 0, 0).Year()
  3607. dataResp.MaxMinLimits.List = make([]*data_manage.MaxMinLimitsData, 0)
  3608. dataTimeMap := make(map[time.Time]time.Time)
  3609. dataTimeList := make([]string, 0)
  3610. maxValueMap := make(map[time.Time]float64)
  3611. minValueMap := make(map[time.Time]float64)
  3612. maxMinDataList := make([]*data_manage.MaxMinLimitsData, 0)
  3613. var startDateStr string
  3614. var endDateStr string
  3615. var newDate time.Time
  3616. startDateStr = fmt.Sprintf("%d-%s", time.Now().Year(), seasonConfig.XStartDate)
  3617. endDateStr = fmt.Sprintf("%d-%s", time.Now().Year(), seasonConfig.XEndDate)
  3618. startDate, e := time.Parse(utils.FormatDate, startDateStr)
  3619. if e != nil {
  3620. err = e
  3621. return
  3622. }
  3623. endDate, e := time.Parse(utils.FormatDate, endDateStr)
  3624. if e != nil {
  3625. err = e
  3626. return
  3627. }
  3628. // 日度 周度插值
  3629. for _, v := range quarterDataList {
  3630. if mappingItem.Frequency == "日度" || mappingItem.Frequency == "周度" {
  3631. handleDataMap := make(map[string]float64)
  3632. dataTimeList, _, err = HandleDataByLinearRegressionToList(v.DataList, handleDataMap)
  3633. if err != nil {
  3634. err = errors.New("插值处理数据异常, Err:" + err.Error())
  3635. return
  3636. }
  3637. // 不包含当年
  3638. if v.ChartLegend == strconv.Itoa(time.Now().Year()) {
  3639. continue
  3640. }
  3641. // 农历时dataTimeList的年份为最新年份,图例时间的年份才是真实年份
  3642. chartLegend, _ := strconv.Atoi(v.ChartLegend)
  3643. if chartLegend < startYear {
  3644. continue
  3645. }
  3646. for _, date := range dataTimeList {
  3647. dateTime, e := time.Parse(utils.FormatDate, date)
  3648. if e != nil {
  3649. err = errors.New("时间格式化异常, Err:" + e.Error())
  3650. return
  3651. }
  3652. if dateTime.Year() < startYear {
  3653. continue
  3654. }
  3655. // 不包含2月29号
  3656. if dateTime.Month() == 2 && dateTime.Day() == 29 {
  3657. continue
  3658. }
  3659. newDate = dateTime.AddDate(time.Now().Year()-dateTime.Year(), 0, 0)
  3660. if seasonConfig.JumpYear == 1 {
  3661. if startDate.After(endDate) {
  3662. // 如果跨年且不到一年
  3663. // 全年截取一部分
  3664. if newDate.Before(startDate.AddDate(0, 0, 1)) && newDate.After(endDate) {
  3665. continue
  3666. }
  3667. if newDate.After(startDate.AddDate(0, 0, -1)) {
  3668. // 减一年
  3669. newDate = dateTime.AddDate(time.Now().Year()-dateTime.Year()-1, 0, 0)
  3670. }
  3671. // 处理上下限列表
  3672. if value, ok := maxValueMap[newDate]; ok {
  3673. if value < handleDataMap[date] {
  3674. maxValueMap[newDate] = handleDataMap[date]
  3675. }
  3676. } else {
  3677. maxValueMap[newDate] = handleDataMap[date]
  3678. }
  3679. if value, ok := minValueMap[newDate]; ok {
  3680. if value > handleDataMap[date] {
  3681. minValueMap[newDate] = handleDataMap[date]
  3682. }
  3683. } else {
  3684. minValueMap[newDate] = handleDataMap[date]
  3685. }
  3686. dataTimeMap[newDate] = newDate
  3687. } else {
  3688. // 如果跨年且大于等于一年
  3689. // double后截取
  3690. if newDate.After(startDate) {
  3691. // 处理上下限列表
  3692. if value, ok := maxValueMap[newDate]; ok {
  3693. if value < handleDataMap[date] {
  3694. maxValueMap[newDate] = handleDataMap[date]
  3695. }
  3696. } else {
  3697. maxValueMap[newDate] = handleDataMap[date]
  3698. }
  3699. if value, ok := minValueMap[newDate]; ok {
  3700. if value > handleDataMap[date] {
  3701. minValueMap[newDate] = handleDataMap[date]
  3702. }
  3703. } else {
  3704. minValueMap[newDate] = handleDataMap[date]
  3705. }
  3706. dataTimeMap[newDate] = newDate
  3707. }
  3708. newDate = dateTime.AddDate(time.Now().Year()-dateTime.Year()+1, 0, 0)
  3709. newEndDate := endDate.AddDate(1, 0, 0)
  3710. if newDate.Before(newEndDate) {
  3711. // 处理上下限列表
  3712. if value, ok := maxValueMap[newDate]; ok {
  3713. if value < handleDataMap[date] {
  3714. maxValueMap[newDate] = handleDataMap[date]
  3715. }
  3716. } else {
  3717. maxValueMap[newDate] = handleDataMap[date]
  3718. }
  3719. if value, ok := minValueMap[newDate]; ok {
  3720. if value > handleDataMap[date] {
  3721. minValueMap[newDate] = handleDataMap[date]
  3722. }
  3723. } else {
  3724. minValueMap[newDate] = handleDataMap[date]
  3725. }
  3726. dataTimeMap[newDate] = newDate
  3727. }
  3728. }
  3729. } else {
  3730. // 如果不跨年 正常获取
  3731. // 获取当前日期所在区间
  3732. // 处理上下限列表
  3733. if value, ok := maxValueMap[newDate]; ok {
  3734. if value < handleDataMap[date] {
  3735. maxValueMap[newDate] = handleDataMap[date]
  3736. }
  3737. } else {
  3738. maxValueMap[newDate] = handleDataMap[date]
  3739. }
  3740. if value, ok := minValueMap[newDate]; ok {
  3741. if value > handleDataMap[date] {
  3742. minValueMap[newDate] = handleDataMap[date]
  3743. }
  3744. } else {
  3745. minValueMap[newDate] = handleDataMap[date]
  3746. }
  3747. dataTimeMap[newDate] = newDate
  3748. }
  3749. }
  3750. } else {
  3751. // 旬度、月度、季度、半年度 不插值,需要先把日期列表和数据map取出来
  3752. for _, vv := range v.DataList {
  3753. dateTime, e := time.Parse(utils.FormatDate, vv.DataTime)
  3754. if e != nil {
  3755. err = errors.New("时间格式化异常, Err:" + e.Error())
  3756. return
  3757. }
  3758. // 不包含当年
  3759. if v.ChartLegend == strconv.Itoa(time.Now().Year()) {
  3760. continue
  3761. }
  3762. if dateTime.Year() < startYear {
  3763. continue
  3764. }
  3765. // 农历时dataTimeList的年份为最新年份,图例时间的年份才是真实年份
  3766. chartLegend, _ := strconv.Atoi(v.ChartLegend)
  3767. if chartLegend < startYear {
  3768. continue
  3769. }
  3770. // 月度的2月29号日期改为2月28日
  3771. if dateTime.Month() == 2 && dateTime.Day() == 29 {
  3772. dateTime = dateTime.AddDate(0, 0, -1)
  3773. }
  3774. newDate = dateTime.AddDate(time.Now().Year()-dateTime.Year(), 0, 0)
  3775. if seasonConfig.JumpYear == 1 {
  3776. if startDate.After(endDate) {
  3777. // 如果跨年且不到一年
  3778. // 全年截取一部分
  3779. if newDate.Before(startDate.AddDate(0, 0, 1)) && newDate.After(endDate) {
  3780. continue
  3781. }
  3782. if newDate.After(startDate.AddDate(0, 0, -1)) {
  3783. // 减一年
  3784. newDate = dateTime.AddDate(time.Now().Year()-dateTime.Year()-1, 0, 0)
  3785. }
  3786. // 处理上下限列表
  3787. if value, ok := maxValueMap[newDate]; ok {
  3788. if value < vv.Value {
  3789. maxValueMap[newDate] = vv.Value
  3790. }
  3791. } else {
  3792. maxValueMap[newDate] = vv.Value
  3793. }
  3794. if value, ok := minValueMap[newDate]; ok {
  3795. if value > vv.Value {
  3796. minValueMap[newDate] = vv.Value
  3797. }
  3798. } else {
  3799. minValueMap[newDate] = vv.Value
  3800. }
  3801. dataTimeMap[newDate] = newDate
  3802. } else {
  3803. // 如果跨年且大于等于一年
  3804. // double后截取
  3805. if newDate.After(startDate) {
  3806. // 处理上下限列表
  3807. if value, ok := maxValueMap[newDate]; ok {
  3808. if value < vv.Value {
  3809. maxValueMap[newDate] = vv.Value
  3810. }
  3811. } else {
  3812. maxValueMap[newDate] = vv.Value
  3813. }
  3814. if value, ok := minValueMap[newDate]; ok {
  3815. if value > vv.Value {
  3816. minValueMap[newDate] = vv.Value
  3817. }
  3818. } else {
  3819. minValueMap[newDate] = vv.Value
  3820. }
  3821. dataTimeMap[newDate] = newDate
  3822. }
  3823. newDate = dateTime.AddDate(time.Now().Year()-dateTime.Year()+1, 0, 0)
  3824. newEndDate := endDate.AddDate(1, 0, 0)
  3825. if newDate.Before(newEndDate) {
  3826. // 处理上下限列表
  3827. if value, ok := maxValueMap[newDate]; ok {
  3828. if value < vv.Value {
  3829. maxValueMap[newDate] = vv.Value
  3830. }
  3831. } else {
  3832. maxValueMap[newDate] = vv.Value
  3833. }
  3834. if value, ok := minValueMap[newDate]; ok {
  3835. if value > vv.Value {
  3836. minValueMap[newDate] = vv.Value
  3837. }
  3838. } else {
  3839. minValueMap[newDate] = vv.Value
  3840. }
  3841. dataTimeMap[newDate] = newDate
  3842. }
  3843. }
  3844. } else {
  3845. // 如果不跨年 正常获取
  3846. // 获取当前日期所在区间
  3847. // 处理上下限列表
  3848. if value, ok := maxValueMap[newDate]; ok {
  3849. if value < vv.Value {
  3850. maxValueMap[newDate] = vv.Value
  3851. }
  3852. } else {
  3853. maxValueMap[newDate] = vv.Value
  3854. }
  3855. if value, ok := minValueMap[newDate]; ok {
  3856. if value > vv.Value {
  3857. minValueMap[newDate] = vv.Value
  3858. }
  3859. } else {
  3860. minValueMap[newDate] = vv.Value
  3861. }
  3862. dataTimeMap[newDate] = newDate
  3863. }
  3864. }
  3865. }
  3866. }
  3867. for _, v := range dataTimeMap {
  3868. maxMinItem := &data_manage.MaxMinLimitsData{}
  3869. if maxValue, ok := maxValueMap[v]; ok {
  3870. maxMinItem.MaxValue = maxValue
  3871. } else {
  3872. maxMinItem.MaxValue = minValueMap[v]
  3873. }
  3874. if minValue, ok := minValueMap[v]; ok {
  3875. maxMinItem.MinValue = minValue
  3876. } else {
  3877. maxMinItem.MinValue = maxValueMap[v]
  3878. }
  3879. maxMinItem.DataTime = v.Format(utils.FormatDate)
  3880. maxMinItem.DataTimestamp = v.UnixNano() / 1e6
  3881. maxMinDataList = append(maxMinDataList, maxMinItem)
  3882. }
  3883. // 排序
  3884. sort.Slice(maxMinDataList, func(i, j int) bool {
  3885. return maxMinDataList[i].DataTime < maxMinDataList[j].DataTime
  3886. })
  3887. dataResp.MaxMinLimits.List = maxMinDataList
  3888. dataResp.MaxMinLimits.Color = seasonConfig.MaxMinLimits.Color
  3889. dataResp.MaxMinLimits.Legend = seasonConfig.MaxMinLimits.Legend
  3890. dataResp.MaxMinLimits.IsShow = seasonConfig.MaxMinLimits.IsShow
  3891. dataResp.MaxMinLimits.IsAdd = seasonConfig.MaxMinLimits.IsAdd
  3892. dataResp.MaxMinLimits.Year = seasonConfig.MaxMinLimits.Year
  3893. }
  3894. // 自定义同期均线
  3895. if seasonConfig.SamePeriodAverage.Year > 0 {
  3896. handleDataMap := make(map[string]float64)
  3897. dataTimeMap := make(map[time.Time]time.Time)
  3898. dataTimeList := make([]string, 0)
  3899. valueMap := make(map[time.Time]float64)
  3900. averageDataList := make([]*data_manage.SamePeriodAverageData, 0)
  3901. dateNumMap := make(map[time.Time]float64)
  3902. for i := len(quarterDataList) - 1; i >= 0; i-- {
  3903. // 插值成日度
  3904. dataTimeList, _, err = HandleDataByLinearRegressionToList(quarterDataList[i].DataList, handleDataMap)
  3905. if err != nil {
  3906. err = errors.New("插值处理数据异常, Err:" + err.Error())
  3907. return
  3908. }
  3909. for _, date := range dataTimeList {
  3910. dateTime, e := time.Parse(utils.FormatDate, date)
  3911. if e != nil {
  3912. err = errors.New("时间格式化异常, Err:" + e.Error())
  3913. return
  3914. }
  3915. startYear := time.Now().AddDate(-seasonConfig.SamePeriodAverage.Year, 0, 0).Year()
  3916. if dateTime.Year() < startYear {
  3917. continue
  3918. }
  3919. // 农历时dataTimeList的年份为最新年份,图例时间的年份才是真实年份
  3920. chartLegend, _ := strconv.Atoi(quarterDataList[i].ChartLegend)
  3921. if chartLegend < startYear {
  3922. continue
  3923. }
  3924. // 不包含2月29号
  3925. if dateTime.Month() == 2 && dateTime.Day() == 29 {
  3926. continue
  3927. }
  3928. // 不包含当年
  3929. if quarterDataList[i].ChartLegend == strconv.Itoa(time.Now().Year()) {
  3930. continue
  3931. }
  3932. newDate := dateTime.AddDate(time.Now().Year()-dateTime.Year(), 0, 0)
  3933. // 处理均值
  3934. if value, ok := valueMap[newDate]; ok {
  3935. valueMap[newDate] = handleDataMap[date] + value
  3936. } else {
  3937. valueMap[newDate] = handleDataMap[date]
  3938. }
  3939. dateNumMap[newDate] += 1
  3940. dataTimeMap[newDate] = newDate
  3941. }
  3942. }
  3943. //year := float64(seasonConfig.SamePeriodAverage.Year)
  3944. for _, v := range dataTimeMap {
  3945. averageItem := &data_manage.SamePeriodAverageData{}
  3946. year := dateNumMap[v]
  3947. if value, ok := valueMap[v]; ok {
  3948. if year > 0 {
  3949. averageItem.Value = value / year
  3950. } else {
  3951. averageItem.Value = value
  3952. }
  3953. }
  3954. averageItem.DataTime = v.Format(utils.FormatDate)
  3955. averageItem.DataTimestamp = v.UnixNano() / 1e6
  3956. averageDataList = append(averageDataList, averageItem)
  3957. }
  3958. // 排序
  3959. sort.Slice(averageDataList, func(i, j int) bool {
  3960. return averageDataList[i].DataTime < averageDataList[j].DataTime
  3961. })
  3962. dataResp.SamePeriodAverage.List = averageDataList
  3963. dataResp.SamePeriodAverage.Year = seasonConfig.SamePeriodAverage.Year
  3964. dataResp.SamePeriodAverage.Color = seasonConfig.SamePeriodAverage.Color
  3965. dataResp.SamePeriodAverage.Legend = seasonConfig.SamePeriodAverage.Legend
  3966. dataResp.SamePeriodAverage.IsShow = seasonConfig.SamePeriodAverage.IsShow
  3967. dataResp.SamePeriodAverage.LineType = seasonConfig.SamePeriodAverage.LineType
  3968. dataResp.SamePeriodAverage.LineWidth = seasonConfig.SamePeriodAverage.LineWidth
  3969. dataResp.SamePeriodAverage.IsAdd = seasonConfig.SamePeriodAverage.IsAdd
  3970. }
  3971. // 自定义同期标准差
  3972. if seasonConfig.SamePeriodStandardDeviation.Year > 1 && seasonConfig.SamePeriodStandardDeviation.Multiple > 0 {
  3973. startYear := time.Now().AddDate(-seasonConfig.SamePeriodStandardDeviation.Year, 0, 0).Year()
  3974. // 先算均值,再算标准差
  3975. handleDataMap := make(map[string]float64)
  3976. dataTimeMap := make(map[time.Time]time.Time)
  3977. dataTimeValueMap := make(map[time.Time][]float64)
  3978. dataTimeList := make([]string, 0)
  3979. valueMap := make(map[time.Time]float64)
  3980. samePeriodStandardDeviationList := make([]*data_manage.MaxMinLimitsData, 0)
  3981. for i := len(quarterDataList) - 1; i > len(quarterDataList)-seasonConfig.SamePeriodStandardDeviation.Year-1 && i > 0; i-- {
  3982. // 插值成日度
  3983. dataTimeList, _, err = HandleDataByLinearRegressionToListV2(quarterDataList[i].DataList, handleDataMap)
  3984. if err != nil {
  3985. err = errors.New("插值处理数据异常, Err:" + err.Error())
  3986. return
  3987. }
  3988. for _, date := range dataTimeList {
  3989. dateTime, e := time.Parse(utils.FormatDate, date)
  3990. if e != nil {
  3991. err = errors.New("时间格式化异常, Err:" + e.Error())
  3992. return
  3993. }
  3994. if dateTime.Year() < startYear {
  3995. continue
  3996. }
  3997. // 农历时dataTimeList的年份为最新年份,图例时间的年份才是真实年份
  3998. chartLegend, _ := strconv.Atoi(quarterDataList[i].ChartLegend)
  3999. if chartLegend < startYear {
  4000. continue
  4001. }
  4002. // 不包含2月29号
  4003. if dateTime.Month() == 2 && dateTime.Day() == 29 {
  4004. continue
  4005. }
  4006. newDate := dateTime.AddDate(time.Now().Year()-dateTime.Year(), 0, 0)
  4007. // 处理均值
  4008. if value, ok := valueMap[newDate]; ok {
  4009. valueMap[newDate] = (handleDataMap[date] + value) / 2
  4010. } else {
  4011. valueMap[newDate] = handleDataMap[date]
  4012. }
  4013. dataTimeMap[newDate] = newDate
  4014. valueList := dataTimeValueMap[newDate]
  4015. valueList = append(valueList, handleDataMap[date])
  4016. dataTimeValueMap[newDate] = valueList
  4017. }
  4018. }
  4019. for _, v := range dataTimeMap {
  4020. valueList := dataTimeValueMap[v]
  4021. stdev := utils.CalculateStandardDeviation(valueList)
  4022. stdev, _ = decimal.NewFromFloat(stdev).Round(4).Float64()
  4023. maxMinItem := &data_manage.MaxMinLimitsData{}
  4024. if value, ok := valueMap[v]; ok {
  4025. maxMinItem.MaxValue = value + stdev*seasonConfig.SamePeriodStandardDeviation.Multiple
  4026. maxMinItem.MinValue = value - stdev*seasonConfig.SamePeriodStandardDeviation.Multiple
  4027. }
  4028. maxMinItem.DataTime = v.Format(utils.FormatDate)
  4029. maxMinItem.DataTimestamp = v.UnixNano() / 1e6
  4030. samePeriodStandardDeviationList = append(samePeriodStandardDeviationList, maxMinItem)
  4031. }
  4032. // 排序
  4033. sort.Slice(samePeriodStandardDeviationList, func(i, j int) bool {
  4034. return samePeriodStandardDeviationList[i].DataTime < samePeriodStandardDeviationList[j].DataTime
  4035. })
  4036. dataResp.SamePeriodStandardDeviation.List = samePeriodStandardDeviationList
  4037. dataResp.SamePeriodStandardDeviation.Color = seasonConfig.SamePeriodStandardDeviation.Color
  4038. dataResp.SamePeriodStandardDeviation.Legend = seasonConfig.SamePeriodStandardDeviation.Legend
  4039. dataResp.SamePeriodStandardDeviation.IsShow = seasonConfig.SamePeriodStandardDeviation.IsShow
  4040. dataResp.SamePeriodStandardDeviation.Multiple = seasonConfig.SamePeriodStandardDeviation.Multiple
  4041. dataResp.SamePeriodStandardDeviation.Year = seasonConfig.SamePeriodStandardDeviation.Year
  4042. dataResp.SamePeriodStandardDeviation.IsAdd = seasonConfig.SamePeriodStandardDeviation.IsAdd
  4043. }
  4044. // 自定义右轴
  4045. if seasonConfig.RightAxis.IndicatorType != 0 {
  4046. if seasonConfig.RightAxis.IndicatorType == 1 {
  4047. startTime, _ := time.Parse(utils.FormatDate, mappingItem.StartDate)
  4048. for i := len(quarterDataList) - 1; i > len(quarterDataList)-2 && i > 0; i-- {
  4049. var rightMappingItem data_manage.ChartEdbInfoMapping
  4050. rightMappingItem = *mappingItem
  4051. // 计算同比值
  4052. tbzDataList, minValue, maxValue, e := GetEdbDataTbzForSeason(mappingItem.Frequency, quarterDataList[i].DataList, startTime)
  4053. if e != nil {
  4054. err = errors.New("计算同比值失败, Err:" + e.Error())
  4055. return
  4056. }
  4057. rightMappingItem.DataList = tbzDataList
  4058. rightMappingItem.MaxData = maxValue
  4059. rightMappingItem.MinData = minValue
  4060. dataResp.RightAxis.EdbInfoList = append(dataResp.RightAxis.EdbInfoList, &rightMappingItem)
  4061. }
  4062. }
  4063. dataResp.RightAxis.SeasonRightAxis = seasonConfig.RightAxis
  4064. }
  4065. }
  4066. return
  4067. }
  4068. // 计算百分位对应的值
  4069. func PercentileAlgorithm(x float64, data []float64) float64 {
  4070. N := float64(len(data))
  4071. n := (x / 100) * (N - 1)
  4072. // 如果n是整数,则直接返回第n个数值
  4073. if n == float64(int(n)) {
  4074. return data[int(n)-1]
  4075. }
  4076. // 如果n是小数,执行插值
  4077. nInt := int(n)
  4078. e := n - float64(nInt)
  4079. // 取出相邻的两个数值
  4080. Sn := data[nInt-1]
  4081. Sn1 := data[nInt]
  4082. // 计算插值结果
  4083. y := Sn + e*(Sn1-Sn)
  4084. return y
  4085. }
  4086. func MarkerLineCalculate(markerLine data_manage.MarkersLine, dataList interface{}, chartInfo *data_manage.ChartInfoView) (value string, err error) {
  4087. if markerLine.Calculation == 1 {
  4088. // 区间均值
  4089. averge := 0.0
  4090. length := 0
  4091. // 计算左轴
  4092. if chartInfo.ChartType == 2 && markerLine.EdbType == 0 {
  4093. //季节性图结构体不一样
  4094. quarterDataList := dataList.(data_manage.QuarterDataList)
  4095. for _, quarterData := range quarterDataList[len(quarterDataList)-1:] {
  4096. for _, vv := range quarterData.DataList {
  4097. if markerLine.TimeIntervalType == 1 {
  4098. startDate := markerLine.StartDate.Date
  4099. endDate := time.Now().Format(utils.FormatDate)
  4100. if markerLine.StartDate.TimeType == 2 {
  4101. // 动态
  4102. if markerLine.StartDate.Conf.BaseDate == 1 {
  4103. // 指标最新日期
  4104. startDate = quarterData.DataList[len(quarterData.DataList)-1].DataTime
  4105. } else {
  4106. // 系统日期
  4107. startDate = time.Now().Format(utils.FormatDate)
  4108. }
  4109. startDate, err = HandleDateChange(startDate, markerLine.StartDate.Conf)
  4110. }
  4111. if markerLine.EndDate.TimeType == 1 {
  4112. // 固定
  4113. endDate = markerLine.EndDate.Date
  4114. } else if markerLine.EndDate.TimeType == 2 {
  4115. // 动态
  4116. if markerLine.StartDate.Conf.BaseDate == 1 {
  4117. // 指标最新日期
  4118. endDate = quarterData.DataList[len(quarterData.DataList)-1].DataTime
  4119. } else {
  4120. // 系统日期
  4121. endDate = time.Now().Format(utils.FormatDate)
  4122. }
  4123. endDate, err = HandleDateChange(endDate, markerLine.StartDate.Conf)
  4124. }
  4125. if vv.DataTime >= startDate && vv.DataTime <= endDate {
  4126. averge += vv.Value
  4127. length += 1
  4128. }
  4129. } else {
  4130. averge += vv.Value
  4131. length += 1
  4132. }
  4133. }
  4134. averge = averge / float64(length)
  4135. value = fmt.Sprintf("%.2f", averge)
  4136. }
  4137. } else {
  4138. dataList := dataList.([]*data_manage.EdbDataList)
  4139. for _, dataItem := range dataList {
  4140. if markerLine.TimeIntervalType == 1 {
  4141. startDate := markerLine.StartDate.Date
  4142. endDate := time.Now().Format(utils.FormatDate)
  4143. if markerLine.StartDate.TimeType == 2 {
  4144. // 动态
  4145. if markerLine.StartDate.Conf.BaseDate == 1 {
  4146. // 指标最新日期
  4147. startDate = dataList[len(dataList)-1].DataTime
  4148. } else {
  4149. // 系统日期
  4150. startDate = time.Now().Format(utils.FormatDate)
  4151. }
  4152. startDate, err = HandleDateChange(startDate, markerLine.StartDate.Conf)
  4153. }
  4154. if markerLine.EndDate.TimeType == 1 {
  4155. // 固定
  4156. endDate = markerLine.EndDate.Date
  4157. } else if markerLine.EndDate.TimeType == 2 {
  4158. // 动态
  4159. if markerLine.StartDate.Conf.BaseDate == 1 {
  4160. // 指标最新日期
  4161. endDate = dataList[len(dataList)-1].DataTime
  4162. } else {
  4163. // 系统日期
  4164. endDate = time.Now().Format(utils.FormatDate)
  4165. }
  4166. endDate, err = HandleDateChange(endDate, markerLine.StartDate.Conf)
  4167. }
  4168. if dataItem.DataTime >= startDate && dataItem.DataTime <= endDate {
  4169. averge += dataItem.Value
  4170. length += 1
  4171. }
  4172. } else {
  4173. averge += dataItem.Value
  4174. length += 1
  4175. }
  4176. }
  4177. averge = averge / float64(length)
  4178. value = fmt.Sprintf("%.2f", averge)
  4179. }
  4180. } else if markerLine.Calculation == 2 {
  4181. // 区间均值加N倍标准差
  4182. averge := 0.0
  4183. length := 0
  4184. // 计算左轴
  4185. if chartInfo.ChartType == 2 && markerLine.EdbType == 0 {
  4186. //季节性图结构体不一样
  4187. faloatList := make([]float64, 0)
  4188. quarterDataList := dataList.(data_manage.QuarterDataList)
  4189. for _, quarterData := range quarterDataList[len(quarterDataList)-1:] {
  4190. for _, vv := range quarterData.DataList {
  4191. if markerLine.TimeIntervalType == 1 {
  4192. startDate := markerLine.StartDate.Date
  4193. endDate := time.Now().Format(utils.FormatDate)
  4194. if markerLine.StartDate.TimeType == 2 {
  4195. // 动态
  4196. if markerLine.StartDate.Conf.BaseDate == 1 {
  4197. // 指标最新日期
  4198. startDate = quarterData.DataList[len(quarterData.DataList)-1].DataTime
  4199. } else {
  4200. // 系统日期
  4201. startDate = time.Now().Format(utils.FormatDate)
  4202. }
  4203. startDate, err = HandleDateChange(startDate, markerLine.StartDate.Conf)
  4204. }
  4205. if markerLine.EndDate.TimeType == 1 {
  4206. // 固定
  4207. endDate = markerLine.EndDate.Date
  4208. } else if markerLine.EndDate.TimeType == 2 {
  4209. // 动态
  4210. if markerLine.StartDate.Conf.BaseDate == 1 {
  4211. // 指标最新日期
  4212. endDate = quarterData.DataList[len(quarterData.DataList)-1].DataTime
  4213. } else {
  4214. // 系统日期
  4215. endDate = time.Now().Format(utils.FormatDate)
  4216. }
  4217. endDate, err = HandleDateChange(endDate, markerLine.StartDate.Conf)
  4218. }
  4219. if vv.DataTime >= startDate && vv.DataTime <= endDate {
  4220. faloatList = append(faloatList, vv.Value)
  4221. averge += vv.Value
  4222. length += 1
  4223. }
  4224. } else {
  4225. faloatList = append(faloatList, vv.Value)
  4226. averge += vv.Value
  4227. length += 1
  4228. }
  4229. }
  4230. averge = averge / float64(length)
  4231. stdev := utils.CalculateStandardDeviation(faloatList)
  4232. stdev, _ = decimal.NewFromFloat(stdev).Round(4).Float64()
  4233. value = fmt.Sprintf("%.2f", averge+stdev*markerLine.CalculationValue)
  4234. }
  4235. } else {
  4236. dataList := dataList.([]*data_manage.EdbDataList)
  4237. floatList := make([]float64, 0)
  4238. for _, dataItem := range dataList {
  4239. if markerLine.TimeIntervalType == 1 {
  4240. startDate := markerLine.StartDate.Date
  4241. endDate := time.Now().Format(utils.FormatDate)
  4242. if markerLine.StartDate.TimeType == 2 {
  4243. // 动态
  4244. if markerLine.StartDate.Conf.BaseDate == 1 {
  4245. // 指标最新日期
  4246. startDate = dataList[len(dataList)-1].DataTime
  4247. } else {
  4248. // 系统日期
  4249. startDate = time.Now().Format(utils.FormatDate)
  4250. }
  4251. startDate, err = HandleDateChange(startDate, markerLine.StartDate.Conf)
  4252. }
  4253. if markerLine.EndDate.TimeType == 1 {
  4254. // 固定
  4255. endDate = markerLine.EndDate.Date
  4256. } else if markerLine.EndDate.TimeType == 2 {
  4257. // 动态
  4258. if markerLine.StartDate.Conf.BaseDate == 1 {
  4259. // 指标最新日期
  4260. endDate = dataList[len(dataList)-1].DataTime
  4261. } else {
  4262. // 系统日期
  4263. endDate = time.Now().Format(utils.FormatDate)
  4264. }
  4265. endDate, err = HandleDateChange(endDate, markerLine.StartDate.Conf)
  4266. }
  4267. if dataItem.DataTime >= startDate && dataItem.DataTime <= endDate {
  4268. floatList = append(floatList, dataItem.Value)
  4269. averge += dataItem.Value
  4270. length += 1
  4271. }
  4272. } else {
  4273. floatList = append(floatList, dataItem.Value)
  4274. averge += dataItem.Value
  4275. length += 1
  4276. }
  4277. }
  4278. averge = averge / float64(length)
  4279. stdev := utils.CalculateStandardDeviation(floatList)
  4280. stdev, _ = decimal.NewFromFloat(stdev).Round(4).Float64()
  4281. value = fmt.Sprintf("%.2f", averge+stdev*markerLine.CalculationValue)
  4282. }
  4283. } else if markerLine.Calculation == 3 {
  4284. // 区间个数分位
  4285. markerLineValue := 0.0
  4286. if chartInfo.ChartType == 2 && markerLine.EdbType == 0 {
  4287. //季节性图结构体不一样
  4288. faloatList := make([]float64, 0)
  4289. quarterDataList := dataList.(data_manage.QuarterDataList)
  4290. for _, quarterData := range quarterDataList[len(quarterDataList)-1:] {
  4291. for _, vv := range quarterData.DataList {
  4292. if markerLine.TimeIntervalType == 1 {
  4293. startDate := markerLine.StartDate.Date
  4294. endDate := time.Now().Format(utils.FormatDate)
  4295. if markerLine.StartDate.TimeType == 2 {
  4296. // 动态
  4297. if markerLine.StartDate.Conf.BaseDate == 1 {
  4298. // 指标最新日期
  4299. startDate = quarterData.DataList[len(quarterData.DataList)-1].DataTime
  4300. } else {
  4301. // 系统日期
  4302. startDate = time.Now().Format(utils.FormatDate)
  4303. }
  4304. startDate, err = HandleDateChange(startDate, markerLine.StartDate.Conf)
  4305. }
  4306. if markerLine.EndDate.TimeType == 1 {
  4307. // 固定
  4308. endDate = markerLine.EndDate.Date
  4309. } else if markerLine.EndDate.TimeType == 2 {
  4310. // 动态
  4311. if markerLine.StartDate.Conf.BaseDate == 1 {
  4312. // 指标最新日期
  4313. endDate = quarterData.DataList[len(quarterData.DataList)-1].DataTime
  4314. } else {
  4315. // 系统日期
  4316. endDate = time.Now().Format(utils.FormatDate)
  4317. }
  4318. endDate, err = HandleDateChange(endDate, markerLine.StartDate.Conf)
  4319. }
  4320. if vv.DataTime >= startDate && vv.DataTime <= endDate {
  4321. faloatList = append(faloatList, vv.Value)
  4322. }
  4323. } else {
  4324. faloatList = append(faloatList, vv.Value)
  4325. }
  4326. }
  4327. sort.Float64s(faloatList)
  4328. markerLineValue = PercentileAlgorithm(markerLine.CalculationValue, faloatList)
  4329. value = fmt.Sprintf("%.2f", markerLineValue)
  4330. }
  4331. } else {
  4332. dataList := dataList.([]*data_manage.EdbDataList)
  4333. floatList := make([]float64, 0)
  4334. for _, dataItem := range dataList {
  4335. if markerLine.TimeIntervalType == 1 {
  4336. startDate := markerLine.StartDate.Date
  4337. endDate := time.Now().Format(utils.FormatDate)
  4338. if markerLine.StartDate.TimeType == 2 {
  4339. // 动态
  4340. if markerLine.StartDate.Conf.BaseDate == 1 {
  4341. // 指标最新日期
  4342. startDate = dataList[len(dataList)-1].DataTime
  4343. } else {
  4344. // 系统日期
  4345. startDate = time.Now().Format(utils.FormatDate)
  4346. }
  4347. startDate, err = HandleDateChange(startDate, markerLine.StartDate.Conf)
  4348. }
  4349. if markerLine.EndDate.TimeType == 1 {
  4350. // 固定
  4351. endDate = markerLine.EndDate.Date
  4352. } else if markerLine.EndDate.TimeType == 2 {
  4353. // 动态
  4354. if markerLine.StartDate.Conf.BaseDate == 1 {
  4355. // 指标最新日期
  4356. endDate = dataList[len(dataList)-1].DataTime
  4357. } else {
  4358. // 系统日期
  4359. endDate = time.Now().Format(utils.FormatDate)
  4360. }
  4361. endDate, err = HandleDateChange(endDate, markerLine.StartDate.Conf)
  4362. }
  4363. if dataItem.DataTime >= startDate && dataItem.DataTime <= endDate {
  4364. floatList = append(floatList, dataItem.Value)
  4365. }
  4366. } else {
  4367. floatList = append(floatList, dataItem.Value)
  4368. }
  4369. }
  4370. sort.Float64s(floatList)
  4371. markerLineValue = PercentileAlgorithm(markerLine.CalculationValue, floatList)
  4372. value = fmt.Sprintf("%.2f", markerLineValue)
  4373. }
  4374. } else if markerLine.Calculation == 4 {
  4375. // 数值分位
  4376. markerLineValue := 0.0
  4377. maxValue := 0.0
  4378. minValue := 0.0
  4379. if chartInfo.ChartType == 2 && markerLine.EdbType == 0 {
  4380. //季节性图结构体不一样
  4381. quarterDataList := dataList.(data_manage.QuarterDataList)
  4382. for _, quarterData := range quarterDataList[len(quarterDataList)-1:] {
  4383. for _, vv := range quarterData.DataList {
  4384. if markerLine.TimeIntervalType == 1 {
  4385. startDate := markerLine.StartDate.Date
  4386. endDate := time.Now().Format(utils.FormatDate)
  4387. if markerLine.StartDate.TimeType == 2 {
  4388. // 动态
  4389. if markerLine.StartDate.Conf.BaseDate == 1 {
  4390. // 指标最新日期
  4391. startDate = quarterData.DataList[len(quarterData.DataList)-1].DataTime
  4392. } else {
  4393. // 系统日期
  4394. startDate = time.Now().Format(utils.FormatDate)
  4395. }
  4396. startDate, err = HandleDateChange(startDate, markerLine.StartDate.Conf)
  4397. }
  4398. if markerLine.EndDate.TimeType == 1 {
  4399. // 固定
  4400. endDate = markerLine.EndDate.Date
  4401. } else if markerLine.EndDate.TimeType == 2 {
  4402. // 动态
  4403. if markerLine.StartDate.Conf.BaseDate == 1 {
  4404. // 指标最新日期
  4405. endDate = quarterData.DataList[len(quarterData.DataList)-1].DataTime
  4406. } else {
  4407. // 系统日期
  4408. endDate = time.Now().Format(utils.FormatDate)
  4409. }
  4410. endDate, err = HandleDateChange(endDate, markerLine.StartDate.Conf)
  4411. }
  4412. if vv.DataTime >= startDate && vv.DataTime <= endDate {
  4413. if maxValue < vv.Value {
  4414. maxValue = vv.Value
  4415. }
  4416. if minValue > vv.Value {
  4417. minValue = vv.Value
  4418. }
  4419. }
  4420. } else {
  4421. if maxValue < vv.Value {
  4422. maxValue = vv.Value
  4423. }
  4424. if minValue > vv.Value {
  4425. minValue = vv.Value
  4426. }
  4427. }
  4428. }
  4429. markerLineValue = CalculatePercentile(markerLine.CalculationValue, minValue, maxValue)
  4430. value = fmt.Sprintf("%.2f", markerLineValue)
  4431. }
  4432. } else {
  4433. dataList := dataList.([]*data_manage.EdbDataList)
  4434. for _, dataItem := range dataList {
  4435. if markerLine.TimeIntervalType == 1 {
  4436. startDate := markerLine.StartDate.Date
  4437. endDate := time.Now().Format(utils.FormatDate)
  4438. if markerLine.StartDate.TimeType == 2 {
  4439. // 动态
  4440. if markerLine.StartDate.Conf.BaseDate == 1 {
  4441. // 指标最新日期
  4442. startDate = dataList[len(dataList)-1].DataTime
  4443. } else {
  4444. // 系统日期
  4445. startDate = time.Now().Format(utils.FormatDate)
  4446. }
  4447. startDate, err = HandleDateChange(startDate, markerLine.StartDate.Conf)
  4448. }
  4449. if markerLine.EndDate.TimeType == 1 {
  4450. // 固定
  4451. endDate = markerLine.EndDate.Date
  4452. } else if markerLine.EndDate.TimeType == 2 {
  4453. // 动态
  4454. if markerLine.StartDate.Conf.BaseDate == 1 {
  4455. // 指标最新日期
  4456. endDate = dataList[len(dataList)-1].DataTime
  4457. } else {
  4458. // 系统日期
  4459. endDate = time.Now().Format(utils.FormatDate)
  4460. }
  4461. endDate, err = HandleDateChange(endDate, markerLine.StartDate.Conf)
  4462. }
  4463. if dataItem.DataTime >= startDate && dataItem.DataTime <= endDate {
  4464. if maxValue < dataItem.Value {
  4465. maxValue = dataItem.Value
  4466. }
  4467. if minValue > dataItem.Value {
  4468. minValue = dataItem.Value
  4469. }
  4470. }
  4471. } else {
  4472. if maxValue < dataItem.Value {
  4473. maxValue = dataItem.Value
  4474. }
  4475. if minValue > dataItem.Value {
  4476. minValue = dataItem.Value
  4477. }
  4478. }
  4479. }
  4480. markerLineValue = CalculatePercentile(markerLine.CalculationValue, minValue, maxValue)
  4481. value = fmt.Sprintf("%.2f", markerLineValue)
  4482. }
  4483. }
  4484. return
  4485. }
  4486. // HandleDateChange 处理日期变换
  4487. func HandleDateChange(date string, edbDateConf data_manage.EdbDateChangeConf) (newDate string, err error) {
  4488. newDate = date
  4489. if newDate != "" {
  4490. if len(edbDateConf.DateChange) > 0 {
  4491. var dateTime time.Time
  4492. dateTime, err = time.ParseInLocation(utils.FormatDate, newDate, time.Local)
  4493. if err != nil {
  4494. err = fmt.Errorf("日期解析失败: %s", err.Error())
  4495. return
  4496. }
  4497. for _, v := range edbDateConf.DateChange {
  4498. if v.ChangeType == 1 {
  4499. dateTime = dateTime.AddDate(v.Year, v.Month, v.Day)
  4500. newDate = dateTime.Format(utils.FormatDate)
  4501. } else if v.ChangeType == 2 {
  4502. newDate, err, _ = handleSystemAppointDateT2(dateTime, v.FrequencyDay, v.Frequency)
  4503. if err != nil {
  4504. return
  4505. }
  4506. dateTime, err = time.ParseInLocation(utils.FormatDate, newDate, time.Local)
  4507. if err != nil {
  4508. err = fmt.Errorf("日期解析失败: %s", err.Error())
  4509. return
  4510. }
  4511. }
  4512. }
  4513. }
  4514. }
  4515. return
  4516. }
  4517. // handleSystemAppointDateT
  4518. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  4519. // @author: Roc
  4520. // @datetime2023-10-27 09:31:35
  4521. // @param Frequency string
  4522. // @param Day string
  4523. // @return date string
  4524. // @return err error
  4525. // @return errMsg string
  4526. func handleSystemAppointDateT2(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  4527. //currDate := time.Now()
  4528. switch frequency {
  4529. case "本周":
  4530. day := int(currDate.Weekday())
  4531. if day == 0 { // 周日
  4532. day = 7
  4533. }
  4534. num := 0
  4535. switch appointDay {
  4536. case "周一":
  4537. num = 1
  4538. case "周二":
  4539. num = 2
  4540. case "周三":
  4541. num = 3
  4542. case "周四":
  4543. num = 4
  4544. case "周五":
  4545. num = 5
  4546. case "周六":
  4547. num = 6
  4548. case "周日":
  4549. num = 7
  4550. }
  4551. day = num - day
  4552. date = currDate.AddDate(0, 0, day).Format(utils.FormatDate)
  4553. case "本旬":
  4554. day := currDate.Day()
  4555. var tmpDate time.Time
  4556. switch appointDay {
  4557. case "第一天":
  4558. if day <= 10 {
  4559. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  4560. } else if day <= 20 {
  4561. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  4562. } else {
  4563. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  4564. }
  4565. case "最后一天":
  4566. if day <= 10 {
  4567. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  4568. } else if day <= 20 {
  4569. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  4570. } else {
  4571. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  4572. }
  4573. }
  4574. date = tmpDate.Format(utils.FormatDate)
  4575. case "本月":
  4576. var tmpDate time.Time
  4577. switch appointDay {
  4578. case "第一天":
  4579. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  4580. case "最后一天":
  4581. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  4582. }
  4583. date = tmpDate.Format(utils.FormatDate)
  4584. case "本季":
  4585. month := currDate.Month()
  4586. var tmpDate time.Time
  4587. switch appointDay {
  4588. case "第一天":
  4589. if month <= 3 {
  4590. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  4591. } else if month <= 6 {
  4592. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  4593. } else if month <= 9 {
  4594. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  4595. } else {
  4596. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  4597. }
  4598. case "最后一天":
  4599. if month <= 3 {
  4600. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  4601. } else if month <= 6 {
  4602. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  4603. } else if month <= 9 {
  4604. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  4605. } else {
  4606. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  4607. }
  4608. }
  4609. date = tmpDate.Format(utils.FormatDate)
  4610. case "本半年":
  4611. month := currDate.Month()
  4612. var tmpDate time.Time
  4613. switch appointDay {
  4614. case "第一天":
  4615. if month <= 6 {
  4616. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  4617. } else {
  4618. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  4619. }
  4620. case "最后一天":
  4621. if month <= 6 {
  4622. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  4623. } else {
  4624. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  4625. }
  4626. }
  4627. date = tmpDate.Format(utils.FormatDate)
  4628. case "本年":
  4629. var tmpDate time.Time
  4630. switch appointDay {
  4631. case "第一天":
  4632. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  4633. case "最后一天":
  4634. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  4635. }
  4636. date = tmpDate.Format(utils.FormatDate)
  4637. default:
  4638. errMsg = "错误的日期频度:" + frequency
  4639. err = errors.New(errMsg)
  4640. return
  4641. }
  4642. return
  4643. }
  4644. // CalculatePercentile 计算数值分位
  4645. func CalculatePercentile(x float64, min float64, max float64) float64 {
  4646. return (x/100)*(max-min) + min
  4647. }
  4648. // getEdbDataMapListForSeason 获取指标最后的基础数据-插值补充好数据-季节性图用
  4649. func getEdbDataMapListForSeason(chartInfoId, chartType int, calendar, startDate, endDate string, mappingList []*data_manage.ChartEdbInfoMapping, seasonExtraConfig string) (edbDataListMap map[int][]*data_manage.EdbDataList, edbList []*data_manage.ChartEdbInfoMapping, err error) {
  4650. // 指标对应的所有数据
  4651. edbDataListMap = make(map[int][]*data_manage.EdbDataList)
  4652. for _, v := range mappingList {
  4653. //fmt.Println("v:", v.EdbInfoId)
  4654. item := new(data_manage.ChartEdbInfoMapping)
  4655. item.EdbInfoId = v.EdbInfoId
  4656. item.SourceName = v.SourceName
  4657. item.Source = v.Source
  4658. item.EdbCode = v.EdbCode
  4659. item.EdbName = v.EdbName
  4660. item.EdbNameEn = v.EdbNameEn
  4661. item.Frequency = v.Frequency
  4662. item.EdbType = v.EdbType
  4663. item.FrequencyEn = GetFrequencyEn(v.Frequency)
  4664. if v.Unit != `无` {
  4665. item.Unit = v.Unit
  4666. }
  4667. item.UnitEn = v.UnitEn
  4668. item.StartDate = v.StartDate
  4669. item.EndDate = v.EndDate
  4670. item.ModifyTime = v.ModifyTime
  4671. item.EdbInfoCategoryType = v.EdbInfoCategoryType
  4672. item.PredictChartColor = v.PredictChartColor
  4673. item.ClassifyId = v.ClassifyId
  4674. if chartInfoId <= 0 {
  4675. item.IsAxis = 1
  4676. item.LeadValue = 0
  4677. item.LeadUnit = ""
  4678. item.ChartEdbMappingId = 0
  4679. item.ChartInfoId = 0
  4680. item.IsOrder = false
  4681. item.EdbInfoType = 1
  4682. item.ChartStyle = ""
  4683. item.ChartColor = ""
  4684. item.ChartWidth = 0
  4685. item.MaxData = v.MaxValue
  4686. item.MinData = v.MinValue
  4687. } else {
  4688. item.IsAxis = v.IsAxis
  4689. item.EdbInfoType = v.EdbInfoType
  4690. item.LeadValue = v.LeadValue
  4691. item.LeadUnit = v.LeadUnit
  4692. item.LeadUnitEn = GetLeadUnitEn(v.LeadUnit)
  4693. item.ChartEdbMappingId = v.ChartEdbMappingId
  4694. item.ChartInfoId = v.ChartInfoId
  4695. item.ChartStyle = v.ChartStyle
  4696. item.ChartColor = v.ChartColor
  4697. item.ChartWidth = v.ChartWidth
  4698. item.IsOrder = v.IsOrder
  4699. item.MaxData = v.MaxData
  4700. item.MinData = v.MinData
  4701. }
  4702. item.LatestValue = v.LatestValue
  4703. item.LatestDate = v.LatestDate
  4704. item.UniqueCode = v.UniqueCode
  4705. item.MoveLatestDate = v.LatestDate
  4706. item.EdbAliasName = v.EdbAliasName
  4707. item.IsConvert = v.IsConvert
  4708. item.ConvertType = v.ConvertType
  4709. item.ConvertValue = v.ConvertValue
  4710. item.ConvertUnit = v.ConvertUnit
  4711. item.ConvertEnUnit = v.ConvertEnUnit
  4712. item.IsJoinPermission = v.IsJoinPermission
  4713. var startDateReal string
  4714. var diffSeconds int64
  4715. if chartType == 2 { //季节性图
  4716. startDateReal = startDate
  4717. if len(mappingList) > 1 {
  4718. item.IsAxis = v.IsAxis
  4719. }
  4720. } else {
  4721. if v.EdbInfoType == 0 && v.LeadUnit != "" && v.LeadValue > 0 { //领先指标
  4722. var startTimeRealTemp time.Time
  4723. startDateParse, _ := time.Parse(utils.FormatDate, startDate)
  4724. switch v.LeadUnit {
  4725. case "天":
  4726. startTimeRealTemp = startDateParse.AddDate(0, 0, -v.LeadValue)
  4727. case "月":
  4728. startTimeRealTemp = startDateParse.AddDate(0, -v.LeadValue, 0)
  4729. case "季":
  4730. startTimeRealTemp = startDateParse.AddDate(0, -3*v.LeadValue, 0)
  4731. case "周":
  4732. startTimeRealTemp = startDateParse.AddDate(0, 0, -7*v.LeadValue)
  4733. case "年":
  4734. startTimeRealTemp = startDateParse.AddDate(-v.LeadValue, 0, 0)
  4735. }
  4736. if startTimeRealTemp.Before(startDateParse) {
  4737. startDateReal = startTimeRealTemp.Format(utils.FormatDate)
  4738. diffSeconds = (int64(startTimeRealTemp.UnixNano()) - int64(startDateParse.UnixNano())) / 1e6
  4739. } else {
  4740. startDateReal = startDate
  4741. diffSeconds = 0
  4742. }
  4743. // 预测指标的开始日期也要偏移
  4744. {
  4745. day, tmpErr := utils.GetDaysBetween2Date(utils.FormatDate, startDate, startDateReal)
  4746. if tmpErr != nil {
  4747. err = tmpErr
  4748. return
  4749. }
  4750. moveLatestDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, item.MoveLatestDate, time.Local)
  4751. if tmpErr != nil {
  4752. err = tmpErr
  4753. return
  4754. }
  4755. item.MoveLatestDate = moveLatestDateTime.AddDate(0, 0, day).Format(utils.FormatDate)
  4756. }
  4757. } else {
  4758. startDateReal = startDate
  4759. }
  4760. }
  4761. //fmt.Println("line 1011 chart:", v.Source, v.EdbInfoId, startDateReal, endDate)
  4762. calendarPreYear := 0
  4763. if calendar == "农历" {
  4764. newStartDateReal, err := time.Parse(utils.FormatDate, startDateReal)
  4765. if err != nil {
  4766. fmt.Println("time.Parse:" + err.Error())
  4767. }
  4768. calendarPreYear = newStartDateReal.Year() - 1
  4769. newStartDateReal = newStartDateReal.AddDate(-1, 0, 0)
  4770. startDateReal = newStartDateReal.Format(utils.FormatDate)
  4771. }
  4772. dataList := make([]*data_manage.EdbDataList, 0)
  4773. //fmt.Println("chart:", v.Source, v.EdbInfoId, startDateReal, endDate)
  4774. //fmt.Println("calendarPreYear:", calendarPreYear)
  4775. //var newEdbInfo *data_manage.EdbInfo
  4776. switch v.EdbInfoCategoryType {
  4777. case 0:
  4778. dataList, err = data_manage.GetEdbDataList(v.Source, v.SubSource, v.EdbInfoId, startDateReal, endDate)
  4779. case 1:
  4780. _, dataList, _, _, err, _ = GetPredictDataListByPredictEdbInfoId(v.EdbInfoId, startDateReal, endDate, true)
  4781. default:
  4782. err = errors.New(fmt.Sprint("获取失败,指标类型异常", v.EdbInfoCategoryType))
  4783. }
  4784. if err != nil {
  4785. return
  4786. }
  4787. handleDataMap := make(map[string]float64)
  4788. newDataList, _, _, e := HandleDataByLinearRegressionToListV3(dataList, handleDataMap)
  4789. if e != nil {
  4790. err = e
  4791. return
  4792. }
  4793. if v.IsConvert == 1 {
  4794. switch v.ConvertType {
  4795. case 1:
  4796. for i, data := range newDataList {
  4797. newDataList[i].Value = data.Value * v.ConvertValue
  4798. }
  4799. //item.MaxData = item.MaxData * v.ConvertValue
  4800. //item.MinData = item.MinData * v.ConvertValue
  4801. case 2:
  4802. for i, data := range newDataList {
  4803. newDataList[i].Value = data.Value / v.ConvertValue
  4804. }
  4805. //item.MaxData = item.MaxData / v.ConvertValue
  4806. //item.MinData = item.MinData / v.ConvertValue
  4807. case 3:
  4808. for i, data := range newDataList {
  4809. if data.Value <= 0 {
  4810. err = errors.New("数据中含有负数或0,无法对数运算")
  4811. return
  4812. }
  4813. newDataList[i].Value = math.Log(data.Value) / math.Log(v.ConvertValue)
  4814. }
  4815. //item.MaxData = math.Log(item.MaxData) / math.Log(v.ConvertValue)
  4816. //item.MinData = math.Log(item.MinData) / math.Log(v.ConvertValue)
  4817. }
  4818. }
  4819. edbDataListMap[v.EdbInfoId] = newDataList
  4820. if diffSeconds != 0 && v.EdbInfoType == 0 {
  4821. newDataListLen := len(newDataList)
  4822. for i := 0; i < newDataListLen; i++ {
  4823. newDataList[i].DataTimestamp = newDataList[i].DataTimestamp - diffSeconds
  4824. }
  4825. }
  4826. if chartType == 2 && item.IsAxis == 1 {
  4827. latestDate, tmpErr := time.Parse(utils.FormatDate, v.LatestDate)
  4828. if tmpErr != nil {
  4829. //item.DataList = newDataList
  4830. item.IsNullData = true
  4831. edbList = append(edbList, item)
  4832. continue
  4833. err = errors.New(fmt.Sprint("获取最后实际数据的日期失败,Err:" + tmpErr.Error() + ";LatestDate:" + v.LatestDate))
  4834. return
  4835. }
  4836. if calendar == "农历" {
  4837. if len(newDataList) <= 0 {
  4838. result := new(data_manage.EdbDataResult)
  4839. item.DataList = result
  4840. } else {
  4841. result, tmpErr := data_manage.AddCalculateQuarterV6(newDataList)
  4842. if tmpErr != nil {
  4843. err = errors.New("获取农历数据失败,Err:" + tmpErr.Error())
  4844. return
  4845. }
  4846. quarterDataList, tErr := GetSeasonEdbInfoDataListByXDateNong(result, latestDate, seasonExtraConfig, calendarPreYear)
  4847. if tErr != nil {
  4848. err = errors.New("获取季节性图表数据失败,Err:" + tErr.Error())
  4849. return
  4850. }
  4851. item.DataList = quarterDataList
  4852. }
  4853. } else {
  4854. quarterDataList, tErr := GetSeasonEdbInfoDataListByXDate(newDataList, latestDate, seasonExtraConfig)
  4855. if tErr != nil {
  4856. err = errors.New("获取季节性图表数据失败,Err:" + tErr.Error())
  4857. return
  4858. }
  4859. item.DataList = quarterDataList
  4860. }
  4861. } else if chartType == 2 && item.IsAxis == 0 {
  4862. // 右轴数据处理
  4863. xStartDate := "01-01"
  4864. jumpYear := 0
  4865. var seasonExtra data_manage.SeasonExtraItem
  4866. if seasonExtraConfig != "" {
  4867. err = json.Unmarshal([]byte(seasonExtraConfig), &seasonExtra)
  4868. if err != nil {
  4869. return
  4870. }
  4871. }
  4872. if seasonExtra.XStartDate != "" {
  4873. xStartDate = seasonExtra.XStartDate
  4874. jumpYear = seasonExtra.JumpYear
  4875. }
  4876. length := len(newDataList)
  4877. if length == 0 {
  4878. return
  4879. }
  4880. latestDate, tmpErr := time.Parse(utils.FormatDate, v.LatestDate)
  4881. if tmpErr != nil {
  4882. //item.DataList = newDataList
  4883. item.IsNullData = true
  4884. edbList = append(edbList, item)
  4885. continue
  4886. err = errors.New(fmt.Sprint("获取最后实际数据的日期失败,Err:" + tmpErr.Error() + ";LatestDate:" + v.LatestDate))
  4887. return
  4888. }
  4889. var rightAxisDate time.Time
  4890. if jumpYear == 1 {
  4891. latestDate = latestDate.AddDate(-1, 0, 0)
  4892. }
  4893. latestDateStr := fmt.Sprintf("%d-%s", latestDate.Year(), xStartDate)
  4894. rightAxisDate, err = time.Parse(utils.FormatDate, latestDateStr)
  4895. if err != nil {
  4896. return
  4897. }
  4898. nowYear := time.Now().Year()
  4899. newList := make([]*data_manage.EdbDataList, 0)
  4900. for _, v := range dataList {
  4901. dataTime, e := time.Parse(utils.FormatDate, v.DataTime)
  4902. if e != nil {
  4903. err = errors.New("季节性图处理右轴指标数据转换日期失败,Err:" + e.Error())
  4904. return
  4905. }
  4906. dataTimeT, _ := time.Parse(utils.FormatDate, v.DataTime)
  4907. year := dataTimeT.Year()
  4908. newItemDate := dataTimeT.AddDate(nowYear-year, 0, 0)
  4909. v.DataTimestamp = newItemDate.UnixNano() / 1e6
  4910. if dataTime.Equal(rightAxisDate) || dataTime.After(rightAxisDate) {
  4911. newList = append(newList, v)
  4912. }
  4913. }
  4914. item.DataList = newList
  4915. } else if chartType == 7 || chartType == utils.CHART_TYPE_RADAR { //柱方图
  4916. //item.DataList = newDataList
  4917. } else {
  4918. item.DataList = newDataList
  4919. }
  4920. edbList = append(edbList, item)
  4921. }
  4922. return
  4923. }