chart_info.go 164 KB

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