edb_data_calculate_qjjs.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_index_lib/utils"
  6. "fmt"
  7. "github.com/beego/beego/v2/client/orm"
  8. "github.com/shopspring/decimal"
  9. "math"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. type CalculateRangeAnalysis struct {
  15. }
  16. type RangeAnalysisCalculateFormula struct {
  17. DateRangeType int `description:"区间划分类型 0:智能划分,1:手工划分,2:跨年划分"`
  18. AutoDateConf ChartRangeAnalysisAutoDateConf `description:"智能划分时间区间配置"`
  19. ManualDateConf []ChartRangeAnalysisManualDateConf `description:"手工划分时间区间配置"`
  20. YearDateConf ChartRangeAnalysisYearDateConf `description:"跨年划分时间区间配置"`
  21. CalculateType int `description:"计算类型 0: 区间均值,1: 区间累计值,2:区间涨幅,3:区间年化增长率,4:区间最大值,5:区间最小值"`
  22. UnNormalDataDealType int `description:"异常值处理配置 0:不处理,1:剔除,2替换"`
  23. UnNormalDataConf ChartRangeAnalysisDeleteDataConf
  24. DataConvertType int `description:"数据转换类型 0不转, 1乘 2除 3对数"`
  25. DataConvertConf ChartRangeAnalysisDataConvertConf `description:"数据转换详情"`
  26. }
  27. type ChartRangeAnalysisAutoDateConf struct { //智能划分
  28. IsAutoStartDate int `description:"起始日期是否是动态设置:0固定,1动态"`
  29. StartDate string `description:"起始日期"` //固定模式下,截止日期为指标的最新日期
  30. EndDate string `description:"固定模式下的截止日期"`
  31. IsAutoEndDate int `description:"截止日期是否是动态设置:0固定,1动态"`
  32. StartDateConf ChartRangeAnalysisAutoDateChangeConf `description:"动态起始日期配置"`
  33. EndDateConf ChartRangeAnalysisAutoDateChangeConf `description:"动态截止日期配置"`
  34. }
  35. type ChartRangeAnalysisAutoDateChangeConf struct {
  36. BaseDateType int `description:"基准日期类型:0指标日期,1系统日期,2固定日期"`
  37. MoveForward int `description:"前移的期数"`
  38. DateChange []*EdbDataDateChangeConf
  39. }
  40. type EdbDataDateChangeConf struct {
  41. Year int
  42. Month int
  43. Day int
  44. Frequency string `description:"频度变换"`
  45. FrequencyDay string `description:"频度的固定日期"`
  46. ChangeType int `description:"日期变换类型1日期位移,2指定频率"`
  47. }
  48. type ChartRangeAnalysisManualDateConf struct { //手工划分
  49. StartDate string `description:"开始日期"`
  50. EndDate string `description:"结束日期"`
  51. }
  52. type ChartRangeAnalysisYearDateConf struct {
  53. StartDay string `description:"开始日"`
  54. EndDay string `description:"结束日"`
  55. }
  56. type ChartRangeAnalysisDeleteDataConf struct {
  57. Formula string
  58. Value float64
  59. ReplaceValue float64 `description:"替换的值"`
  60. }
  61. type ChartRangeAnalysisDataConvertConf struct {
  62. Value float64 `description:"数据转换值"`
  63. Unit string `description:"数据转换单位"`
  64. EnUnit string `description:"数据转换单位"`
  65. }
  66. type ChartRangeAnalysisDateDataItem struct {
  67. StartDate time.Time
  68. EndDate time.Time
  69. DataList []*EdbInfoSearchData
  70. }
  71. func (obj CalculateRangeAnalysis) Add(params AddCalculateBatchParams) (edbInfo *EdbInfo, err error, errMsg string) {
  72. req := params.Req
  73. edbCode := params.EdbCode
  74. uniqueCode := params.UniqueCode
  75. sysUserId := params.SysUserId
  76. sysUserRealName := params.SysUserRealName
  77. //req *EdbInfoCalculateBatchSaveReq, edbCode, uniqueCode string, sysUserId int, sysUserRealName string
  78. o := orm.NewOrm()
  79. to, err := o.Begin()
  80. if err != nil {
  81. return
  82. }
  83. defer func() {
  84. if err != nil {
  85. fmt.Println("AddCalculateRangeAnalysis,Err:" + err.Error())
  86. _ = to.Rollback()
  87. } else {
  88. _ = to.Commit()
  89. }
  90. }()
  91. if req.EdbInfoId > 0 {
  92. err = errors.New("无法新增")
  93. return
  94. }
  95. edbInfo = new(EdbInfo)
  96. edbInfo.Source = obj.GetSource()
  97. edbInfo.SourceName = obj.GetSourceName()
  98. edbInfo.EdbCode = edbCode
  99. edbInfo.EdbName = req.EdbName
  100. edbInfo.EdbNameSource = req.EdbName
  101. edbInfo.Frequency = req.Frequency
  102. edbInfo.Unit = req.Unit
  103. edbInfo.ClassifyId = req.ClassifyId
  104. edbInfo.SysUserId = sysUserId
  105. edbInfo.SysUserRealName = sysUserRealName
  106. edbInfo.CreateTime = time.Now()
  107. edbInfo.ModifyTime = time.Now()
  108. edbInfo.UniqueCode = uniqueCode
  109. edbInfo.CalculateFormula = req.CalculateFormula
  110. edbInfo.EdbNameEn = req.EdbName
  111. edbInfo.UnitEn = req.Unit
  112. edbInfo.EdbType = obj.GetEdbType()
  113. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  114. if tmpErr != nil {
  115. err = tmpErr
  116. return
  117. }
  118. edbInfo.EdbInfoId = int(newEdbInfoId)
  119. //关联关系
  120. fromEdbInfo, e := GetEdbInfoById(req.FromEdbInfoId)
  121. if e != nil {
  122. err = fmt.Errorf("获取来源指标失败,Err:%s", e.Error())
  123. return
  124. }
  125. calculateMappingItem := new(EdbInfoCalculateMapping)
  126. calculateMappingItem.CreateTime = time.Now()
  127. calculateMappingItem.ModifyTime = time.Now()
  128. calculateMappingItem.Sort = 1
  129. calculateMappingItem.EdbCode = edbCode
  130. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  131. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  132. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  133. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  134. calculateMappingItem.FromSource = fromEdbInfo.Source
  135. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  136. calculateMappingItem.FromTag = ""
  137. calculateMappingItem.Source = edbInfo.Source
  138. calculateMappingItem.SourceName = edbInfo.SourceName
  139. calculateMappingItem.FromSubSource = edbInfo.SubSource
  140. _, err = to.Insert(calculateMappingItem)
  141. if err != nil {
  142. return
  143. }
  144. //计算数据
  145. err, errMsg = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, edbInfo.CalculateFormula)
  146. return
  147. }
  148. func (obj CalculateRangeAnalysis) Edit(params EditCalculateBatchParams) (err error, errMsg string) {
  149. edbInfo := params.EdbInfo
  150. req := params.Req
  151. o := orm.NewOrm()
  152. to, err := o.Begin()
  153. if err != nil {
  154. return
  155. }
  156. defer func() {
  157. if err != nil {
  158. fmt.Println("EditCalculateRangeAnalysis,Err:" + err.Error())
  159. _ = to.Rollback()
  160. } else {
  161. _ = to.Commit()
  162. }
  163. }()
  164. //修改指标信息
  165. edbInfo.EdbName = req.EdbName
  166. edbInfo.EdbNameSource = req.EdbName
  167. edbInfo.Frequency = req.Frequency
  168. edbInfo.Unit = req.Unit
  169. edbInfo.ClassifyId = req.ClassifyId
  170. edbInfo.CalculateFormula = req.CalculateFormula
  171. edbInfo.EdbNameEn = req.EdbNameEn
  172. edbInfo.UnitEn = req.UnitEn
  173. edbInfo.ModifyTime = time.Now()
  174. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn")
  175. if err != nil {
  176. return
  177. }
  178. //删除,计算指标关联的,基础指标的关联关系
  179. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  180. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  181. if err != nil {
  182. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  183. return
  184. }
  185. //清空原有数据
  186. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  187. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  188. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  189. if err != nil {
  190. return
  191. }
  192. fromEdbInfo, e := GetEdbInfoById(req.FromEdbInfoId)
  193. if e != nil {
  194. err = fmt.Errorf("获取来源指标失败,Err:%s", e.Error())
  195. return
  196. }
  197. calculateMappingItem := new(EdbInfoCalculateMapping)
  198. calculateMappingItem.CreateTime = time.Now()
  199. calculateMappingItem.ModifyTime = time.Now()
  200. calculateMappingItem.Sort = 1
  201. calculateMappingItem.EdbCode = edbInfo.EdbCode
  202. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  203. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  204. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  205. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  206. calculateMappingItem.FromSource = fromEdbInfo.Source
  207. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  208. calculateMappingItem.FromTag = ""
  209. calculateMappingItem.Source = edbInfo.Source
  210. calculateMappingItem.SourceName = edbInfo.SourceName
  211. calculateMappingItem.FromSubSource = edbInfo.SubSource
  212. _, err = to.Insert(calculateMappingItem)
  213. if err != nil {
  214. return
  215. }
  216. //计算数据
  217. err, errMsg = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, edbInfo.CalculateFormula)
  218. return
  219. }
  220. func (obj CalculateRangeAnalysis) Refresh(params RefreshParams) (err error, errMsg string) {
  221. edbInfo := params.EdbInfo
  222. edbInfoCalculateDetailList, err := GetEdbInfoCalculateDetailList(edbInfo.EdbInfoId)
  223. if err != nil {
  224. return
  225. }
  226. var fromEdbInfo *EdbInfo
  227. for _, v := range edbInfoCalculateDetailList {
  228. fromEdbInfo, _ = GetEdbInfoById(v.FromEdbInfoId)
  229. break
  230. }
  231. if fromEdbInfo == nil {
  232. errMsg = "指标异常"
  233. err = errors.New(errMsg)
  234. return
  235. }
  236. o := orm.NewOrm()
  237. to, err := o.Begin()
  238. if err != nil {
  239. return
  240. }
  241. defer func() {
  242. if err != nil {
  243. fmt.Println("RefreshAllCalculateRangeAnalysis,Err:" + err.Error())
  244. _ = to.Rollback()
  245. } else {
  246. _ = to.Commit()
  247. }
  248. }()
  249. // 计算数据
  250. err, errMsg = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, edbInfo.CalculateFormula)
  251. return
  252. }
  253. func (obj CalculateRangeAnalysis) refresh(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, calculateFormula string) (err error, errMsg string) {
  254. edbInfoIdStr := strconv.Itoa(edbInfoId)
  255. tableName := GetEdbDataTableName(obj.GetSource(), utils.DATA_SUB_SOURCE_EDB)
  256. //获取扩散指数指标所有数据
  257. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  258. if err != nil {
  259. return
  260. }
  261. //计算指标的map
  262. existDataMap := make(map[string]*EdbData, 0)
  263. removeDateMap := make(map[string]string)
  264. for _, v := range existDataList {
  265. existDataMap[v.DataTime] = v
  266. removeDateMap[v.DataTime] = ``
  267. }
  268. var rangeAnalysisConf RangeAnalysisCalculateFormula
  269. //fmt.Println("calculateFormula:", calculateFormula)
  270. err = json.Unmarshal([]byte(calculateFormula), &rangeAnalysisConf)
  271. if err != nil {
  272. err = fmt.Errorf("解析区间计算公式失败 %s", err.Error())
  273. return
  274. }
  275. rangeAnalysisChartData, err := GetRangeAnalysisChartDataByEdbInfo(fromEdbInfo, rangeAnalysisConf)
  276. if err != nil {
  277. err = fmt.Errorf("获取区间计算数据失败 %s", err.Error())
  278. return
  279. }
  280. addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  281. var isAdd bool
  282. for _, item := range rangeAnalysisChartData {
  283. currDateStr := item.DataTime
  284. currVal := item.Value
  285. // 判断扩散指数指标是否存在数据
  286. if existData, ok := existDataMap[currDateStr]; ok {
  287. // 处理扩散指数数据的值
  288. existValStr := existData.Value
  289. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  290. if tmpErr != nil {
  291. err = tmpErr
  292. return
  293. }
  294. existVal, _ := existValDeci.Round(4).Float64()
  295. // 判断扩散指数数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
  296. if existVal != currVal {
  297. err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
  298. if err != nil {
  299. return
  300. }
  301. }
  302. } else {
  303. // 直接入库
  304. timestamp := item.DataTimestamp
  305. timestampStr := fmt.Sprintf("%d", timestamp)
  306. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timestampStr, fmt.Sprint(currVal))
  307. isAdd = true
  308. }
  309. delete(removeDateMap, currDateStr)
  310. }
  311. // 数据入库
  312. {
  313. if isAdd {
  314. addSql = strings.TrimRight(addSql, ",")
  315. _, err = to.Raw(addSql).Exec()
  316. }
  317. // 移除不存在的日期数据
  318. if len(removeDateMap) > 0 {
  319. removeDateList := make([]string, 0) //需要移除的日期
  320. for k := range removeDateMap {
  321. removeDateList = append(removeDateList, k)
  322. }
  323. removeDateStr := strings.Join(removeDateList, `","`)
  324. removeDateStr = `"` + removeDateStr + `"`
  325. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  326. _, err = to.Raw(sql, edbInfoId).Exec()
  327. if err != nil {
  328. err = fmt.Errorf("删除扩散指数指标数据失败,Err:" + err.Error())
  329. return
  330. }
  331. }
  332. }
  333. return
  334. }
  335. // GetAutoCalculateDateDataList 获取当前时间相关的区间作为计算依据
  336. func GetAutoCalculateDateDataList(currentDate string, dataList []*EdbInfoSearchData, req RangeAnalysisCalculateFormula) (newDataList []*EdbInfoSearchData, err error) {
  337. currentDateTime, _ := time.ParseInLocation(utils.FormatDate, currentDate, time.Local)
  338. switch req.DateRangeType {
  339. case 0:
  340. // 智能划分得到一个开始日期,和结束日期
  341. var startDateTime time.Time
  342. if req.AutoDateConf.IsAutoStartDate == 0 { //固定设置
  343. startDate := req.AutoDateConf.StartDate
  344. if startDate == "" {
  345. startDate = "2020-01-01"
  346. }
  347. startDateTime, _ = time.ParseInLocation(utils.FormatDate, startDate, time.Local)
  348. } else {
  349. startConf := req.AutoDateConf.StartDateConf
  350. startDate := ""
  351. if startConf.BaseDateType == 0 { //
  352. startDate = currentDate
  353. } else if startConf.BaseDateType == 1 {
  354. startDate = time.Now().Format(utils.FormatDate)
  355. }
  356. if startConf.MoveForward > 0 {
  357. startDate = GetEdbDateByMoveForward(startDate, startConf.MoveForward, dataList)
  358. }
  359. if len(startConf.DateChange) > 0 {
  360. startDate, err = HandleEdbDateChange(startDate, startConf.DateChange)
  361. if err != nil {
  362. err = fmt.Errorf("智能划分开始日期处理失败:%s", err.Error())
  363. return
  364. }
  365. }
  366. startDateTime, _ = time.ParseInLocation(utils.FormatDate, startDate, time.Local)
  367. }
  368. var calStartTime, calEndTime time.Time
  369. if currentDateTime.Before(startDateTime) {
  370. calStartTime = currentDateTime
  371. calEndTime = startDateTime
  372. } else {
  373. calStartTime = startDateTime
  374. calEndTime = currentDateTime
  375. }
  376. // 根据日期,获取数据
  377. for _, vv := range dataList {
  378. dataTimeT, _ := time.ParseInLocation(utils.FormatDate, vv.DataTime, time.Local)
  379. if dataTimeT.After(calStartTime) && dataTimeT.Before(calEndTime) ||
  380. dataTimeT.Equal(calStartTime) ||
  381. dataTimeT.Equal(calEndTime) {
  382. newDataList = append(newDataList, vv)
  383. }
  384. }
  385. }
  386. return
  387. }
  388. // HandleDataByCalculateType 根据计算公式处理数据
  389. func HandleRangeAnalysisDataByCalculateType(originList []*ChartRangeAnalysisDateDataItem, originDataList []*EdbInfoSearchData, req RangeAnalysisCalculateFormula) (newList []*EdbInfoSearchData, err error) {
  390. if len(originList) == 0 {
  391. return
  392. }
  393. calculateType := req.CalculateType
  394. switch calculateType {
  395. case 0: //均值
  396. var sum float64
  397. if req.DateRangeType == 0 && req.AutoDateConf.IsAutoStartDate > 0 {
  398. for _, item := range originList {
  399. for _, v := range item.DataList {
  400. sum = 0
  401. //计算的数据返回需要重新确定
  402. calDataList, e := GetAutoCalculateDateDataList(v.DataTime, originDataList, req)
  403. if e != nil {
  404. err = fmt.Errorf("获取区间数据失败:%s", e.Error())
  405. return
  406. }
  407. for _, vv := range calDataList {
  408. sum += vv.Value
  409. }
  410. val := sum / float64(len(calDataList))
  411. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  412. newList = append(newList, &EdbInfoSearchData{
  413. DataTime: v.DataTime,
  414. Value: val,
  415. DataTimestamp: v.DataTimestamp,
  416. })
  417. }
  418. }
  419. } else {
  420. for _, item := range originList {
  421. sum = 0
  422. for k, v := range item.DataList {
  423. sum += v.Value
  424. val := sum / float64(k+1)
  425. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  426. newList = append(newList, &EdbInfoSearchData{
  427. DataTime: v.DataTime,
  428. Value: val,
  429. DataTimestamp: v.DataTimestamp,
  430. })
  431. }
  432. }
  433. }
  434. case 1: //累计值
  435. var sum float64
  436. if req.DateRangeType == 0 && req.AutoDateConf.IsAutoStartDate > 0 {
  437. for _, item := range originList {
  438. sum = 0
  439. for _, v := range item.DataList {
  440. sum = 0
  441. //计算的数据返回需要重新确定
  442. calDataList, e := GetAutoCalculateDateDataList(v.DataTime, originDataList, req)
  443. if e != nil {
  444. err = fmt.Errorf("获取区间数据失败:%s", e.Error())
  445. return
  446. }
  447. for _, vv := range calDataList {
  448. sum += vv.Value
  449. }
  450. val := sum
  451. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  452. newList = append(newList, &EdbInfoSearchData{
  453. DataTime: v.DataTime,
  454. Value: val,
  455. DataTimestamp: v.DataTimestamp,
  456. })
  457. }
  458. }
  459. } else {
  460. for _, item := range originList {
  461. sum = 0
  462. for _, v := range item.DataList {
  463. sum += v.Value
  464. val := sum
  465. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  466. newList = append(newList, &EdbInfoSearchData{
  467. DataTime: v.DataTime,
  468. Value: val,
  469. DataTimestamp: v.DataTimestamp,
  470. })
  471. }
  472. }
  473. }
  474. case 2: //涨幅
  475. if req.DateRangeType == 0 && req.AutoDateConf.IsAutoStartDate > 0 {
  476. for _, item := range originList {
  477. for _, v := range item.DataList {
  478. var baseVal float64
  479. //计算的数据返回需要重新确定
  480. calDataList, e := GetAutoCalculateDateDataList(v.DataTime, originDataList, req)
  481. if e != nil {
  482. err = fmt.Errorf("获取区间数据失败:%s", e.Error())
  483. return
  484. }
  485. if len(calDataList) == 0 {
  486. continue
  487. }
  488. baseVal = calDataList[0].Value
  489. baseDate := calDataList[0].DataTime
  490. if baseVal == 0 {
  491. continue
  492. }
  493. if v.DataTime == baseDate {
  494. continue
  495. }
  496. val := (v.Value - baseVal) / baseVal
  497. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  498. newList = append(newList, &EdbInfoSearchData{
  499. DataTime: v.DataTime,
  500. Value: val,
  501. DataTimestamp: v.DataTimestamp,
  502. })
  503. }
  504. }
  505. } else {
  506. for _, item := range originList {
  507. if len(item.DataList) == 0 {
  508. break
  509. }
  510. baseVal := item.DataList[0].Value
  511. baseDate := item.DataList[0].DataTime
  512. if baseVal == 0 {
  513. break
  514. }
  515. for _, v := range item.DataList {
  516. if v.DataTime == baseDate {
  517. continue
  518. }
  519. val := (v.Value - baseVal) / baseVal
  520. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  521. newList = append(newList, &EdbInfoSearchData{
  522. DataTime: v.DataTime,
  523. Value: val,
  524. DataTimestamp: v.DataTimestamp,
  525. })
  526. }
  527. }
  528. }
  529. case 3: //复合增长率
  530. if req.DateRangeType == 0 && req.AutoDateConf.IsAutoStartDate > 0 {
  531. for _, item := range originList {
  532. for _, v := range item.DataList {
  533. var baseVal float64
  534. var baseDate string
  535. calDataList, e := GetAutoCalculateDateDataList(v.DataTime, originDataList, req)
  536. if e != nil {
  537. err = fmt.Errorf("获取区间数据失败:%s", e.Error())
  538. return
  539. }
  540. if len(calDataList) == 0 {
  541. continue
  542. }
  543. baseVal = calDataList[0].Value
  544. baseDate = calDataList[0].DataTime
  545. if v.DataTime == baseDate {
  546. continue
  547. }
  548. if baseVal == 0 {
  549. continue
  550. }
  551. baseDateT, e := time.ParseInLocation(utils.FormatDate, baseDate, time.Local)
  552. if e != nil {
  553. err = fmt.Errorf("time.ParseInLocation err: %v", e)
  554. return
  555. }
  556. tmpT, e := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
  557. if e != nil {
  558. err = fmt.Errorf("time.ParseInLocation err: %v", e)
  559. return
  560. }
  561. // 计算两个日期相差的天数
  562. diff := tmpT.Sub(baseDateT).Hours() / 24 / 365
  563. val := v.Value / baseVal
  564. val = math.Pow(val, 1/diff) - 1
  565. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  566. newList = append(newList, &EdbInfoSearchData{DataTime: v.DataTime, Value: val, DataTimestamp: v.DataTimestamp})
  567. }
  568. }
  569. } else {
  570. for _, item := range originList {
  571. if len(item.DataList) == 0 {
  572. break
  573. }
  574. baseVal := item.DataList[0].Value
  575. baseDate := item.DataList[0].DataTime
  576. if baseVal == 0 {
  577. break
  578. }
  579. for _, v := range item.DataList {
  580. if v.DataTime == baseDate {
  581. continue
  582. }
  583. baseDateT, e := time.ParseInLocation(utils.FormatDate, baseDate, time.Local)
  584. if e != nil {
  585. err = fmt.Errorf("time.ParseInLocation err: %v", e)
  586. return
  587. }
  588. tmpT, e := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
  589. if e != nil {
  590. err = fmt.Errorf("time.ParseInLocation err: %v", e)
  591. return
  592. }
  593. // 计算两个日期相差的天数
  594. diff := tmpT.Sub(baseDateT).Hours() / 24 / 365
  595. val := v.Value / baseVal
  596. val = math.Pow(val, 1/diff) - 1
  597. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  598. newList = append(newList, &EdbInfoSearchData{DataTime: v.DataTime, Value: val, DataTimestamp: v.DataTimestamp})
  599. }
  600. }
  601. }
  602. case 4: //最大值
  603. var maxVal float64
  604. if req.DateRangeType == 0 && req.AutoDateConf.IsAutoStartDate > 0 {
  605. for _, item := range originList {
  606. for _, v := range item.DataList {
  607. calDataList, e := GetAutoCalculateDateDataList(v.DataTime, originDataList, req)
  608. if e != nil {
  609. err = fmt.Errorf("获取区间数据失败:%s", e.Error())
  610. return
  611. }
  612. for kk, vv := range calDataList {
  613. if kk == 0 {
  614. maxVal = vv.Value
  615. }
  616. if vv.Value > maxVal {
  617. maxVal = vv.Value
  618. }
  619. }
  620. val := maxVal
  621. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  622. newList = append(newList, &EdbInfoSearchData{DataTime: v.DataTime, Value: val, DataTimestamp: v.DataTimestamp})
  623. }
  624. }
  625. } else {
  626. for _, item := range originList {
  627. for k, v := range item.DataList {
  628. if k == 0 {
  629. maxVal = v.Value
  630. }
  631. if v.Value > maxVal {
  632. maxVal = v.Value
  633. }
  634. val := maxVal
  635. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  636. newList = append(newList, &EdbInfoSearchData{DataTime: v.DataTime, Value: val, DataTimestamp: v.DataTimestamp})
  637. }
  638. }
  639. }
  640. case 5: //最小值
  641. var minVal float64
  642. if req.DateRangeType == 0 && req.AutoDateConf.IsAutoStartDate > 0 {
  643. for _, item := range originList {
  644. for _, v := range item.DataList {
  645. calDataList, e := GetAutoCalculateDateDataList(v.DataTime, originDataList, req)
  646. if e != nil {
  647. err = fmt.Errorf("获取区间数据失败:%s", e.Error())
  648. return
  649. }
  650. for kk, vv := range calDataList {
  651. if kk == 0 {
  652. minVal = vv.Value
  653. }
  654. if vv.Value < minVal {
  655. minVal = vv.Value
  656. }
  657. }
  658. val := minVal
  659. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  660. newList = append(newList, &EdbInfoSearchData{DataTime: v.DataTime, Value: val, DataTimestamp: v.DataTimestamp})
  661. }
  662. }
  663. } else {
  664. for _, item := range originList {
  665. for k, v := range item.DataList {
  666. if k == 0 {
  667. minVal = v.Value
  668. }
  669. if v.Value < minVal {
  670. minVal = v.Value
  671. }
  672. val := minVal
  673. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  674. newList = append(newList, &EdbInfoSearchData{DataTime: v.DataTime, Value: val, DataTimestamp: v.DataTimestamp})
  675. }
  676. }
  677. }
  678. }
  679. return
  680. }
  681. // GetRangeAnalysisChartDataByEdbInfo 区间计算
  682. func GetRangeAnalysisChartDataByEdbInfo(fromEdbInfo *EdbInfo, calculateFormula RangeAnalysisCalculateFormula) (newDataList []*EdbInfoSearchData, err error) {
  683. // 指标的开始日期和结束日期
  684. edbStartDateTime, _ := time.ParseInLocation(utils.FormatDate, fromEdbInfo.StartDate, time.Local)
  685. //edbStartDate := edbStartDateTime.AddDate(0, 0, 1).Format(utils.FormatDate)
  686. edbEndDateTime, _ := time.ParseInLocation(utils.FormatDate, fromEdbInfo.EndDate, time.Local)
  687. edbEndDate := edbEndDateTime.Format(utils.FormatDate)
  688. // 获取时间基准指标在时间区间内的值
  689. dataList := make([]*EdbInfoSearchData, 0)
  690. switch fromEdbInfo.EdbInfoType {
  691. case 0:
  692. //获取来源指标的数据
  693. dataList, err = GetEdbDataListAll(fromEdbInfo.Source, fromEdbInfo.SubSource,
  694. FindEdbDataListAllCond{
  695. EdbInfoId: fromEdbInfo.EdbInfoId,
  696. }, 1)
  697. case 1:
  698. dataList, err = GetPredictEdbDataListAllByStartDate(fromEdbInfo, 1, "")
  699. default:
  700. err = errors.New(fmt.Sprint("获取失败,指标base类型异常", fromEdbInfo.EdbInfoType))
  701. return
  702. }
  703. if err != nil {
  704. err = fmt.Errorf("获取时间基准指标在时间区间内的值失败,Err:" + err.Error())
  705. return
  706. }
  707. dateList := make([]*ChartRangeAnalysisDateDataItem, 0)
  708. switch calculateFormula.DateRangeType {
  709. case 0:
  710. // 智能划分得到一个开始日期,和结束日期
  711. var startDateTime, endDateTime time.Time
  712. startDateTime = edbStartDateTime
  713. if calculateFormula.AutoDateConf.IsAutoStartDate == 0 { //固定设置
  714. startDate := calculateFormula.AutoDateConf.StartDate
  715. if startDate == "" {
  716. startDate = "2020-01-01"
  717. }
  718. startDateTime, _ = time.ParseInLocation(utils.FormatDate, startDate, time.Local)
  719. }
  720. if calculateFormula.AutoDateConf.IsAutoEndDate == 0 { //固定设置
  721. endDate := calculateFormula.AutoDateConf.EndDate
  722. if endDate == "" {
  723. err = fmt.Errorf("智能划分截止日期处理失败:请输入截止日期")
  724. return
  725. }
  726. // todo 如果截止日期比指标日期还要大,则用指标的最新日期
  727. endDateTime, _ = time.ParseInLocation(utils.FormatDate, endDate, time.Local)
  728. } else {
  729. endConf := calculateFormula.AutoDateConf.EndDateConf
  730. endDate := edbEndDate
  731. if endConf.MoveForward > 0 {
  732. endDate = GetEdbDateByMoveForward(endDate, endConf.MoveForward, dataList)
  733. }
  734. if len(endConf.DateChange) > 0 {
  735. endDate, err = HandleEdbDateChange(endDate, endConf.DateChange)
  736. if err != nil {
  737. err = fmt.Errorf("智能划分结束日期处理失败:%s", err.Error())
  738. return
  739. }
  740. }
  741. endDateTime, _ = time.ParseInLocation(utils.FormatDate, endDate, time.Local)
  742. }
  743. dateList = append(dateList, &ChartRangeAnalysisDateDataItem{
  744. StartDate: startDateTime,
  745. EndDate: endDateTime})
  746. case 1:
  747. // 手工划分得到多个开始日期和结束日期(已排序)
  748. for _, v := range calculateFormula.ManualDateConf {
  749. startDateT, _ := time.ParseInLocation(utils.FormatDate, v.StartDate, time.Local)
  750. endDateT, _ := time.ParseInLocation(utils.FormatDate, v.EndDate, time.Local)
  751. tmp := &ChartRangeAnalysisDateDataItem{
  752. StartDate: startDateT,
  753. EndDate: endDateT,
  754. }
  755. dateList = append(dateList, tmp)
  756. }
  757. case 2:
  758. // 跨年划分得到多个开始日期和结束日期
  759. startYear := edbStartDateTime.Year()
  760. endYear := edbEndDateTime.Year()
  761. startDay := calculateFormula.YearDateConf.StartDay
  762. endDay := calculateFormula.YearDateConf.EndDay
  763. for year := startYear; year <= endYear; year++ {
  764. startDate := fmt.Sprintf("%d-%s", year, startDay)
  765. endDate := fmt.Sprintf("%d-%s", year+1, endDay)
  766. startDateTime, _ := time.ParseInLocation(utils.FormatDate, startDate, time.Local)
  767. endDateTime, _ := time.ParseInLocation(utils.FormatDate, endDate, time.Local)
  768. if startDateTime.Before(edbStartDateTime) {
  769. break
  770. }
  771. tmp := &ChartRangeAnalysisDateDataItem{
  772. StartDate: startDateTime,
  773. EndDate: endDateTime,
  774. }
  775. dateList = append(dateList, tmp)
  776. }
  777. }
  778. // 根据日期,获取数据
  779. for _, v := range dateList {
  780. for _, vv := range dataList {
  781. dataTimeT, _ := time.ParseInLocation(utils.FormatDate, vv.DataTime, time.Local)
  782. if dataTimeT.After(v.StartDate) && dataTimeT.Before(v.EndDate) ||
  783. dataTimeT.Equal(v.StartDate) ||
  784. dataTimeT.Equal(v.EndDate) {
  785. v.DataList = append(v.DataList, vv)
  786. }
  787. }
  788. }
  789. // 根据时间区间类型来获取数据的计算窗口,然后再拼接成整段数据
  790. newDataList, err = HandleRangeAnalysisDataByCalculateType(dateList, dataList, calculateFormula)
  791. if err != nil {
  792. return
  793. }
  794. if calculateFormula.UnNormalDataDealType > 0 {
  795. switch calculateFormula.UnNormalDataDealType { //0:不处理,1:剔除,2替换
  796. case 1:
  797. dealDataList := make([]*EdbInfoSearchData, 0)
  798. for _, v := range newDataList {
  799. if !utils.CompareFloatByOpStrings(calculateFormula.UnNormalDataConf.Formula, v.Value, calculateFormula.UnNormalDataConf.Value) {
  800. dealDataList = append(dealDataList, v)
  801. }
  802. }
  803. newDataList = dealDataList
  804. case 2:
  805. for i, v := range newDataList {
  806. if utils.CompareFloatByOpStrings(calculateFormula.UnNormalDataConf.Formula, v.Value, calculateFormula.UnNormalDataConf.Value) {
  807. newDataList[i].Value = calculateFormula.UnNormalDataConf.ReplaceValue
  808. }
  809. }
  810. }
  811. }
  812. if calculateFormula.DataConvertType > 0 {
  813. // 数据转换类型 0不转, 1乘 2除 3对数
  814. switch calculateFormula.DataConvertType {
  815. case 1:
  816. for i, v := range newDataList {
  817. val := v.Value * calculateFormula.DataConvertConf.Value
  818. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  819. newDataList[i].Value = val
  820. }
  821. //item.MaxData = item.MaxData * v.ConvertValue
  822. //item.MinData = item.MinData * v.ConvertValue
  823. case 2:
  824. for i, v := range newDataList {
  825. val := v.Value / calculateFormula.DataConvertConf.Value
  826. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  827. newDataList[i].Value = val
  828. }
  829. //item.MaxData = item.MaxData / v.ConvertValue
  830. //item.MinData = item.MinData / v.ConvertValue
  831. case 3:
  832. for i, v := range newDataList {
  833. if v.Value <= 0 {
  834. err = errors.New("数据中含有负数或0,无法对数运算")
  835. return
  836. }
  837. val := math.Log(v.Value) / math.Log(calculateFormula.DataConvertConf.Value)
  838. val, _ = decimal.NewFromFloat(val).Round(4).Float64()
  839. newDataList[i].Value = val
  840. }
  841. //item.MaxData = math.Log(item.MaxData) / math.Log(v.ConvertValue)
  842. //item.MinData = math.Log(item.MinData) / math.Log(v.ConvertValue)
  843. }
  844. }
  845. return
  846. }
  847. func GetEdbDateByMoveForward(startDate string, moveForward int, edbDataList []*EdbInfoSearchData) (date string) {
  848. // 根据日期进行排序
  849. index := 0
  850. length := len(edbDataList)
  851. for i := length - 1; i >= 0; i-- {
  852. item := edbDataList[i]
  853. if item.DataTime == startDate {
  854. index += 1
  855. continue
  856. }
  857. if index >= moveForward {
  858. date = item.DataTime
  859. break
  860. }
  861. if index > 0 {
  862. index += 1
  863. date = item.DataTime
  864. }
  865. }
  866. return
  867. }
  868. // HandleEdbDateChange 处理日期变换
  869. func HandleEdbDateChange(date string, dateChange []*EdbDataDateChangeConf) (newDate string, err error) {
  870. newDate = date
  871. if newDate != "" {
  872. if len(dateChange) > 0 {
  873. var dateTime time.Time
  874. dateTime, err = time.ParseInLocation(utils.FormatDate, newDate, time.Local)
  875. if err != nil {
  876. err = fmt.Errorf("日期解析失败: %s", err.Error())
  877. return
  878. }
  879. for _, v := range dateChange {
  880. if v.ChangeType == 1 {
  881. dateTime = dateTime.AddDate(v.Year, v.Month, v.Day)
  882. newDate = dateTime.Format(utils.FormatDate)
  883. } else if v.ChangeType == 2 {
  884. newDate, err, _ = utils.HandleSystemAppointDateT(dateTime, v.FrequencyDay, v.Frequency)
  885. if err != nil {
  886. return
  887. }
  888. dateTime, err = time.ParseInLocation(utils.FormatDate, newDate, time.Local)
  889. if err != nil {
  890. err = fmt.Errorf("日期解析失败: %s", err.Error())
  891. return
  892. }
  893. }
  894. }
  895. }
  896. }
  897. return
  898. }
  899. // GetSource 获取来源编码id
  900. func (obj CalculateRangeAnalysis) GetSource() int {
  901. return utils.DATA_SOURCE_CALCULATE_RANGEANLYSIS
  902. }
  903. // GetSourceName 获取来源名称
  904. func (obj CalculateRangeAnalysis) GetSourceName() string {
  905. return utils.DATA_SOURCE_NAME_CALCULATE_RANGEANLYSIS
  906. }
  907. // GetEdbType 获取指标类型
  908. func (obj CalculateRangeAnalysis) GetEdbType() int {
  909. return utils.CALCULATE_EDB_TYPE
  910. }