chart_info.go 164 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292
  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 {
  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 {
  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 err.Error() == utils.ErrNoRow() {
  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 err.Error() == utils.ErrNoRow() {
  2141. errMsg = "分类不存在"
  2142. err = errors.New(errMsg)
  2143. return
  2144. }
  2145. errMsg = "获取分类信息失败"
  2146. return
  2147. }
  2148. if chartClassify == nil {
  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 tmpErr.Error() == utils.ErrNoRow() {
  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 {
  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 err.Error() == utils.ErrNoRow() {
  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 err.Error() == utils.ErrNoRow() {
  2494. errMsg = "分类不存在"
  2495. err = errors.New(errMsg)
  2496. return
  2497. }
  2498. errMsg = "获取分类信息失败"
  2499. return
  2500. }
  2501. if chartClassify == nil {
  2502. errMsg = "分类不存在"
  2503. err = errors.New(errMsg)
  2504. return
  2505. }
  2506. chartItem, err = data_manage.GetChartInfoById(req.ChartInfoId)
  2507. if err != nil {
  2508. if err.Error() == utils.ErrNoRow() {
  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 tmpErr.Error() == utils.ErrNoRow() {
  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 {
  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}, 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. }