predict_edb_data_calculate_kszs.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/shopspring/decimal"
  8. "hongze/hongze_edb_lib/utils"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. // SavePredictCalculateKszs 预测扩散指数
  14. func SavePredictCalculateKszs(reqEdbInfoId, classifyId int, edbName, frequency, unit, formula string, relationCalculateEdbInfoIdList []EdbInfoCalculateEdbInfoIdReq, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
  15. o := orm.NewOrm()
  16. to, err := o.Begin()
  17. if err != nil {
  18. return
  19. }
  20. defer func() {
  21. if err != nil {
  22. fmt.Println("SavePredictCalculateKszs,Err:" + err.Error())
  23. _ = to.Rollback()
  24. } else {
  25. _ = to.Commit()
  26. }
  27. }()
  28. fmt.Println("reqEdbInfoId:", reqEdbInfoId)
  29. tagMap := make(map[string]int) //指标的标签map
  30. relationEdbInfoList := make([]*EdbInfo, 0)
  31. if reqEdbInfoId <= 0 {
  32. edbInfo = &EdbInfo{
  33. //EdbInfoId: 0,
  34. EdbInfoType: 1,
  35. SourceName: utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_KSZS,
  36. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_KSZS,
  37. EdbCode: edbCode,
  38. EdbName: edbName,
  39. EdbNameSource: edbName,
  40. Frequency: frequency,
  41. Unit: unit,
  42. //StartDate: "",
  43. //EndDate: "",
  44. ClassifyId: classifyId,
  45. SysUserId: sysUserId,
  46. SysUserRealName: sysUserRealName,
  47. UniqueCode: uniqueCode,
  48. CreateTime: time.Now(),
  49. ModifyTime: time.Now(),
  50. MinValue: 0,
  51. MaxValue: 0,
  52. CalculateFormula: formula,
  53. EdbType: 2,
  54. Sort: 0,
  55. MoveType: 0,
  56. MoveFrequency: "",
  57. NoUpdate: 0,
  58. ServerUrl: "",
  59. EdbNameEn: "",
  60. UnitEn: "",
  61. LatestDate: "",
  62. LatestValue: 0,
  63. ChartImage: "",
  64. }
  65. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  66. if tmpErr != nil {
  67. err = tmpErr
  68. return
  69. }
  70. edbInfo.EdbInfoId = int(newEdbInfoId)
  71. //关联关系
  72. calculateMappingItemList := make([]*EdbInfoCalculateMapping, 0)
  73. for _, v := range relationCalculateEdbInfoIdList {
  74. tmpEdbInfo, tmpErr := GetEdbInfoById(v.EdbInfoId)
  75. if tmpErr != nil {
  76. err = tmpErr
  77. return
  78. }
  79. relationEdbInfoList = append(relationEdbInfoList, tmpEdbInfo)
  80. calculateMappingItem := new(EdbInfoCalculateMapping)
  81. calculateMappingItem.CreateTime = time.Now()
  82. calculateMappingItem.ModifyTime = time.Now()
  83. calculateMappingItem.Sort = 1
  84. calculateMappingItem.EdbCode = edbCode
  85. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  86. calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
  87. calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
  88. calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
  89. calculateMappingItem.FromSource = tmpEdbInfo.Source
  90. calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
  91. calculateMappingItem.FromTag = v.FromTag
  92. calculateMappingItem.Source = edbInfo.Source
  93. calculateMappingItem.SourceName = edbInfo.SourceName
  94. calculateMappingItemList = append(calculateMappingItemList, calculateMappingItem)
  95. tagMap[v.FromTag] = v.EdbInfoId
  96. }
  97. _, err = to.InsertMulti(len(calculateMappingItemList), calculateMappingItemList)
  98. if err != nil {
  99. return
  100. }
  101. } else {
  102. edbInfo, err = GetEdbInfoById(reqEdbInfoId)
  103. if err != nil {
  104. if err.Error() == utils.ErrNoRow() {
  105. errMsg = `获取指标信息失败`
  106. }
  107. return
  108. }
  109. if edbInfo.EdbInfoType != 1 {
  110. errMsg = `该指标不是预测指标`
  111. err = errors.New(errMsg)
  112. return
  113. }
  114. //修改指标信息
  115. edbInfo.EdbName = edbName
  116. edbInfo.EdbNameSource = edbName
  117. edbInfo.Frequency = frequency
  118. edbInfo.Unit = unit
  119. edbInfo.ClassifyId = classifyId
  120. edbInfo.CalculateFormula = formula
  121. edbInfo.ModifyTime = time.Now()
  122. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
  123. if err != nil {
  124. return
  125. }
  126. //删除,计算指标关联的,基础指标的关联关系
  127. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  128. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  129. if err != nil {
  130. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  131. return
  132. }
  133. //清空原有数据
  134. tableName := GetEdbDataTableName(edbInfo.Source)
  135. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  136. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  137. if err != nil {
  138. return
  139. }
  140. //关联关系
  141. calculateMappingItemList := make([]*EdbInfoCalculateMapping, 0)
  142. for _, v := range relationCalculateEdbInfoIdList {
  143. tmpEdbInfo, tmpErr := GetEdbInfoById(v.EdbInfoId)
  144. if tmpErr != nil {
  145. err = tmpErr
  146. return
  147. }
  148. relationEdbInfoList = append(relationEdbInfoList, tmpEdbInfo)
  149. calculateMappingItem := new(EdbInfoCalculateMapping)
  150. calculateMappingItem.CreateTime = time.Now()
  151. calculateMappingItem.ModifyTime = time.Now()
  152. calculateMappingItem.Sort = 1
  153. calculateMappingItem.EdbCode = edbInfo.EdbCode
  154. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  155. calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
  156. calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
  157. calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
  158. calculateMappingItem.FromSource = tmpEdbInfo.Source
  159. calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
  160. calculateMappingItem.FromTag = v.FromTag
  161. calculateMappingItem.Source = edbInfo.Source
  162. calculateMappingItem.SourceName = edbInfo.SourceName
  163. calculateMappingItemList = append(calculateMappingItemList, calculateMappingItem)
  164. tagMap[v.FromTag] = v.EdbInfoId
  165. }
  166. _, err = to.InsertMulti(len(calculateMappingItemList), calculateMappingItemList)
  167. if err != nil {
  168. return
  169. }
  170. }
  171. // 计算数据
  172. latestDateStr, latestValue, err = refreshAllPredictCalculateKszs(to, edbInfo.EdbInfoId, edbInfo.Source, relationEdbInfoList, edbCode, formula, tagMap)
  173. return
  174. }
  175. // RefreshAllPredictCalculateKszs 刷新全部预测扩散指数数据
  176. func RefreshAllPredictCalculateKszs(edbInfo *EdbInfo) (latestDateStr string, latestValue float64, err error) {
  177. edbInfoCalculateDetailList, err := GetEdbInfoCalculateDetailList(edbInfo.EdbInfoId)
  178. if err != nil {
  179. return
  180. }
  181. tagMap := make(map[string]int)
  182. relationEdbInfoList := make([]*EdbInfo, 0)
  183. for _, v := range edbInfoCalculateDetailList {
  184. tagMap[v.FromTag] = v.FromEdbInfoId
  185. fromEdbInfo, _ := GetEdbInfoById(v.FromEdbInfoId)
  186. relationEdbInfoList = append(relationEdbInfoList, fromEdbInfo)
  187. }
  188. o := orm.NewOrm()
  189. to, err := o.Begin()
  190. if err != nil {
  191. return
  192. }
  193. defer func() {
  194. if err != nil {
  195. fmt.Println("RefreshAllCalculateKszs,Err:" + err.Error())
  196. _ = to.Rollback()
  197. } else {
  198. _ = to.Commit()
  199. }
  200. }()
  201. // 计算数据
  202. latestDateStr, latestValue, err = refreshAllPredictCalculateKszs(to, edbInfo.EdbInfoId, edbInfo.Source, relationEdbInfoList, edbInfo.EdbCode, edbInfo.CalculateFormula, tagMap)
  203. return
  204. }
  205. // refreshAllPredictCalculateKszs 刷新预测年化数据
  206. func refreshAllPredictCalculateKszs(to orm.TxOrmer, edbInfoId, source int, relationEdbInfoList []*EdbInfo, edbCode, calculateFormula string, tagMap map[string]int) (latestDateStr string, latestValue float64, err error) {
  207. edbInfoIdStr := strconv.Itoa(edbInfoId)
  208. tableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_KSZS)
  209. // 获取扩散指标关联的指标id
  210. checkEdbInfoIdMap := make(map[int]int)
  211. {
  212. var config KszsConfig
  213. err = json.Unmarshal([]byte(calculateFormula), &config)
  214. if err != nil {
  215. return
  216. }
  217. if config.DateType == 1 {
  218. for _, tmpEdbInfoId := range tagMap {
  219. checkEdbInfoIdMap[tmpEdbInfoId] = tmpEdbInfoId
  220. }
  221. } else {
  222. for _, v := range config.CheckList {
  223. if tmpEdbInfoId, ok := tagMap[v]; ok {
  224. checkEdbInfoIdMap[tmpEdbInfoId] = tmpEdbInfoId
  225. }
  226. }
  227. }
  228. }
  229. //获取当前指标的所有数据
  230. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source)
  231. if err != nil {
  232. return
  233. }
  234. //计算指标的map
  235. existDataMap := make(map[string]*EdbData, 0)
  236. removeDateMap := make(map[string]string)
  237. for _, v := range existDataList {
  238. existDataMap[v.DataTime] = v
  239. removeDateMap[v.DataTime] = ``
  240. }
  241. var latestDateTime time.Time //真实数据的最后日期
  242. var hasValLatestDateTime time.Time // 存在数据的真实日期(正常情况下,这两个值是相等的,除非出现一种情况:真实数据的最后日期当天 计算不出结果,那么 hasValLatestDateTime 不等于 latestDateTime)
  243. //获取来源指标的数据
  244. relationEdbDataMap := make(map[int]map[string]float64)
  245. // 获取选择指标的 需要数据的 开始日期和结束日期
  246. var startDate, endDate time.Time
  247. for _, v := range relationEdbInfoList {
  248. tmpLatestDate, _ := time.ParseInLocation(utils.FormatDate, v.LatestDate, time.Local)
  249. if latestDateTime.IsZero() || latestDateTime.After(tmpLatestDate) {
  250. // 真实数据的最后日期
  251. latestDateTime = tmpLatestDate
  252. }
  253. tmpDataList, tmpErr := GetPredictEdbDataListAll(v, 1)
  254. if tmpErr != nil {
  255. err = tmpErr
  256. return
  257. }
  258. if tmpDataList != nil {
  259. if _, ok2 := checkEdbInfoIdMap[v.EdbInfoId]; ok2 {
  260. lenTmpDataList := len(tmpDataList)
  261. if lenTmpDataList > 0 {
  262. tmpStartTime, _ := time.ParseInLocation(utils.FormatDate, tmpDataList[0].DataTime, time.Local)
  263. tmpEndTime, _ := time.ParseInLocation(utils.FormatDate, tmpDataList[lenTmpDataList-1].DataTime, time.Local)
  264. if startDate.IsZero() || tmpStartTime.Before(startDate) {
  265. startDate = tmpStartTime
  266. }
  267. if tmpEndTime.IsZero() || tmpEndTime.After(endDate) {
  268. endDate = tmpEndTime
  269. }
  270. }
  271. }
  272. // 用上期的数据补充当期的数据处理
  273. handleDataMap := make(map[string]float64)
  274. err = HandleDataByPreviousData(tmpDataList, handleDataMap)
  275. if err != nil {
  276. return
  277. }
  278. relationEdbDataMap[v.EdbInfoId] = handleDataMap
  279. }
  280. }
  281. addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  282. var isAdd bool
  283. for currDate := startDate.AddDate(0, 0, 1); !currDate.After(endDate); currDate = currDate.AddDate(0, 0, 1) {
  284. currDateStr := currDate.Format(utils.FormatDate)
  285. //环差指数列表
  286. tmpValList := make([]float64, 0)
  287. for _, dataMap := range relationEdbDataMap {
  288. currVal, ok := dataMap[currDateStr]
  289. if !ok {
  290. continue
  291. }
  292. perVal, ok := dataMap[currDate.AddDate(0, 0, -1).Format(utils.FormatDate)]
  293. if !ok {
  294. continue
  295. }
  296. var tmpVal float64
  297. if currVal > perVal {
  298. tmpVal = 1
  299. } else if currVal == perVal {
  300. tmpVal = 0.5
  301. } else {
  302. tmpVal = 0
  303. }
  304. tmpValList = append(tmpValList, tmpVal)
  305. }
  306. lenTmpValList := len(tmpValList)
  307. if lenTmpValList <= 0 {
  308. continue
  309. }
  310. currValDeci := decimal.NewFromFloat(0)
  311. for _, tmpVal := range tmpValList {
  312. currValDeci = currValDeci.Add(decimal.NewFromFloat(tmpVal))
  313. }
  314. currVal, _ := currValDeci.Div(decimal.NewFromInt(int64(lenTmpValList))).Round(4).Float64()
  315. // 如果存在数据的真实日期为空,或者 当前日期 早于或等于 实际数据的日期,那么就给 存在数据的真实日期 赋值
  316. if hasValLatestDateTime.IsZero() || currDate.Before(latestDateTime) || currDate.Equal(latestDateTime) {
  317. latestValue = currVal
  318. hasValLatestDateTime = currDate
  319. }
  320. // 判断扩散指数指标是否存在数据
  321. if existData, ok := existDataMap[currDateStr]; ok {
  322. // 处理扩散指数数据的值
  323. existValStr := existData.Value
  324. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  325. if tmpErr != nil {
  326. err = tmpErr
  327. return
  328. }
  329. existVal, _ := existValDeci.Round(4).Float64()
  330. // 判断扩散指数数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
  331. if existVal != currVal {
  332. err = ModifyEdbDataById(source, existData.EdbDataId, fmt.Sprint(currVal))
  333. if err != nil {
  334. return
  335. }
  336. }
  337. } else {
  338. // 直接入库
  339. timestamp := currDate.UnixNano() / 1e6
  340. timestampStr := fmt.Sprintf("%d", timestamp)
  341. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timestampStr, fmt.Sprint(currVal))
  342. isAdd = true
  343. }
  344. delete(removeDateMap, currDateStr)
  345. }
  346. if isAdd {
  347. addSql = strings.TrimRight(addSql, ",")
  348. _, err = to.Raw(addSql).Exec()
  349. }
  350. // 移除不存在的日期数据
  351. if len(removeDateMap) > 0 {
  352. removeDateList := make([]string, 0) //需要移除的日期
  353. for k := range removeDateMap {
  354. removeDateList = append(removeDateList, k)
  355. }
  356. removeDateStr := strings.Join(removeDateList, `","`)
  357. removeDateStr = `"` + removeDateStr + `"`
  358. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  359. _, err = to.Raw(sql, edbInfoId).Exec()
  360. if err != nil {
  361. err = fmt.Errorf("删除扩散指数指标数据失败,Err:" + err.Error())
  362. return
  363. }
  364. }
  365. // 真实数据的最后日期
  366. latestDateStr = hasValLatestDateTime.Format(utils.FormatDate)
  367. return
  368. }