chart_info.go 65 KB

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