chart_info.go 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880
  1. package chart
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/shopspring/decimal"
  7. "hongze/hongze_yb/global"
  8. "hongze/hongze_yb/models/request"
  9. "hongze/hongze_yb/models/response/chart_info"
  10. chartEdbMappingModel "hongze/hongze_yb/models/tables/chart_edb_mapping"
  11. chartInfoModel "hongze/hongze_yb/models/tables/chart_info"
  12. company2 "hongze/hongze_yb/models/tables/company"
  13. edbDataModel "hongze/hongze_yb/models/tables/edb_data"
  14. edbInfoModel "hongze/hongze_yb/models/tables/edb_info"
  15. "hongze/hongze_yb/models/tables/my_chart_classify"
  16. "hongze/hongze_yb/models/tables/yb_chart_daily_visit_log"
  17. "hongze/hongze_yb/models/tables/yb_chart_visit_log"
  18. "hongze/hongze_yb/services/alarm_msg"
  19. edbDataService "hongze/hongze_yb/services/edb_data"
  20. "hongze/hongze_yb/services/user"
  21. "hongze/hongze_yb/utils"
  22. "math"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "time"
  27. )
  28. // ModifyChartInfoAndMapping 修改图表信息
  29. func ModifyChartInfoAndMapping(edbInfoIdStr string, req *chartInfoModel.SaveChartInfoReq, chartType int, chartEdbInfoList []*chartInfoModel.ChartSaveItem) (err error) {
  30. // 开启事务
  31. tx := global.MYSQL["data"].Begin()
  32. defer func() {
  33. if err != nil {
  34. tx.Rollback()
  35. } else {
  36. tx.Commit()
  37. }
  38. }()
  39. // 更新图表信息
  40. if chartType != 2 {
  41. updateStr := `
  42. edb_info_ids = ?,
  43. modify_time = NOW(),
  44. date_type = ?,
  45. start_date = ?,
  46. end_date = ?,
  47. left_min = ?,
  48. left_max = ?,
  49. right_min = ?,
  50. right_max = ?`
  51. pars := []interface{}{edbInfoIdStr, req.DateType, req.StartDate, req.EndDate, req.LeftMin, req.LeftMax, req.RightMin, req.RightMax}
  52. if req.ExtraConfig != `` {
  53. updateStr += `,extra_config=? `
  54. pars = append(pars, req.ExtraConfig)
  55. }
  56. pars = append(pars, req.ChartInfoId)
  57. sql := ` UPDATE chart_info SET ` + updateStr + ` WHERE chart_info_id = ?`
  58. err = tx.Exec(sql, pars...).Error
  59. } else {
  60. updateStr := `edb_info_ids = ?,
  61. modify_time = NOW(),
  62. date_type = ?,
  63. calendar = ?,
  64. start_date = ?,
  65. end_date = ?,
  66. season_start_date = ?,
  67. season_end_date = ?,
  68. left_min = ?,
  69. left_max = ?,
  70. right_min = ?,
  71. right_max = ?`
  72. pars := []interface{}{edbInfoIdStr, req.DateType, req.Calendar, req.StartDate, req.EndDate, req.StartDate, req.EndDate, req.LeftMin, req.LeftMax, req.RightMin, req.RightMax}
  73. if req.ExtraConfig != `` {
  74. updateStr += `,extra_config=? `
  75. pars = append(pars, req.ExtraConfig)
  76. }
  77. pars = append(pars, req.ChartInfoId)
  78. sql := ` UPDATE chart_info SET ` + updateStr + ` WHERE chart_info_id = ?`
  79. err = tx.Exec(sql, pars...).Error
  80. }
  81. if err != nil {
  82. fmt.Println("UPDATE chart_info Err:", err.Error())
  83. return
  84. }
  85. // 修改图表关联指标
  86. chartEdbMappingIdList := make([]string, 0)
  87. for _, v := range chartEdbInfoList {
  88. var tmpChartEdbMapping *chartEdbMappingModel.ChartEdbMapping
  89. csql := `SELECT * FROM chart_edb_mapping WHERE chart_info_id=? AND edb_info_id=? AND source = ? `
  90. err = tx.Raw(csql, req.ChartInfoId, v.EdbInfoId, utils.CHART_SOURCE_DEFAULT).First(&tmpChartEdbMapping).Error
  91. if err != nil && err != utils.ErrNoRow {
  92. fmt.Println("QueryRow Err:", err.Error())
  93. return err
  94. }
  95. if tmpChartEdbMapping == nil || tmpChartEdbMapping.ChartEdbMappingId == 0 {
  96. mapItem := new(chartEdbMappingModel.ChartEdbMapping)
  97. mapItem.ChartInfoId = req.ChartInfoId
  98. mapItem.EdbInfoId = v.EdbInfoId
  99. mapItem.CreateTime = time.Now()
  100. mapItem.ModifyTime = time.Now()
  101. timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
  102. mapItem.UniqueCode = utils.MD5(utils.CHART_PREFIX + "_" + timestamp)
  103. mapItem.MaxData = v.MaxData
  104. mapItem.MinData = v.MinData
  105. mapItem.IsOrder = 0
  106. if v.IsOrder {
  107. mapItem.IsOrder = 1
  108. }
  109. mapItem.IsAxis = v.IsAxis
  110. mapItem.EdbInfoType = v.EdbInfoType
  111. mapItem.LeadValue = v.LeadValue
  112. mapItem.LeadUnit = v.LeadUnit
  113. mapItem.ChartStyle = v.ChartStyle
  114. mapItem.ChartColor = v.ChartColor
  115. mapItem.ChartWidth = v.ChartWidth
  116. mapItem.Source = utils.CHART_SOURCE_DEFAULT
  117. err = tx.Create(mapItem).Error
  118. if err != nil {
  119. return
  120. }
  121. chartEdbMappingIdList = append(chartEdbMappingIdList, strconv.Itoa(mapItem.ChartEdbMappingId))
  122. } else {
  123. chartEdbMappingIdList = append(chartEdbMappingIdList, strconv.Itoa(tmpChartEdbMapping.ChartEdbMappingId))
  124. tmpChartEdbMapping.ModifyTime = time.Now()
  125. tmpChartEdbMapping.MaxData = v.MaxData
  126. tmpChartEdbMapping.MinData = v.MinData
  127. tmpChartEdbMapping.IsOrder = 0
  128. if v.IsOrder {
  129. tmpChartEdbMapping.IsOrder = 1
  130. }
  131. tmpChartEdbMapping.IsAxis = v.IsAxis
  132. tmpChartEdbMapping.EdbInfoType = v.EdbInfoType
  133. tmpChartEdbMapping.LeadValue = v.LeadValue
  134. tmpChartEdbMapping.LeadUnit = v.LeadUnit
  135. tmpChartEdbMapping.ChartStyle = v.ChartStyle
  136. tmpChartEdbMapping.ChartColor = v.ChartColor
  137. //tmpChartEdbMapping.PredictChartColor = v.PredictChartColor
  138. tmpChartEdbMapping.ChartWidth = v.ChartWidth
  139. err = tx.Model(tmpChartEdbMapping).Select([]string{"ModifyTime", "MaxData", "MinData", "IsOrder", "IsAxis", "EdbInfoType", "LeadValue", "LeadUnit", "ChartStyle", "ChartColor", "PredictChartColor", "ChartWidth"}).Updates(*tmpChartEdbMapping).Error
  140. if err != nil {
  141. fmt.Println("chart_edb_mapping Err:" + err.Error())
  142. return err
  143. }
  144. }
  145. }
  146. // 清除原图表指标
  147. if len(chartEdbMappingIdList) > 0 {
  148. chartEdbMappingIdStr := strings.Join(chartEdbMappingIdList, ",")
  149. dsql := `DELETE FROM chart_edb_mapping WHERE chart_info_id=? AND chart_edb_mapping_id NOT IN(` + chartEdbMappingIdStr + `)`
  150. err = tx.Exec(dsql, req.ChartInfoId).Error
  151. if err != nil {
  152. fmt.Println("delete err:" + err.Error())
  153. return err
  154. }
  155. }
  156. return
  157. }
  158. // GetChartInfoRefreshData 获取需要刷新的指标
  159. func GetChartInfoRefreshData(chartInfoId int) (baseEdbInfoArr, calculateInfoArr []*edbInfoModel.EdbInfo, err error) {
  160. sql := ` SELECT b.* FROM chart_edb_mapping AS a
  161. INNER JOIN edb_info AS b ON a.edb_info_id=b.edb_info_id
  162. WHERE a.chart_info_id=? `
  163. edbInfoList := make([]*edbInfoModel.EdbInfo, 0)
  164. err = global.MYSQL["data"].Raw(sql, chartInfoId).Scan(&edbInfoList).Error
  165. if err != nil {
  166. return
  167. }
  168. for _, v := range edbInfoList {
  169. fmt.Println(v.EdbInfoId, v.EdbType)
  170. if v.EdbType == 1 {
  171. baseEdbInfoArr = append(baseEdbInfoArr, v)
  172. } else {
  173. calculateInfoArr = append(calculateInfoArr, v)
  174. newBaseEdbInfoArr, newCalculateInfoArr, err := GetChartRefreshEdbInfo(v.EdbInfoId, v.Source, 0)
  175. if err != nil {
  176. return baseEdbInfoArr, calculateInfoArr, err
  177. }
  178. baseEdbInfoArr = append(baseEdbInfoArr, newBaseEdbInfoArr...)
  179. calculateInfoArr = append(calculateInfoArr, newCalculateInfoArr...)
  180. }
  181. }
  182. return
  183. }
  184. // GetChartRefreshEdbInfo
  185. func GetChartRefreshEdbInfo(edbInfoId, source, n int) (baseEdbInfoArr, calculateInfoArr []*edbInfoModel.EdbInfo, err error) {
  186. calculateList, err := GetEdbInfoCalculateMap(edbInfoId, source)
  187. if err != nil && err != utils.ErrNoRow {
  188. return
  189. }
  190. n++
  191. for _, item := range calculateList {
  192. fmt.Println(item.EdbInfoId)
  193. if item.EdbType == 1 {
  194. baseEdbInfoArr = append(baseEdbInfoArr, item)
  195. } else {
  196. calculateInfoArr = append(calculateInfoArr, item)
  197. if n > 10 {
  198. return
  199. }
  200. newBaseEdbInfoArr, newCalculateInfoArr, _ := GetChartRefreshEdbInfo(item.EdbInfoId, item.Source, n)
  201. baseEdbInfoArr = append(baseEdbInfoArr, newBaseEdbInfoArr...)
  202. calculateInfoArr = append(calculateInfoArr, newCalculateInfoArr...)
  203. }
  204. }
  205. return
  206. }
  207. func GetEdbInfoCalculateMap(edbInfoId, source int) (list []*edbInfoModel.EdbInfo, err error) {
  208. sql := ` SELECT b.* FROM edb_info_calculate_mapping AS a
  209. INNER JOIN edb_info AS b ON a.from_edb_info_id=b.edb_info_id
  210. WHERE a.edb_info_id=? ORDER BY sort ASC `
  211. err = global.MYSQL["data"].Exec(sql, edbInfoId).Error
  212. return
  213. }
  214. // SaveChartVisitLog 保存图表访问记录
  215. func SaveChartVisitLog(userInfo user.UserInfo, chartInfo *chartInfoModel.ChartInfoView, myChartClassifyId int) (err error) {
  216. userId := int(userInfo.UserID)
  217. companyId := int(userInfo.CompanyID)
  218. chartInfoId := chartInfo.ChartInfoId
  219. // 访问记录
  220. visitLog := new(yb_chart_visit_log.YbChartVisitLog)
  221. visitLog.CompanyId = companyId
  222. companyInfo, err := company2.GetByCompanyId(userInfo.CompanyID)
  223. if err == nil {
  224. visitLog.CompanyName = companyInfo.CompanyName
  225. }
  226. visitLog.UserId = userId
  227. visitLog.RealName = userInfo.RealName
  228. visitLog.Mobile = userInfo.Mobile
  229. visitLog.Email = userInfo.Email
  230. visitLog.ChartInfoId = chartInfoId
  231. visitLog.ChartName = chartInfo.ChartName
  232. visitLog.CreateTime = time.Now().Local()
  233. visitLog.Create()
  234. // 每日访问记录,用户/天/图仅记录一次
  235. if myChartClassifyId > 0 {
  236. // 今日是否已访问
  237. nowTime := time.Now().Local()
  238. startTime := time.Date(nowTime.Year(), nowTime.Month(), nowTime.Day(), 0, 0, 0, 0, time.Local)
  239. endTime := time.Date(nowTime.Year(), nowTime.Month(), nowTime.Day(), 23, 59, 59, 0, time.Local)
  240. _, tmpErr := yb_chart_daily_visit_log.GetTodayVisitLog(userId, chartInfoId, myChartClassifyId, startTime, endTime)
  241. if tmpErr == nil {
  242. return
  243. }
  244. myChartClassify, tmpErr := my_chart_classify.GetClassifyById(myChartClassifyId)
  245. if tmpErr != nil {
  246. return
  247. }
  248. dailyLog := new(yb_chart_daily_visit_log.YbChartDailyVisitLog)
  249. dailyLog.CompanyId = companyId
  250. if companyInfo != nil {
  251. dailyLog.CompanyName = companyInfo.CompanyName
  252. }
  253. dailyLog.UserId = userId
  254. dailyLog.RealName = userInfo.RealName
  255. dailyLog.Mobile = userInfo.Mobile
  256. dailyLog.Email = userInfo.Email
  257. dailyLog.ChartInfoId = chartInfoId
  258. dailyLog.ChartName = chartInfo.ChartName
  259. dailyLog.MyChartClassifyId = myChartClassifyId
  260. dailyLog.MyChartClassifyName = myChartClassify.MyChartClassifyName
  261. dailyLog.CreateTime = time.Now().Local()
  262. dailyLog.Create()
  263. }
  264. return
  265. }
  266. // RefreshChart 图表刷新
  267. func RefreshChart(chartInfoId int) (err error) {
  268. var errMsg string
  269. defer func() {
  270. if err != nil {
  271. if global.CONFIG.Serve.RunMode == "release" {
  272. //go services.SendEmail(utils.APPNAME+"【"+global.CONFIG.Serve.RunMode+"】"+"失败提醒", "RefreshChart:"+errMsg, utils.EmailSendToUsers)
  273. go alarm_msg.SendAlarmMsg("RefreshChart Err:"+errMsg, 3)
  274. }
  275. fmt.Println("RefreshChart Err:" + errMsg)
  276. }
  277. }()
  278. // 获取需要刷新的指标
  279. baseEdbInfoArr, calculateInfoArr, err := GetChartInfoRefreshData(chartInfoId)
  280. if err != nil {
  281. errMsg = "获取需要刷新的指标失败:Err:" + err.Error()
  282. return
  283. }
  284. newBaseEdbInfoArr := make([]*edbInfoModel.EdbInfo, 0)
  285. baseMap := make(map[int]*edbInfoModel.EdbInfo)
  286. for _, bv := range baseEdbInfoArr {
  287. // 如果不是普通指标,那么过滤
  288. if bv.EdbInfoType != 0 {
  289. continue
  290. }
  291. if _, ok := baseMap[bv.EdbInfoId]; !ok {
  292. newBaseEdbInfoArr = append(newBaseEdbInfoArr, bv)
  293. }
  294. baseMap[bv.EdbInfoId] = bv
  295. }
  296. newCalculateInfoArr := make([]*edbInfoModel.EdbInfo, 0)
  297. calculateMap := make(map[int]*edbInfoModel.EdbInfo)
  298. var calculateArr []int
  299. for _, bv := range calculateInfoArr {
  300. if _, ok := calculateMap[bv.EdbInfoId]; !ok {
  301. newCalculateInfoArr = append(newCalculateInfoArr, bv)
  302. calculateArr = append(calculateArr, bv.EdbInfoId)
  303. }
  304. calculateMap[bv.EdbInfoId] = bv
  305. }
  306. sort.Ints(calculateArr)
  307. // 刷新指标
  308. var startDate string
  309. for _, bv := range newBaseEdbInfoArr {
  310. source := bv.Source
  311. subSource := bv.SubSource
  312. edbInfoId := bv.EdbInfoId
  313. edbCode := bv.EdbCode
  314. startDate = bv.StartDate.Format(utils.FormatDate)
  315. frequency := bv.Frequency
  316. if startDate == "0000-00-00" {
  317. continue
  318. }
  319. sTime := bv.EndDate
  320. var limitDay int
  321. startDate := ""
  322. switch frequency {
  323. case "日度":
  324. limitDay = utils.DATA_START_REFRESH_LIMIT
  325. case "周度":
  326. limitDay = utils.DATA_START_REFRESH_LIMIT * 7
  327. case "月度":
  328. limitDay = utils.DATA_START_REFRESH_LIMIT * 30
  329. case "季度":
  330. limitDay = utils.DATA_START_REFRESH_LIMIT * 90
  331. case "年度":
  332. limitDay = utils.DATA_START_REFRESH_LIMIT * 365
  333. default:
  334. limitDay = utils.DATA_START_REFRESH_LIMIT
  335. }
  336. startDate = sTime.AddDate(0, 0, -limitDay).Format(utils.FormatDate)
  337. fmt.Println("source:", source)
  338. respItem, err := RefreshEdbData(edbInfoId, source, subSource, edbCode, startDate)
  339. if err != nil {
  340. errMsg = errors.New("RefreshEdbData Err:" + err.Error()).Error()
  341. return err
  342. }
  343. if respItem.Ret != 200 {
  344. errMsg = errors.New(respItem.ErrMsg + ";EdbCode:" + edbCode).Error()
  345. return err
  346. }
  347. //maxAndMinItem, err := edbDataModel.GetEdbInfoMaxAndMinInfo(source, edbCode)
  348. //if err != nil {
  349. // return err
  350. //}
  351. //if maxAndMinItem != nil {
  352. // err = edbDataModel.ModifyEdbInfoMaxAndMinInfo(edbInfoId, maxAndMinItem)
  353. // if err != nil {
  354. // return err
  355. // }
  356. //}
  357. }
  358. // 刷新计算指标
  359. for _, v := range calculateArr {
  360. edbInfo := calculateMap[v]
  361. if edbInfo == nil {
  362. return err
  363. }
  364. startDate = edbInfo.StartDate.Format(utils.FormatDate)
  365. source := edbInfo.Source
  366. if source == utils.DATA_SOURCE_CALCULATE {
  367. sTime := edbInfo.EndDate
  368. startDate = sTime.Format(utils.FormatDate)
  369. }
  370. result, err := RefreshEdbCalculateData(edbInfo.EdbInfoId, edbInfo.EdbCode, startDate)
  371. if err != nil {
  372. fmt.Println(v, "RefreshEdbCalculateData err", time.Now())
  373. errMsg = "RefreshEdbCalculateData Err:" + err.Error()
  374. return err
  375. }
  376. if result.Ret != 200 {
  377. fmt.Println(v, "RefreshEdbCalculateData err;msg:", result.Msg, ";errMsg:", result.ErrMsg)
  378. errMsg = fmt.Sprint(v, "RefreshEdbCalculateData err;msg:", result.Msg, ";errMsg:", result.ErrMsg)
  379. return fmt.Errorf("刷新失败")
  380. }
  381. }
  382. return
  383. }
  384. // GetChartEdbData 获取图表的指标数据
  385. func GetChartEdbData(chartInfoId, chartType int, calendar, startDate, endDate string, mappingList []*chartEdbMappingModel.ChartEdbInfoMapping, extraConfigStr string, seasonExtraConfig string) (edbList []*chartEdbMappingModel.ChartEdbInfoMappingList, xEdbIdValue []int, yDataList []chart_info.YData, sourceArr []string, dataResp interface{}, err error, errMsg string) {
  386. edbList = make([]*chartEdbMappingModel.ChartEdbInfoMappingList, 0)
  387. xEdbIdValue = make([]int, 0)
  388. yDataList = make([]chart_info.YData, 0)
  389. var extraConfig interface{}
  390. switch chartType {
  391. case 7: // 柱形图
  392. var barConfig request.BarChartInfoReq
  393. if extraConfigStr == `` {
  394. errMsg = "柱方图未配置"
  395. err = errors.New(errMsg)
  396. return
  397. }
  398. err = json.Unmarshal([]byte(extraConfigStr), &barConfig)
  399. if err != nil {
  400. errMsg = "柱方图配置异常"
  401. err = errors.New(errMsg)
  402. return
  403. }
  404. extraConfig = barConfig
  405. case 10: // 截面散点图
  406. var tmpExtraConfig request.SectionScatterReq
  407. if extraConfigStr == `` {
  408. errMsg = "截面散点图未配置"
  409. err = errors.New(errMsg)
  410. return
  411. }
  412. err = json.Unmarshal([]byte(extraConfigStr), &tmpExtraConfig)
  413. if err != nil {
  414. errMsg = "截面散点配置异常"
  415. err = errors.New(errMsg)
  416. return
  417. }
  418. extraConfig = tmpExtraConfig
  419. case utils.CHART_TYPE_RADAR:
  420. var barConfig request.RadarChartInfoReq
  421. if extraConfigStr == `` {
  422. errMsg = "雷达图未配置"
  423. err = errors.New(errMsg)
  424. return
  425. }
  426. err = json.Unmarshal([]byte(extraConfigStr), &barConfig)
  427. if err != nil {
  428. errMsg = "雷达图配置异常"
  429. err = errors.New(errMsg)
  430. return
  431. }
  432. extraConfig = barConfig
  433. default:
  434. xEdbIdValue = make([]int, 0)
  435. yDataList = make([]chart_info.YData, 0)
  436. }
  437. // 指标对应的所有数据
  438. edbDataListMap, edbList, sourceArr, err := getEdbDataMapList(chartInfoId, chartType, calendar, startDate, endDate, mappingList, seasonExtraConfig)
  439. if err != nil {
  440. return
  441. }
  442. // 特殊图形数据处理
  443. switch chartType {
  444. case 7: // 柱形图
  445. barChartConf := extraConfig.(request.BarChartInfoReq)
  446. xEdbIdValue, yDataList, err = BarChartData(mappingList, edbDataListMap, barChartConf.DateList, barChartConf.Sort)
  447. for _, v := range edbList {
  448. // 指标别名
  449. if barChartConf.EdbInfoIdList != nil && len(barChartConf.EdbInfoIdList) > 0 {
  450. for _, reqEdb := range barChartConf.EdbInfoIdList {
  451. if v.EdbInfoId == reqEdb.EdbInfoId {
  452. v.EdbAliasName = reqEdb.Name
  453. }
  454. }
  455. }
  456. }
  457. case 10: // 截面散点图
  458. sectionScatterConf := extraConfig.(request.SectionScatterReq)
  459. xEdbIdValue, dataResp, err = GetSectionScatterChartData(mappingList, edbDataListMap, sectionScatterConf)
  460. // 这个数据没有必要返回给前端
  461. for _, v := range edbList {
  462. v.DataList = nil
  463. }
  464. case utils.CHART_TYPE_RADAR: //雷达图
  465. radarConf := extraConfig.(request.RadarChartInfoReq)
  466. xEdbIdValue, dataResp, err = RadarChartData(mappingList, edbDataListMap, radarConf)
  467. }
  468. return
  469. }
  470. // GetEdbDataMapList 获取指标最后的基础数据
  471. func GetEdbDataMapList(chartInfoId, chartType int, calendar, startDate, endDate string, mappingList []*chartEdbMappingModel.ChartEdbInfoMapping, seasonExtraConfig string) (edbDataListMap map[int][]*edbDataModel.EdbDataList, edbList []*chartEdbMappingModel.ChartEdbInfoMappingList, sourceArr []string, err error) {
  472. edbDataListMap, edbList, sourceArr, err = getEdbDataMapList(chartInfoId, chartType, calendar, startDate, endDate, mappingList, seasonExtraConfig)
  473. return
  474. }
  475. // getEdbDataMapList 获取指标最后的基础数据
  476. func getEdbDataMapList(chartInfoId, chartType int, calendar, startDate, endDate string, mappingList []*chartEdbMappingModel.ChartEdbInfoMapping, seasonExtraConfig string) (edbDataListMap map[int][]*edbDataModel.EdbDataList, edbList []*chartEdbMappingModel.ChartEdbInfoMappingList, sourceArr []string, err error) {
  477. // 关联指标来源
  478. sourceArr = make([]string, 0)
  479. // 指标对应的所有数据
  480. edbDataListMap = make(map[int][]*edbDataModel.EdbDataList)
  481. for _, v := range mappingList {
  482. //fmt.Println("v:", v.EdbInfoId)
  483. item := new(chartEdbMappingModel.ChartEdbInfoMappingList)
  484. item.EdbInfoId = v.EdbInfoId
  485. item.SourceName = v.SourceName
  486. item.Source = v.Source
  487. item.EdbCode = v.EdbCode
  488. item.EdbName = v.EdbName
  489. item.EdbNameEn = v.EdbNameEn
  490. item.Frequency = v.Frequency
  491. item.FrequencyEn = GetFrequencyEn(v.Frequency)
  492. if v.Unit != `无` {
  493. item.Unit = v.Unit
  494. }
  495. item.UnitEn = v.UnitEn
  496. item.StartDate = v.StartDate
  497. item.EndDate = v.EndDate
  498. item.ModifyTime = v.ModifyTime
  499. item.EdbInfoCategoryType = v.EdbInfoCategoryType
  500. item.PredictChartColor = v.PredictChartColor
  501. item.EdbAliasName = v.EdbAliasName
  502. if !utils.InArray(v.Source, utils.SystemSourceList) { //来源于系统的指标,都展示为弘则研究
  503. if !utils.InArray(v.SourceName, sourceArr) {
  504. sourceArr = append(sourceArr, v.SourceName)
  505. }
  506. }
  507. if chartInfoId <= 0 {
  508. item.IsAxis = 1
  509. item.LeadValue = 0
  510. item.LeadUnit = ""
  511. item.ChartEdbMappingId = 0
  512. item.ChartInfoId = 0
  513. item.IsOrder = false
  514. item.EdbInfoType = 1
  515. item.ChartStyle = ""
  516. item.ChartColor = ""
  517. item.ChartWidth = 0
  518. item.MaxData = v.MaxValue
  519. item.MinData = v.MinValue
  520. } else {
  521. item.IsAxis = v.IsAxis
  522. item.EdbInfoType = v.EdbInfoType
  523. item.LeadValue = v.LeadValue
  524. item.LeadUnit = v.LeadUnit
  525. item.LeadUnitEn = GetLeadUnitEn(v.LeadUnit)
  526. item.ChartEdbMappingId = v.ChartEdbMappingId
  527. item.ChartInfoId = v.ChartInfoId
  528. item.ChartStyle = v.ChartStyle
  529. item.ChartColor = v.ChartColor
  530. item.ChartWidth = v.ChartWidth
  531. item.IsOrder = v.IsOrder
  532. item.MaxData = v.MaxData
  533. item.MinData = v.MinData
  534. }
  535. item.LatestValue = v.LatestValue
  536. item.LatestDate = v.LatestDate
  537. item.UniqueCode = v.UniqueCode
  538. item.MoveLatestDate = item.LatestDate
  539. item.EdbAliasName = v.EdbAliasName
  540. item.IsConvert = v.IsConvert
  541. item.ConvertType = v.ConvertType
  542. item.ConvertValue = v.ConvertValue
  543. item.ConvertUnit = v.ConvertUnit
  544. item.ConvertEnUnit = v.ConvertEnUnit
  545. var startDateReal string
  546. var diffSeconds int64
  547. if chartType == 2 { //季节性图
  548. startDateReal = startDate
  549. } else {
  550. if v.EdbInfoType == 0 && v.LeadUnit != "" && v.LeadValue > 0 { //领先指标
  551. var startTimeRealTemp time.Time
  552. startDateParse, _ := time.Parse(utils.FormatDate, startDate)
  553. switch v.LeadUnit {
  554. case "天":
  555. startTimeRealTemp = startDateParse.AddDate(0, 0, -v.LeadValue)
  556. case "月":
  557. startTimeRealTemp = startDateParse.AddDate(0, -v.LeadValue, 0)
  558. case "季":
  559. startTimeRealTemp = startDateParse.AddDate(0, -3*v.LeadValue, 0)
  560. case "周":
  561. startTimeRealTemp = startDateParse.AddDate(0, 0, -7*v.LeadValue)
  562. case "年":
  563. startTimeRealTemp = startDateParse.AddDate(-v.LeadValue, 0, 0)
  564. }
  565. if startTimeRealTemp.Before(startDateParse) {
  566. startDateReal = startTimeRealTemp.Format(utils.FormatDate)
  567. diffSeconds = (int64(startTimeRealTemp.UnixNano()) - int64(startDateParse.UnixNano())) / 1e6
  568. } else {
  569. startDateReal = startDate
  570. diffSeconds = 0
  571. }
  572. // 预测指标的开始日期也要偏移
  573. {
  574. day, tmpErr := utils.GetDaysBetween2Date(utils.FormatDate, startDate, startDateReal)
  575. if tmpErr != nil {
  576. err = tmpErr
  577. return
  578. }
  579. item.MoveLatestDate = item.MoveLatestDate.AddDate(0, 0, day)
  580. }
  581. } else {
  582. startDateReal = startDate
  583. }
  584. }
  585. //fmt.Println("line 1011 chart:", v.Source, v.EdbInfoId, startDateReal, endDate)
  586. calendarPreYear := 0
  587. if calendar == "农历" {
  588. newStartDateReal, err := time.Parse(utils.FormatDate, startDateReal)
  589. if err != nil {
  590. fmt.Println("time.Parse:" + err.Error())
  591. }
  592. calendarPreYear = newStartDateReal.Year() - 1
  593. newStartDateReal = newStartDateReal.AddDate(-1, 0, 0)
  594. startDateReal = newStartDateReal.Format(utils.FormatDate)
  595. }
  596. dataList := make([]*edbDataModel.EdbDataList, 0)
  597. //fmt.Println("chart:", v.Source, v.EdbInfoId, startDateReal, endDate, ";EdbInfoCategoryType:", v.EdbInfoCategoryType)
  598. //var newEdbInfo *edbInfoModel.EdbInfo
  599. switch v.EdbInfoCategoryType {
  600. case 0:
  601. dataList, err = edbDataModel.GetEdbDataList(v.Source, v.SubSource, v.EdbInfoId, startDateReal, endDate)
  602. case 1:
  603. _, dataList, _, _, err, _ = GetPredictDataListByPredictEdbInfoId(v.EdbInfoId, startDateReal, endDate, false)
  604. //if item.MaxValue < newEdbInfo.MaxValue {
  605. // item.MaxData = newEdbInfo.MaxValue
  606. //}
  607. //if item.MinData > newEdbInfo.MinValue {
  608. // item.MinData = newEdbInfo.MinValue
  609. //}
  610. default:
  611. err = errors.New(fmt.Sprint("获取失败,指标类型异常", v.EdbInfoCategoryType))
  612. }
  613. if err != nil {
  614. return
  615. }
  616. if v.IsConvert == 1 {
  617. switch v.ConvertType {
  618. case 1:
  619. for i, data := range dataList {
  620. dataList[i].Value = data.Value * v.ConvertValue
  621. }
  622. //item.MaxData = item.MaxData * v.ConvertValue
  623. //item.MinData = item.MinData * v.ConvertValue
  624. case 2:
  625. for i, data := range dataList {
  626. dataList[i].Value = data.Value / v.ConvertValue
  627. }
  628. //item.MaxData = item.MaxData / v.ConvertValue
  629. //item.MinData = item.MinData / v.ConvertValue
  630. case 3:
  631. for i, data := range dataList {
  632. dataList[i].Value = math.Log(data.Value) / math.Log(v.ConvertValue)
  633. }
  634. //item.MaxData = math.Log(item.MaxData) / math.Log(v.ConvertValue)
  635. //item.MinData = math.Log(item.MinData) / math.Log(v.ConvertValue)
  636. }
  637. }
  638. edbDataListMap[v.EdbInfoId] = dataList
  639. if diffSeconds != 0 && v.EdbInfoType == 0 {
  640. dataListLen := len(dataList)
  641. for i := 0; i < dataListLen; i++ {
  642. dataList[i].DataTimestamp = dataList[i].DataTimestamp - diffSeconds
  643. }
  644. }
  645. if chartType == 2 {
  646. //latestDateStr := v.LatestDate.Format(utils.FormatDate) //实际数据的截止日期
  647. latestDate := v.LatestDate
  648. if calendar == "农历" {
  649. if len(dataList) <= 0 {
  650. result := new(edbDataModel.EdbDataResult)
  651. item.DataList = result
  652. } else {
  653. result, tmpErr := edbDataService.AddCalculateQuarterV6(dataList)
  654. if tmpErr != nil {
  655. err = errors.New("获取农历数据失败,Err:" + tmpErr.Error())
  656. return
  657. }
  658. quarterDataList, tErr := GetSeasonEdbInfoDataListByXDateNong(result, latestDate, seasonExtraConfig, calendarPreYear)
  659. if tErr != nil {
  660. err = errors.New("获取季节性图表数据失败,Err:" + tErr.Error())
  661. return
  662. }
  663. item.DataList = quarterDataList
  664. }
  665. } else {
  666. quarterDataList, tErr := GetSeasonEdbInfoDataListByXDate(dataList, latestDate, seasonExtraConfig)
  667. if tErr != nil {
  668. err = errors.New("获取季节性图表数据失败,Err:" + tErr.Error())
  669. return
  670. }
  671. item.DataList = quarterDataList
  672. }
  673. } else if chartType == 7 || chartType == utils.CHART_TYPE_RADAR { //柱方图
  674. //item.DataList = dataList
  675. } else {
  676. item.DataList = dataList
  677. }
  678. edbList = append(edbList, item)
  679. }
  680. return
  681. }
  682. // GetSeasonEdbInfoDataListByXDate 季节性图的指标数据根据横轴展示
  683. func GetSeasonEdbInfoDataListByXDate(dataList []*edbDataModel.EdbDataList, latestDate time.Time, seasonExtraConfig string) (quarterDataListSort edbDataModel.QuarterDataList, err error) {
  684. xStartDate := "01-01"
  685. xEndDate := "12-31"
  686. jumpYear := 0
  687. legends := make([]edbDataModel.SeasonChartLegend, 0)
  688. var seasonExtra edbDataModel.SeasonExtraItem
  689. if seasonExtraConfig != "" {
  690. err = json.Unmarshal([]byte(seasonExtraConfig), &seasonExtra)
  691. if err != nil {
  692. return
  693. }
  694. }
  695. if seasonExtra.XStartDate != "" {
  696. xStartDate = seasonExtra.XStartDate
  697. xEndDate = seasonExtra.XEndDate
  698. jumpYear = seasonExtra.JumpYear
  699. legends = seasonExtra.ChartLegend
  700. }
  701. length := len(dataList)
  702. if length == 0 {
  703. return
  704. }
  705. legendMap := make(map[string]string, 0)
  706. if len(legends) > 0 {
  707. for _, v := range legends {
  708. legendMap[v.Name] = v.Value
  709. }
  710. }
  711. latestDateStr := latestDate.Format(utils.FormatDate)
  712. //判断横轴的两个时间之间是不是跨年了,如果跨年了,则横轴截止年份比起始年份+1,如果不跨年,截止年份等于起始年份
  713. //根据数据确定最早的年份,和最近年份
  714. //根据横轴的日期,汇总所有的年份
  715. startDate := dataList[0].DataTime
  716. startDateT, tmpErr := time.Parse(utils.FormatDate, startDate)
  717. if tmpErr != nil {
  718. err = tmpErr
  719. return
  720. }
  721. startYear := startDateT.Year()
  722. //获取数据的最新日期
  723. lastDate := dataList[length-1].DataTime
  724. lastDateT, tmpErr := time.Parse(utils.FormatDate, lastDate)
  725. if tmpErr != nil {
  726. err = tmpErr
  727. return
  728. }
  729. endYear := lastDateT.Year()
  730. nowYear := time.Now().Year()
  731. chartLegendMaxYear := 0
  732. dataMap := make(map[string]edbDataModel.QuarterXDateItem, 0)
  733. quarterDataList := make([]*edbDataModel.QuarterData, 0)
  734. quarterMap := make(map[string][]*edbDataModel.EdbDataList, 0)
  735. //整理出日期
  736. idx := 1
  737. chartLegendMap := make(map[string]int, 0)
  738. for currentStartYear := startYear; currentStartYear <= endYear; currentStartYear++ {
  739. startStr := fmt.Sprintf("%d-%s", currentStartYear, xStartDate)
  740. currentEndYear := currentStartYear
  741. if jumpYear == 1 {
  742. currentEndYear = currentStartYear + 1
  743. }
  744. endStr := fmt.Sprintf("%d-%s", currentEndYear, xEndDate)
  745. name := fmt.Sprintf("%s_%s", startStr, endStr)
  746. showName := fmt.Sprintf("%d_%d", currentStartYear, currentEndYear)
  747. startT, tEr := time.Parse(utils.FormatDate, startStr)
  748. if tEr != nil {
  749. err = tEr
  750. return
  751. }
  752. endT, tEr := time.Parse(utils.FormatDate, endStr)
  753. if tEr != nil {
  754. err = tEr
  755. return
  756. }
  757. if lastDateT.Before(startT) {
  758. //如果最新的日期在起始日之前,则跳出循环
  759. break
  760. }
  761. if endT.Year() > nowYear {
  762. //如果最新的日期比真实年份要大,则数据全部按照最大的年份补齐
  763. nowYear = endT.Year()
  764. }
  765. item := edbDataModel.QuarterXDateItem{
  766. StartDate: startT,
  767. EndDate: endT,
  768. ShowName: showName,
  769. }
  770. chartLegendMaxYear = endT.Year()
  771. dataMap[name] = item
  772. chartLegendMap[name] = idx
  773. idx++
  774. if lastDateT.Before(endT) {
  775. //如果最新的日期在起始日之前,则跳出循环
  776. break
  777. }
  778. }
  779. lenYear := len(dataMap)
  780. if chartLegendMaxYear > endYear {
  781. chartLegendMaxYear = endYear
  782. }
  783. for k, v := range dataMap {
  784. if i, ok := chartLegendMap[k]; ok {
  785. //v.ChartLegend = strconv.Itoa(endYear - lenYear + i)
  786. v.ChartLegend = strconv.Itoa(chartLegendMaxYear - lenYear + i)
  787. }
  788. dataMap[k] = v
  789. }
  790. for _, v := range dataList {
  791. dataTimeT, _ := time.Parse(utils.FormatDate, v.DataTime)
  792. year := dataTimeT.Year()
  793. newItemDate := dataTimeT.AddDate(nowYear-year, 0, 0)
  794. for k, dateItem := range dataMap {
  795. tmpVal := edbDataModel.EdbDataList{
  796. EdbDataId: v.EdbDataId,
  797. EdbInfoId: v.EdbInfoId,
  798. DataTime: v.DataTime,
  799. DataTimestamp: v.DataTimestamp,
  800. Value: v.Value,
  801. }
  802. if (dateItem.StartDate.Before(dataTimeT) && dateItem.EndDate.After(dataTimeT)) || dateItem.StartDate == dataTimeT || dateItem.EndDate == dataTimeT {
  803. if jumpYear == 1 {
  804. //计算前一年最大的日期, 只补齐数据到去年
  805. beforeYearMaxDate := fmt.Sprintf("%d-12-31", dateItem.StartDate.Year())
  806. beforeYearMaxDateT, _ := time.Parse(utils.FormatDate, beforeYearMaxDate)
  807. if dataTimeT.Before(beforeYearMaxDateT) || dataTimeT == beforeYearMaxDateT {
  808. newItemDate = dataTimeT.AddDate(nowYear-year-1, 0, 0)
  809. } else {
  810. newItemDate = dataTimeT.AddDate(nowYear-year, 0, 0)
  811. }
  812. } else {
  813. newItemDate = dataTimeT.AddDate(nowYear-year, 0, 0)
  814. }
  815. timestamp := newItemDate.UnixNano() / 1e6
  816. tmpVal.DataTimestamp = timestamp
  817. tmpV := &tmpVal
  818. if findVal, ok := quarterMap[k]; !ok {
  819. findVal = append(findVal, tmpV)
  820. quarterMap[k] = findVal
  821. } else {
  822. findVal = append(findVal, tmpV)
  823. quarterMap[k] = findVal
  824. }
  825. if v.DataTime == latestDateStr {
  826. dateItem.CuttingDataTimestamp = timestamp
  827. dataMap[k] = dateItem
  828. }
  829. //break
  830. }
  831. }
  832. }
  833. for k, v := range dataMap {
  834. itemList := quarterMap[k]
  835. quarterItem := new(edbDataModel.QuarterData)
  836. quarterItem.Years = v.ShowName
  837. quarterItem.Year = v.ChartLegend
  838. quarterItem.ChartLegend = v.ChartLegend
  839. if le, ok := legendMap[v.ShowName]; ok {
  840. if le != strconv.Itoa(v.StartDate.Year()) && le != strconv.Itoa(v.EndDate.Year()) {
  841. quarterItem.ChartLegend = le
  842. }
  843. }
  844. quarterItem.DataList = itemList
  845. quarterItem.CuttingDataTimestamp = v.CuttingDataTimestamp
  846. //如果等于最后的实际日期,那么将切割时间戳记录
  847. if quarterItem.CuttingDataTimestamp == 0 {
  848. //如果大于最后的实际日期,那么第一个点就是切割的时间戳
  849. if latestDate.Before(v.StartDate) && len(itemList) > 0 {
  850. quarterItem.CuttingDataTimestamp = itemList[0].DataTimestamp - 100
  851. }
  852. }
  853. quarterDataList = append(quarterDataList, quarterItem)
  854. }
  855. if len(quarterDataList) > 0 {
  856. quarterDataListSort = quarterDataList
  857. sort.Sort(quarterDataListSort)
  858. }
  859. return
  860. }
  861. // GetSeasonEdbInfoDataListByXDateNong 季节性图的指标数据根据横轴选择农历时展示
  862. func GetSeasonEdbInfoDataListByXDateNong(result *edbDataModel.EdbDataResult, latestDate time.Time, seasonExtraConfig string, calendarPreYear int) (quarterDataListSort edbDataModel.QuarterDataList, err error) {
  863. xStartDate := "01-01"
  864. xEndDate := "12-31"
  865. jumpYear := 0
  866. legends := make([]edbDataModel.SeasonChartLegend, 0)
  867. var seasonExtra edbDataModel.SeasonExtraItem
  868. if seasonExtraConfig != "" {
  869. err = json.Unmarshal([]byte(seasonExtraConfig), &seasonExtra)
  870. if err != nil {
  871. return
  872. }
  873. }
  874. if seasonExtra.XStartDate != "" {
  875. xStartDate = seasonExtra.XStartDate
  876. xEndDate = seasonExtra.XEndDate
  877. jumpYear = seasonExtra.JumpYear
  878. legends = seasonExtra.ChartLegend
  879. }
  880. length := len(result.List)
  881. if length == 0 {
  882. return
  883. }
  884. legendMap := make(map[string]string, 0)
  885. if len(legends) > 0 {
  886. for _, v := range legends {
  887. legendMap[v.Name] = v.Value
  888. }
  889. }
  890. latestDateYear := latestDate.Year()
  891. //判断横轴的两个时间之间是不是跨年了,如果跨年了,则横轴截止年份比起始年份+1,如果不跨年,截止年份等于起始年份
  892. //根据数据确定最早的年份,和最近年份
  893. //根据横轴的日期,汇总所有的年份
  894. startYear := result.List[0].Year
  895. /*if jumpYear == 1 {
  896. if startYear != calendarPreYear {
  897. startYear = startYear - 1
  898. }
  899. }*/
  900. itemLength := len(result.List[length-1].Items)
  901. //获取数据的最新日期
  902. lastDate := result.List[length-1].Items[itemLength-1].DataTime
  903. maxY := result.List[length-1].Year
  904. lastDateT, tmpErr := time.Parse(utils.FormatDate, lastDate)
  905. if tmpErr != nil {
  906. err = tmpErr
  907. return
  908. }
  909. endYear := lastDateT.Year()
  910. nowYear := time.Now().Year()
  911. chartLegendMaxYear := 0
  912. dataMap := make(map[string]edbDataModel.QuarterXDateItem, 0)
  913. quarterDataList := make([]*edbDataModel.QuarterData, 0)
  914. resultData := make([]*edbDataModel.QuarterData, 0)
  915. quarterMap := make(map[string][]*edbDataModel.EdbDataList, 0)
  916. //整理出日期
  917. var startTmpT, endTmpT time.Time
  918. idx := 1
  919. chartLegendMap := make(map[string]int, 0)
  920. for currentStartYear := startYear; currentStartYear <= endYear; currentStartYear++ {
  921. startStr := fmt.Sprintf("%d-%s", currentStartYear, xStartDate)
  922. currentEndYear := currentStartYear
  923. if jumpYear == 1 {
  924. currentEndYear = currentStartYear + 1
  925. }
  926. endStr := fmt.Sprintf("%d-%s", currentEndYear, xEndDate)
  927. showName := fmt.Sprintf("%d_%d", currentStartYear, currentEndYear)
  928. startT, tEr := time.Parse(utils.FormatDate, startStr)
  929. if tEr != nil {
  930. err = tEr
  931. return
  932. }
  933. endT, tEr := time.Parse(utils.FormatDate, endStr)
  934. if tEr != nil {
  935. err = tEr
  936. return
  937. }
  938. if lastDateT.Before(startT) {
  939. //如果最新的日期在起始日之前,则跳出循环
  940. break
  941. }
  942. if endT.Year() > nowYear {
  943. //如果最新的日期比真实年份要大,则数据全部按照最大的年份补齐
  944. nowYear = endT.Year()
  945. }
  946. item := edbDataModel.QuarterXDateItem{
  947. StartDate: startT,
  948. EndDate: endT,
  949. ShowName: showName,
  950. }
  951. chartLegendMaxYear = endT.Year()
  952. dataMap[showName] = item
  953. fmt.Println("年份" + showName + "日期" + startStr + " " + endStr)
  954. startTmpT = startT
  955. endTmpT = endT
  956. chartLegendMap[showName] = idx
  957. idx++
  958. if lastDateT.Before(endT) {
  959. //如果最新的日期在起始日之前,则跳出循环
  960. break
  961. }
  962. }
  963. lenYear := len(dataMap)
  964. if chartLegendMaxYear > endYear {
  965. chartLegendMaxYear = endYear
  966. }
  967. for k, v := range dataMap {
  968. if i, ok := chartLegendMap[k]; ok {
  969. //v.ChartLegend = strconv.Itoa(endYear - lenYear + i)
  970. v.ChartLegend = strconv.Itoa(chartLegendMaxYear - lenYear + i)
  971. }
  972. dataMap[k] = v
  973. }
  974. yearDataListMap := make(map[int]*edbDataModel.EdbDataItems, 0)
  975. for _, lv := range result.List {
  976. yearDataListMap[lv.Year] = lv
  977. }
  978. fmt.Println("横轴截取日" + startTmpT.Format(utils.FormatDate) + " " + endTmpT.Format(utils.FormatDate))
  979. fmt.Printf("lastDateT.Year() 为%d \n", lastDateT.Year())
  980. fmt.Printf("maxY 为%d \n", maxY)
  981. for name, dateItem := range dataMap {
  982. tY := dateItem.EndDate.Year()
  983. if lastDateT.Month() >= 11 {
  984. if maxY > endTmpT.Year() {
  985. tY = tY + 1
  986. }
  987. }
  988. lv, ok1 := yearDataListMap[tY]
  989. fmt.Printf("name %s yearDataListMap[%d]\n", name, tY)
  990. if !ok1 {
  991. continue
  992. }
  993. for _, item := range lv.Items {
  994. tmpVal := edbDataModel.EdbDataList{
  995. EdbDataId: item.EdbDataId,
  996. EdbInfoId: item.EdbInfoId,
  997. DataTime: item.DataTime,
  998. DataTimestamp: item.DataTimestamp,
  999. Value: item.Value,
  1000. }
  1001. dataTimeT, _ := time.Parse(utils.FormatDate, item.DataTime)
  1002. if (startTmpT.Before(dataTimeT) && endTmpT.After(dataTimeT)) || startTmpT == dataTimeT || endTmpT == dataTimeT {
  1003. tmpV := &tmpVal
  1004. if findVal, ok := quarterMap[name]; !ok {
  1005. findVal = append(findVal, tmpV)
  1006. quarterMap[name] = findVal
  1007. } else {
  1008. findVal = append(findVal, tmpV)
  1009. quarterMap[name] = findVal
  1010. }
  1011. if lv.Year >= latestDateYear {
  1012. // 切割的日期时间字符串
  1013. cuttingDataTimeStr := latestDate.AddDate(0, 0, lv.BetweenDay).Format(utils.FormatDate)
  1014. if item.DataTime == cuttingDataTimeStr {
  1015. dateItem.CuttingDataTimestamp = tmpVal.DataTimestamp
  1016. dataMap[name] = dateItem
  1017. }
  1018. }
  1019. }
  1020. }
  1021. }
  1022. for k, v := range dataMap {
  1023. itemList := quarterMap[k]
  1024. quarterItem := new(edbDataModel.QuarterData)
  1025. quarterItem.Years = v.ShowName
  1026. quarterItem.Year = v.ChartLegend
  1027. quarterItem.ChartLegend = v.ChartLegend
  1028. if le, ok := legendMap[v.ShowName]; ok {
  1029. if le != strconv.Itoa(v.StartDate.Year()) && le != strconv.Itoa(v.EndDate.Year()) {
  1030. quarterItem.ChartLegend = le
  1031. }
  1032. }
  1033. quarterItem.DataList = itemList
  1034. quarterItem.CuttingDataTimestamp = v.CuttingDataTimestamp
  1035. //如果等于最后的实际日期,那么将切割时间戳记录
  1036. if quarterItem.CuttingDataTimestamp == 0 {
  1037. //如果大于最后的实际日期,那么第一个点就是切割的时间戳
  1038. if latestDate.Before(v.StartDate) && len(itemList) > 0 {
  1039. quarterItem.CuttingDataTimestamp = itemList[0].DataTimestamp - 100
  1040. }
  1041. }
  1042. quarterDataList = append(quarterDataList, quarterItem)
  1043. }
  1044. if result.List[0].Year != calendarPreYear {
  1045. itemList := make([]*edbDataModel.EdbDataList, 0)
  1046. items := new(edbDataModel.QuarterData)
  1047. //items.Year = calendarPreYear
  1048. items.DataList = itemList
  1049. newResult := make([]*edbDataModel.QuarterData, 0)
  1050. newResult = append(newResult, items)
  1051. newResult = append(newResult, quarterDataList...)
  1052. resultData = newResult
  1053. } else {
  1054. resultData = quarterDataList
  1055. }
  1056. if len(quarterDataList) > 0 {
  1057. quarterDataListSort = resultData
  1058. sort.Sort(quarterDataListSort)
  1059. }
  1060. return
  1061. }
  1062. // BarChartData 柱方图的数据处理
  1063. func BarChartData(mappingList []*chartEdbMappingModel.ChartEdbInfoMapping, edbDataListMap map[int][]*edbDataModel.EdbDataList, barChartInfoDateList []request.BarChartInfoDateReq, barChartInfoSort request.BarChartInfoSortReq) (edbIdList []int, yDataList []chart_info.YData, err error) {
  1064. // 指标数据数组(10086:{"2022-12-02":100.01,"2022-12-01":102.3})
  1065. edbDataMap := make(map[int]map[string]float64)
  1066. for edbInfoId, edbDataList := range edbDataListMap {
  1067. edbDateData := make(map[string]float64)
  1068. for _, edbData := range edbDataList {
  1069. edbDateData[edbData.DataTime] = edbData.Value
  1070. }
  1071. edbDataMap[edbInfoId] = edbDateData
  1072. }
  1073. // edbIdList 指标展示顺序;x轴的指标顺序
  1074. edbIdList = make([]int, 0)
  1075. //Sort int `description:"排序类型,0:默认,1:升序,2:降序"`
  1076. dateData := make(map[int]float64)
  1077. if barChartInfoSort.Sort == 0 {
  1078. for _, v := range mappingList {
  1079. edbIdList = append(edbIdList, v.EdbInfoId)
  1080. }
  1081. } else {
  1082. lenBarChartInfoDateList := len(barChartInfoDateList)
  1083. if barChartInfoSort.DateIndex >= lenBarChartInfoDateList {
  1084. err = errors.New("排序日期异常")
  1085. return
  1086. }
  1087. notDataEdbIdList := make([]int, 0) //没有数据的指标id
  1088. // 日期配置
  1089. barChartInfoDate := barChartInfoDateList[barChartInfoSort.DateIndex]
  1090. for edbInfoId, dataList := range edbDataListMap {
  1091. if len(dataList) <= 0 {
  1092. // 没有数据的指标id
  1093. notDataEdbIdList = append(notDataEdbIdList, edbInfoId)
  1094. continue
  1095. }
  1096. findDate := barChartInfoDate.Date
  1097. switch barChartInfoDate.Type {
  1098. case 1: //最新值
  1099. findDate = dataList[len(dataList)-1].DataTime
  1100. case 2: //近期几天
  1101. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[len(dataList)-1].DataTime, time.Local)
  1102. if tmpErr != nil {
  1103. err = tmpErr
  1104. return
  1105. }
  1106. findDateTime = findDateTime.AddDate(0, 0, -barChartInfoDate.Value)
  1107. lenData := len(dataList) - 1
  1108. for i := lenData; i >= 0; i-- {
  1109. currDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[i].DataTime, time.Local)
  1110. if tmpErr != nil {
  1111. err = tmpErr
  1112. return
  1113. }
  1114. if currDateTime.Equal(findDateTime) || currDateTime.Before(findDateTime) {
  1115. findDate = dataList[i].DataTime
  1116. break
  1117. }
  1118. }
  1119. case 3: // 固定日期
  1120. //最早的日期
  1121. minDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  1122. if tmpErr != nil {
  1123. err = tmpErr
  1124. return
  1125. }
  1126. //寻找固定日期的数据
  1127. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, barChartInfoDate.Date, time.Local)
  1128. if tmpErr != nil {
  1129. err = tmpErr
  1130. return
  1131. }
  1132. for tmpDateTime := findDateTime; tmpDateTime.After(minDateTime) || tmpDateTime.Equal(minDateTime); tmpDateTime = tmpDateTime.AddDate(0, 0, -1) {
  1133. tmpDate := tmpDateTime.Format(utils.FormatDate)
  1134. if _, ok := edbDataMap[edbInfoId][tmpDate]; ok { //如果能找到数据,那么就返回
  1135. findDate = tmpDate
  1136. break
  1137. }
  1138. }
  1139. default:
  1140. err = errors.New(fmt.Sprint("日期类型异常,Type:", barChartInfoDate.Type))
  1141. return
  1142. }
  1143. if tmpValue, ok := edbDataMap[edbInfoId][findDate]; ok {
  1144. dateData[edbInfoId] = tmpValue
  1145. } else {
  1146. // 没有数据的指标id
  1147. notDataEdbIdList = append(notDataEdbIdList, edbInfoId)
  1148. }
  1149. }
  1150. //Sort int `description:"排序类型,0:默认,1:升序,2:降序"`
  1151. // 排序
  1152. dateDataSort := utils.NewMapSorter(dateData)
  1153. sort.Sort(dateDataSort)
  1154. if barChartInfoSort.Sort == 1 {
  1155. // 先将没有数据的指标id放在最前面
  1156. if len(notDataEdbIdList) > 0 {
  1157. edbIdList = append(edbIdList, notDataEdbIdList...)
  1158. }
  1159. for _, v := range dateDataSort {
  1160. edbIdList = append(edbIdList, v.Key)
  1161. }
  1162. } else {
  1163. for i := len(dateDataSort) - 1; i >= 0; i-- {
  1164. edbIdList = append(edbIdList, dateDataSort[i].Key)
  1165. }
  1166. // 再将没有数据的指标id放在最后面
  1167. if len(notDataEdbIdList) > 0 {
  1168. edbIdList = append(edbIdList, notDataEdbIdList...)
  1169. }
  1170. }
  1171. }
  1172. yDataList = make([]chart_info.YData, 0) //y轴的数据列表
  1173. for _, barChartInfoDate := range barChartInfoDateList {
  1174. var maxDate time.Time
  1175. findDataList := make([]float64, 0) // 当前日期的数据值
  1176. for _, edbInfoId := range edbIdList {
  1177. findDate := barChartInfoDate.Date //需要的日期值
  1178. dataList := edbDataListMap[edbInfoId] //指标的所有数据值
  1179. if len(dataList) <= 0 {
  1180. // 没有数据的指标id
  1181. findDataList = append(findDataList, 0)
  1182. continue
  1183. }
  1184. switch barChartInfoDate.Type {
  1185. case 1: //最新值
  1186. dataList := edbDataListMap[edbInfoId]
  1187. findDate = dataList[len(dataList)-1].DataTime
  1188. case 2: //近期几天
  1189. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[len(dataList)-1].DataTime, time.Local)
  1190. if tmpErr != nil {
  1191. err = tmpErr
  1192. return
  1193. }
  1194. findDateTime = findDateTime.AddDate(0, 0, -barChartInfoDate.Value)
  1195. lenData := len(dataList) - 1
  1196. for i := lenData; i >= 0; i-- {
  1197. currDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[i].DataTime, time.Local)
  1198. if tmpErr != nil {
  1199. err = tmpErr
  1200. return
  1201. }
  1202. if currDateTime.Equal(findDateTime) || currDateTime.Before(findDateTime) {
  1203. findDate = dataList[i].DataTime
  1204. break
  1205. }
  1206. }
  1207. case 3: // 固定日期
  1208. //最早的日期
  1209. minDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  1210. if tmpErr != nil {
  1211. err = tmpErr
  1212. return
  1213. }
  1214. //寻找固定日期的数据
  1215. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, barChartInfoDate.Date, time.Local)
  1216. if tmpErr != nil {
  1217. err = tmpErr
  1218. return
  1219. }
  1220. for tmpDateTime := findDateTime; tmpDateTime.After(minDateTime) || tmpDateTime.Equal(minDateTime); tmpDateTime = tmpDateTime.AddDate(0, 0, -1) {
  1221. tmpDate := tmpDateTime.Format(utils.FormatDate)
  1222. if _, ok := edbDataMap[edbInfoId][tmpDate]; ok { //如果能找到数据,那么就返回
  1223. findDate = tmpDate
  1224. break
  1225. }
  1226. }
  1227. default:
  1228. err = errors.New(fmt.Sprint("日期类型异常,Type:", barChartInfoDate.Type))
  1229. return
  1230. }
  1231. findDateTime, _ := time.ParseInLocation(utils.FormatDate, findDate, time.Local)
  1232. if maxDate.IsZero() {
  1233. maxDate = findDateTime
  1234. } else {
  1235. if findDateTime.After(maxDate) {
  1236. maxDate = findDateTime
  1237. }
  1238. }
  1239. if tmpValue, ok := edbDataMap[edbInfoId][findDate]; ok {
  1240. findDataList = append(findDataList, tmpValue)
  1241. } else {
  1242. findDataList = append(findDataList, 0)
  1243. }
  1244. }
  1245. yDate := "0000-00-00"
  1246. if !maxDate.IsZero() {
  1247. yDate = maxDate.Format(utils.FormatDate)
  1248. }
  1249. yDataList = append(yDataList, chart_info.YData{
  1250. Date: yDate,
  1251. Value: findDataList,
  1252. Color: barChartInfoDate.Color,
  1253. Name: barChartInfoDate.Name,
  1254. })
  1255. }
  1256. return
  1257. }
  1258. // 获取频度的英文版
  1259. func GetFrequencyEn(frequency string) (frequencyEn string) {
  1260. switch frequency {
  1261. case "日度":
  1262. frequencyEn = "day"
  1263. return
  1264. case "周度":
  1265. frequencyEn = "week"
  1266. return
  1267. case "旬度":
  1268. frequencyEn = "ten days"
  1269. return
  1270. case "月度":
  1271. frequencyEn = "month"
  1272. return
  1273. case "季度":
  1274. frequencyEn = "quarter"
  1275. return
  1276. case "年度":
  1277. frequencyEn = "year"
  1278. return
  1279. }
  1280. return
  1281. }
  1282. func GetLeadUnitEn(unit string) (unitEn string) {
  1283. switch unit {
  1284. case "天":
  1285. unitEn = "day"
  1286. return
  1287. case "周":
  1288. unitEn = "week"
  1289. return
  1290. case "月":
  1291. unitEn = "month"
  1292. return
  1293. case "季":
  1294. unitEn = "quarter"
  1295. return
  1296. case "年":
  1297. unitEn = "year"
  1298. return
  1299. }
  1300. return
  1301. }
  1302. // ChartInfoRefreshV2 图表刷新
  1303. // @author Roc
  1304. // @datetime 2022-09-16 10:15:38
  1305. // @description 将原来自己写的一套获取所有关联指标,然后刷新指标逻辑 改成 只获取使用的指标id,然后遍历去调用“指标刷新服务”
  1306. func ChartInfoRefreshV2(chartInfoId int) (err error) {
  1307. var errmsg string
  1308. defer func() {
  1309. if err != nil {
  1310. go alarm_msg.SendAlarmMsg("ChartInfoRefresh:"+errmsg, 3)
  1311. //go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "ChartInfoRefresh:"+errmsg, utils.EmailSendToUsers)
  1312. fmt.Println("ChartInfoRefresh Err:" + errmsg)
  1313. }
  1314. }()
  1315. edbMappingList, err := chartEdbMappingModel.GetMappingListByChartInfoId(chartInfoId)
  1316. if err != nil {
  1317. errmsg = "获取需要刷新的指标失败:Err:" + err.Error()
  1318. return
  1319. }
  1320. edbIdList := make([]int, 0)
  1321. for _, v := range edbMappingList {
  1322. edbIdList = append(edbIdList, v.EdbInfoId)
  1323. }
  1324. // 批量刷新
  1325. err, errmsg = EdbInfoRefreshAllFromBase(edbIdList, false)
  1326. if err != nil {
  1327. return
  1328. }
  1329. return
  1330. }
  1331. // CheckChartExtraConfig 校验图表额外配置的信息,并且获取相关联的指标id
  1332. func CheckChartExtraConfig(chartType int, extraConfigStr string) (edbIdList []int, err error, errMsg string) {
  1333. switch chartType {
  1334. case 10: //截面散点
  1335. var extraConfig request.SectionScatterReq
  1336. err = json.Unmarshal([]byte(extraConfigStr), &extraConfig)
  1337. if err != nil {
  1338. return
  1339. }
  1340. // 判断是否有配置日期序列
  1341. if len(extraConfig.SeriesList) <= 0 {
  1342. errMsg = `请配置序列`
  1343. err = errors.New(errMsg)
  1344. return
  1345. }
  1346. // 判断是否有填写指标
  1347. if len(extraConfig.SeriesList[0].EdbInfoList) <= 0 {
  1348. errMsg = `请选择指标`
  1349. err = errors.New(errMsg)
  1350. return
  1351. }
  1352. // 遍历指标列表获取指标id
  1353. edbIdMap := make(map[int]int)
  1354. for _, v := range extraConfig.SeriesList[0].EdbInfoList {
  1355. // X 轴的指标id
  1356. if _, ok := edbIdMap[v.XEdbInfoId]; !ok {
  1357. edbIdMap[v.XEdbInfoId] = v.XEdbInfoId
  1358. edbIdList = append(edbIdList, v.XEdbInfoId)
  1359. }
  1360. // Y 轴的指标id
  1361. if _, ok := edbIdMap[v.YEdbInfoId]; !ok {
  1362. edbIdMap[v.YEdbInfoId] = v.YEdbInfoId
  1363. edbIdList = append(edbIdList, v.YEdbInfoId)
  1364. }
  1365. }
  1366. }
  1367. return
  1368. }
  1369. // GetSectionScatterChartData 柱方图的数据处理
  1370. func GetSectionScatterChartData(mappingList []*chartEdbMappingModel.ChartEdbInfoMapping, edbDataListMap map[int][]*edbDataModel.EdbDataList, extraConfig request.SectionScatterReq) (edbIdList []int, chartDataResp request.SectionScatterInfoResp, err error) {
  1371. // 指标数据数组(10086:{"2022-12-02":100.01,"2022-12-01":102.3})
  1372. edbDataMap := make(map[int]map[string]float64)
  1373. for edbInfoId, edbDataList := range edbDataListMap {
  1374. edbDateData := make(map[string]float64)
  1375. for _, edbData := range edbDataList {
  1376. edbDateData[edbData.DataTime] = edbData.Value
  1377. }
  1378. edbDataMap[edbInfoId] = edbDateData
  1379. }
  1380. // edbIdList 指标展示顺序;x轴的指标顺序
  1381. edbIdList = make([]int, 0)
  1382. edbMappingMap := make(map[int]*chartEdbMappingModel.ChartEdbInfoMapping)
  1383. for _, v := range mappingList {
  1384. edbIdList = append(edbIdList, v.EdbInfoId)
  1385. edbMappingMap[v.EdbInfoId] = v
  1386. }
  1387. //SectionScatterSeriesInfoResp
  1388. dataListResp := make([]request.SectionScatterSeriesItemResp, 0) //y轴的数据列表
  1389. for _, seriesItem := range extraConfig.SeriesList {
  1390. var maxDate time.Time
  1391. // 系列中的指标数据
  1392. tmpSeriesEdbInfoList := make([]request.SectionScatterEdbItemResp, 0)
  1393. var minXVal, maxXVal, minYVal, maxYVal float64
  1394. for _, edbConf := range seriesItem.EdbInfoList {
  1395. tmpItem := request.SectionScatterEdbItemResp{
  1396. IsShow: edbConf.IsShow,
  1397. Name: edbConf.Name,
  1398. NameEn: edbConf.NameEn,
  1399. } //单个坐标点的数据
  1400. //X轴的数据
  1401. {
  1402. edbInfoId := edbConf.XEdbInfoId //X轴的指标
  1403. edbMappingInfo, ok := edbMappingMap[edbInfoId]
  1404. if !ok {
  1405. continue
  1406. }
  1407. findDate := edbConf.XDate //需要的日期值
  1408. dataList := edbDataListMap[edbInfoId] //指标的所有数据值
  1409. if len(dataList) <= 0 {
  1410. // 没有数据的指标id
  1411. //findDataList = append(findDataList, 0)
  1412. continue
  1413. }
  1414. tmpItem.XEdbInfoId = edbInfoId
  1415. tmpItem.XName = edbMappingInfo.EdbName
  1416. tmpItem.XNameEn = edbMappingInfo.EdbNameEn
  1417. switch edbConf.XDateType {
  1418. case 1: //最新值
  1419. dataList := edbDataListMap[edbInfoId]
  1420. findDate = dataList[len(dataList)-1].DataTime
  1421. case 2: //近期几天
  1422. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[len(dataList)-1].DataTime, time.Local)
  1423. if tmpErr != nil {
  1424. err = tmpErr
  1425. return
  1426. }
  1427. findDateTime = findDateTime.AddDate(0, 0, -edbConf.XDateValue)
  1428. lenData := len(dataList) - 1
  1429. for i := lenData; i >= 0; i-- {
  1430. currDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[i].DataTime, time.Local)
  1431. if tmpErr != nil {
  1432. err = tmpErr
  1433. return
  1434. }
  1435. if currDateTime.Equal(findDateTime) || currDateTime.Before(findDateTime) {
  1436. findDate = dataList[i].DataTime
  1437. break
  1438. }
  1439. }
  1440. case 3: // 固定日期
  1441. //最早的日期
  1442. minDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  1443. if tmpErr != nil {
  1444. err = tmpErr
  1445. return
  1446. }
  1447. //寻找固定日期的数据
  1448. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, edbConf.XDate, time.Local)
  1449. if tmpErr != nil {
  1450. err = tmpErr
  1451. return
  1452. }
  1453. for tmpDateTime := findDateTime; tmpDateTime.After(minDateTime) || tmpDateTime.Equal(minDateTime); tmpDateTime = tmpDateTime.AddDate(0, 0, -1) {
  1454. tmpDate := tmpDateTime.Format(utils.FormatDate)
  1455. if _, ok := edbDataMap[edbInfoId][tmpDate]; ok { //如果能找到数据,那么就返回
  1456. findDate = tmpDate
  1457. break
  1458. }
  1459. }
  1460. default:
  1461. err = errors.New(fmt.Sprint("日期类型异常,Type:", edbConf.XDate))
  1462. return
  1463. }
  1464. findDateTime, _ := time.ParseInLocation(utils.FormatDate, findDate, time.Local)
  1465. if maxDate.IsZero() {
  1466. maxDate = findDateTime
  1467. } else {
  1468. if findDateTime.After(maxDate) {
  1469. maxDate = findDateTime
  1470. }
  1471. }
  1472. if tmpValue, ok := edbDataMap[edbInfoId][findDate]; ok {
  1473. tmpItem.XDate = findDate
  1474. tmpItem.XValue = tmpValue
  1475. } else {
  1476. continue
  1477. }
  1478. }
  1479. //Y轴的数据
  1480. {
  1481. edbInfoId := edbConf.YEdbInfoId //Y轴的指标
  1482. edbMappingInfo, ok := edbMappingMap[edbInfoId]
  1483. if !ok {
  1484. continue
  1485. }
  1486. findDate := edbConf.YDate //需要的日期值
  1487. dataList := edbDataListMap[edbInfoId] //指标的所有数据值
  1488. if len(dataList) <= 0 {
  1489. // 没有数据的指标id
  1490. //findDataList = append(findDataList, 0)
  1491. continue
  1492. }
  1493. tmpItem.YEdbInfoId = edbInfoId
  1494. tmpItem.YName = edbMappingInfo.EdbName
  1495. tmpItem.YNameEn = edbMappingInfo.EdbNameEn
  1496. switch edbConf.YDateType {
  1497. case 1: //最新值
  1498. dataList := edbDataListMap[edbInfoId]
  1499. findDate = dataList[len(dataList)-1].DataTime
  1500. case 2: //近期几天
  1501. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[len(dataList)-1].DataTime, time.Local)
  1502. if tmpErr != nil {
  1503. err = tmpErr
  1504. return
  1505. }
  1506. findDateTime = findDateTime.AddDate(0, 0, -edbConf.YDateValue)
  1507. lenData := len(dataList) - 1
  1508. for i := lenData; i >= 0; i-- {
  1509. currDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[i].DataTime, time.Local)
  1510. if tmpErr != nil {
  1511. err = tmpErr
  1512. return
  1513. }
  1514. if currDateTime.Equal(findDateTime) || currDateTime.Before(findDateTime) {
  1515. findDate = dataList[i].DataTime
  1516. break
  1517. }
  1518. }
  1519. case 3: // 固定日期
  1520. //最早的日期
  1521. minDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  1522. if tmpErr != nil {
  1523. err = tmpErr
  1524. return
  1525. }
  1526. //寻找固定日期的数据
  1527. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, edbConf.YDate, time.Local)
  1528. if tmpErr != nil {
  1529. err = tmpErr
  1530. return
  1531. }
  1532. for tmpDateTime := findDateTime; tmpDateTime.After(minDateTime) || tmpDateTime.Equal(minDateTime); tmpDateTime = tmpDateTime.AddDate(0, 0, -1) {
  1533. tmpDate := tmpDateTime.Format(utils.FormatDate)
  1534. if _, ok := edbDataMap[edbInfoId][tmpDate]; ok { //如果能找到数据,那么就返回
  1535. findDate = tmpDate
  1536. break
  1537. }
  1538. }
  1539. default:
  1540. err = errors.New(fmt.Sprint("日期类型异常,Type:", edbConf.YDate))
  1541. return
  1542. }
  1543. findDateTime, _ := time.ParseInLocation(utils.FormatDate, findDate, time.Local)
  1544. if maxDate.IsZero() {
  1545. maxDate = findDateTime
  1546. } else {
  1547. if findDateTime.After(maxDate) {
  1548. maxDate = findDateTime
  1549. }
  1550. }
  1551. if tmpValue, ok := edbDataMap[edbInfoId][findDate]; ok {
  1552. tmpItem.YDate = findDate
  1553. tmpItem.YValue = tmpValue
  1554. } else {
  1555. continue
  1556. }
  1557. }
  1558. // 获取当前系列的X轴的最大最小值
  1559. {
  1560. if tmpItem.XValue < minXVal {
  1561. minXVal = tmpItem.XValue
  1562. }
  1563. if tmpItem.XValue > maxXVal {
  1564. maxXVal = tmpItem.XValue
  1565. }
  1566. if tmpItem.YValue < minYVal {
  1567. minYVal = tmpItem.YValue
  1568. }
  1569. if tmpItem.YValue > maxYVal {
  1570. maxYVal = tmpItem.YValue
  1571. }
  1572. }
  1573. tmpSeriesEdbInfoList = append(tmpSeriesEdbInfoList, tmpItem)
  1574. }
  1575. trendLimitData := make([]request.CoordinatePoint, 0) //趋势线的前后坐标点
  1576. var trendLine, rSquare string
  1577. // 生成线性方程式
  1578. var a, b float64
  1579. {
  1580. coordinateData := make([]utils.Coordinate, 0)
  1581. for _, tmpSeriesEdbInfo := range tmpSeriesEdbInfoList {
  1582. tmpCoordinate1 := utils.Coordinate{
  1583. X: tmpSeriesEdbInfo.XValue,
  1584. Y: tmpSeriesEdbInfo.YValue,
  1585. }
  1586. coordinateData = append(coordinateData, tmpCoordinate1)
  1587. }
  1588. // 只有存在两个坐标点的时候,才能去计算线性方程和R平方
  1589. if len(coordinateData) >= 2 {
  1590. a, b = utils.GetLinearResult(coordinateData)
  1591. if !math.IsNaN(a) && !math.IsNaN(b) {
  1592. if b > 0 {
  1593. trendLine = fmt.Sprintf("y=%sx+%s", utils.SubFloatToString(a, 4), utils.SubFloatToString(b, 4))
  1594. } else {
  1595. trendLine = fmt.Sprintf("y=%sx%s", utils.SubFloatToString(a, 4), utils.SubFloatToString(b, 4))
  1596. }
  1597. minYVal, _ = decimal.NewFromFloat(a).Mul(decimal.NewFromFloat(minXVal)).Add(decimal.NewFromFloat(b)).Round(4).Float64()
  1598. maxYVal, _ = decimal.NewFromFloat(a).Mul(decimal.NewFromFloat(maxXVal)).Add(decimal.NewFromFloat(b)).Round(4).Float64()
  1599. }
  1600. // 计算R平方
  1601. rSquare = fmt.Sprint(utils.CalculationDecisive(coordinateData))
  1602. }
  1603. trendLimitData = append(trendLimitData, request.CoordinatePoint{
  1604. X: minXVal,
  1605. Y: minYVal,
  1606. }, request.CoordinatePoint{
  1607. X: maxXVal,
  1608. Y: maxYVal,
  1609. })
  1610. }
  1611. dataListResp = append(dataListResp, request.SectionScatterSeriesItemResp{
  1612. Name: seriesItem.Name,
  1613. NameEn: seriesItem.NameEn,
  1614. Color: seriesItem.Color,
  1615. EdbInfoList: tmpSeriesEdbInfoList,
  1616. ShowTrendLine: seriesItem.ShowTrendLine,
  1617. ShowFitEquation: seriesItem.ShowFitEquation,
  1618. ShowRSquare: seriesItem.ShowRSquare,
  1619. TrendLine: trendLine,
  1620. RSquare: rSquare,
  1621. TrendLimitData: trendLimitData,
  1622. })
  1623. }
  1624. chartDataResp = request.SectionScatterInfoResp{
  1625. XName: extraConfig.XName,
  1626. XNameEn: extraConfig.XNameEn,
  1627. XUnitName: extraConfig.XUnitName,
  1628. XUnitNameEn: extraConfig.XUnitNameEn,
  1629. YName: extraConfig.YName,
  1630. YNameEn: extraConfig.YNameEn,
  1631. YUnitName: extraConfig.YUnitName,
  1632. YUnitNameEn: extraConfig.YUnitNameEn,
  1633. XMinValue: extraConfig.XMinValue,
  1634. XMaxValue: extraConfig.XMaxValue,
  1635. YMinValue: extraConfig.YMinValue,
  1636. YMaxValue: extraConfig.YMaxValue,
  1637. DataList: dataListResp,
  1638. }
  1639. return
  1640. }
  1641. // RadarChartData 雷达图的数据处理
  1642. func RadarChartData(mappingList []*chartEdbMappingModel.ChartEdbInfoMapping, edbDataListMap map[int][]*edbDataModel.EdbDataList, extraConfig request.RadarChartInfoReq) (edbIdList []int, chartDataResp chart_info.RadarChartInfoResp, err error) {
  1643. // 指标数据数组(10086:{"2022-12-02":100.01,"2022-12-01":102.3})
  1644. edbDataMap := make(map[int]map[string]float64)
  1645. for edbInfoId, edbDataList := range edbDataListMap {
  1646. edbDateData := make(map[string]float64)
  1647. for _, edbData := range edbDataList {
  1648. edbDateData[edbData.DataTime] = edbData.Value
  1649. }
  1650. edbDataMap[edbInfoId] = edbDateData
  1651. }
  1652. // edbIdList 指标展示顺序;x轴的指标顺序
  1653. edbIdList = make([]int, 0)
  1654. for _, v := range mappingList {
  1655. edbIdList = append(edbIdList, v.EdbInfoId)
  1656. }
  1657. chartDateList := extraConfig.DateList
  1658. yDataList := make([]chart_info.RadarYData, 0) //y轴的数据列表
  1659. for _, chartDate := range chartDateList {
  1660. var maxDate time.Time
  1661. findDataList := make([]float64, 0) // 当前日期的数据值
  1662. for _, edbInfoId := range edbIdList {
  1663. findDate := chartDate.Date //需要的日期值
  1664. dataList := edbDataListMap[edbInfoId] //指标的所有数据值
  1665. if len(dataList) <= 0 {
  1666. // 没有数据的指标id
  1667. findDataList = append(findDataList, 0)
  1668. continue
  1669. }
  1670. switch chartDate.Type {
  1671. case 1: //最新值
  1672. findDate = dataList[len(dataList)-1].DataTime
  1673. case 2: //近期几天
  1674. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[len(dataList)-1].DataTime, time.Local)
  1675. if tmpErr != nil {
  1676. err = tmpErr
  1677. return
  1678. }
  1679. findDateTime = findDateTime.AddDate(0, 0, -chartDate.Value)
  1680. lenData := len(dataList) - 1
  1681. for i := lenData; i >= 0; i-- {
  1682. currDateTime, e := time.ParseInLocation(utils.FormatDate, dataList[i].DataTime, time.Local)
  1683. if e != nil {
  1684. err = e
  1685. return
  1686. }
  1687. if currDateTime.Equal(findDateTime) || currDateTime.Before(findDateTime) {
  1688. findDate = dataList[i].DataTime
  1689. break
  1690. }
  1691. }
  1692. case 3: // 固定日期
  1693. //最早的日期
  1694. minDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  1695. if tmpErr != nil {
  1696. err = tmpErr
  1697. return
  1698. }
  1699. //寻找固定日期的数据
  1700. findDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, chartDate.Date, time.Local)
  1701. if tmpErr != nil {
  1702. err = tmpErr
  1703. return
  1704. }
  1705. for tmpDateTime := findDateTime; tmpDateTime.After(minDateTime) || tmpDateTime.Equal(minDateTime); tmpDateTime = tmpDateTime.AddDate(0, 0, -1) {
  1706. tmpDate := tmpDateTime.Format(utils.FormatDate)
  1707. if _, ok := edbDataMap[edbInfoId][tmpDate]; ok { //如果能找到数据,那么就返回
  1708. findDate = tmpDate
  1709. break
  1710. }
  1711. }
  1712. default:
  1713. err = errors.New(fmt.Sprint("日期类型异常,Type:", chartDate.Type))
  1714. return
  1715. }
  1716. findDateTime, _ := time.ParseInLocation(utils.FormatDate, findDate, time.Local)
  1717. if maxDate.IsZero() {
  1718. maxDate = findDateTime
  1719. } else {
  1720. if findDateTime.After(maxDate) {
  1721. maxDate = findDateTime
  1722. }
  1723. }
  1724. if tmpValue, ok := edbDataMap[edbInfoId][findDate]; ok {
  1725. tmpValue, _ = decimal.NewFromFloat(tmpValue).Round(4).Float64()
  1726. findDataList = append(findDataList, tmpValue)
  1727. } else {
  1728. findDataList = append(findDataList, 0)
  1729. }
  1730. }
  1731. yDate := "0000-00-00"
  1732. if !maxDate.IsZero() {
  1733. yDate = maxDate.Format(utils.FormatDate)
  1734. }
  1735. yDataList = append(yDataList, chart_info.RadarYData{
  1736. Date: yDate,
  1737. Value: findDataList,
  1738. Color: chartDate.Color,
  1739. Name: chartDate.Name,
  1740. })
  1741. }
  1742. chartDataResp = chart_info.RadarChartInfoResp{
  1743. YDataList: yDataList,
  1744. XEdbIdValue: edbIdList,
  1745. }
  1746. return
  1747. }