predict_edb_data_calculate_bp.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. package models
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/beego/beego/v2/client/orm"
  6. "github.com/shopspring/decimal"
  7. "hongze/hongze_edb_lib/utils"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // SavePredictCalculateBp 变频
  13. func SavePredictCalculateBp(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error) {
  14. o := orm.NewOrm()
  15. to, err := o.Begin()
  16. if err != nil {
  17. return
  18. }
  19. defer func() {
  20. if err != nil {
  21. fmt.Println("AddPredictCalculateBp,Err:" + err.Error())
  22. _ = to.Rollback()
  23. } else {
  24. _ = to.Commit()
  25. }
  26. }()
  27. if req.EdbInfoId <= 0 {
  28. edbInfo = new(EdbInfo)
  29. edbInfo.EdbInfoType = 1
  30. edbInfo.Source = utils.DATA_SOURCE_PREDICT_CALCULATE_BP
  31. edbInfo.SourceName = "预测变频"
  32. edbInfo.EdbCode = edbCode
  33. edbInfo.EdbName = req.EdbName
  34. edbInfo.EdbNameSource = req.EdbName
  35. edbInfo.Frequency = req.Frequency
  36. edbInfo.Unit = req.Unit
  37. edbInfo.ClassifyId = req.ClassifyId
  38. edbInfo.SysUserId = sysUserId
  39. edbInfo.SysUserRealName = sysUserRealName
  40. edbInfo.CreateTime = time.Now()
  41. edbInfo.ModifyTime = time.Now()
  42. edbInfo.UniqueCode = uniqueCode
  43. edbInfo.CalculateFormula = req.Formula
  44. edbInfo.EdbType = 2
  45. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  46. if tmpErr != nil {
  47. err = tmpErr
  48. return
  49. }
  50. edbInfo.EdbInfoId = int(newEdbInfoId)
  51. //关联关系
  52. {
  53. calculateMappingItem := new(EdbInfoCalculateMapping)
  54. calculateMappingItem.CreateTime = time.Now()
  55. calculateMappingItem.ModifyTime = time.Now()
  56. calculateMappingItem.Sort = 1
  57. calculateMappingItem.EdbCode = edbCode
  58. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  59. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  60. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  61. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  62. calculateMappingItem.FromSource = fromEdbInfo.Source
  63. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  64. calculateMappingItem.FromTag = ""
  65. calculateMappingItem.Source = edbInfo.Source
  66. calculateMappingItem.SourceName = edbInfo.SourceName
  67. _, err = to.Insert(calculateMappingItem)
  68. if err != nil {
  69. return
  70. }
  71. }
  72. } else {
  73. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  74. if err != nil {
  75. return
  76. }
  77. latestDateStr = edbInfo.LatestDate
  78. latestValue = edbInfo.LatestValue
  79. //修改指标信息
  80. edbInfo.EdbName = req.EdbName
  81. edbInfo.EdbNameSource = req.EdbName
  82. edbInfo.Frequency = req.Frequency
  83. edbInfo.Unit = req.Unit
  84. edbInfo.ClassifyId = req.ClassifyId
  85. edbInfo.ModifyTime = time.Now()
  86. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
  87. if err != nil {
  88. return
  89. }
  90. //判断计算指标是否被更换
  91. var existCondition string
  92. var existPars []interface{}
  93. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  94. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  95. count, e := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  96. if e != nil {
  97. err = errors.New("判断指标是否改变失败,Err:" + e.Error())
  98. return
  99. }
  100. if count > 0 { // 指标未被替换,无需重新计算
  101. return
  102. }
  103. //删除,计算指标关联的,基础指标的关联关系
  104. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  105. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  106. if err != nil {
  107. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  108. return
  109. }
  110. //清空原有数据
  111. sql = ` DELETE FROM edb_data_predict_calculate_bp WHERE edb_info_id = ? `
  112. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  113. if err != nil {
  114. return
  115. }
  116. //关联关系
  117. {
  118. calculateMappingItem := &EdbInfoCalculateMapping{
  119. EdbInfoCalculateMappingId: 0,
  120. EdbInfoId: edbInfo.EdbInfoId,
  121. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_BP,
  122. SourceName: "预测变频",
  123. EdbCode: edbInfo.EdbCode,
  124. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  125. FromEdbCode: fromEdbInfo.EdbCode,
  126. FromEdbName: fromEdbInfo.EdbName,
  127. FromSource: fromEdbInfo.Source,
  128. FromSourceName: fromEdbInfo.SourceName,
  129. FromTag: "",
  130. Sort: 1,
  131. CreateTime: time.Now(),
  132. ModifyTime: time.Now(),
  133. }
  134. _, err = to.Insert(calculateMappingItem)
  135. if err != nil {
  136. return
  137. }
  138. }
  139. }
  140. //计算数据
  141. latestDateStr, latestValue, err = refreshAllPredictCalculateBp(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", 0)
  142. return
  143. }
  144. func RefreshAllPredictCalculateBp(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (latestDateStr string, latestValue float64, err error) {
  145. o := orm.NewOrm()
  146. to, err := o.Begin()
  147. if err != nil {
  148. return
  149. }
  150. defer func() {
  151. if err != nil {
  152. fmt.Println("RefreshAllPredictCalculateBp,Err:" + err.Error())
  153. _ = to.Rollback()
  154. } else {
  155. _ = to.Commit()
  156. }
  157. }()
  158. // 计算数据
  159. latestDateStr, latestValue, err = refreshAllPredictCalculateBp(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate, 1)
  160. return
  161. }
  162. // refreshAllPredictCalculateBp 刷新变频数据
  163. func refreshAllPredictCalculateBp(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, order int) (latestDateStr string, latestValue float64, err error) {
  164. edbInfoIdStr := strconv.Itoa(edbInfoId)
  165. // 获取关联指标数据
  166. dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, order, "")
  167. if err != nil {
  168. return
  169. }
  170. latestDateStr = fromEdbInfo.LatestDate
  171. var dateArr []string
  172. dataMap := make(map[string]*EdbInfoSearchData)
  173. fromDataMap := make(map[string]float64)
  174. //来源指指标数据
  175. for _, v := range dataList {
  176. dateArr = append(dateArr, v.DataTime)
  177. dataMap[v.DataTime] = v
  178. fromDataMap[v.DataTime] = v.Value
  179. }
  180. fmt.Println("source:", source)
  181. //获取变频指标所有数据
  182. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source)
  183. if err != nil {
  184. return
  185. }
  186. //计算指标的map
  187. existDataMap := make(map[string]*EdbData, 0)
  188. addSql := ` INSERT INTO edb_data_predict_calculate_bp(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  189. var isAdd bool
  190. var lastValue float64 //最后数据的值(float64)
  191. var lastValueStr string //最后数据的值(string)
  192. //待删除的日期
  193. removeDateList := make([]string, 0)
  194. if len(existDataList) > 0 {
  195. //第一个已经入库的日期
  196. firstExistDataTimeStr := existDataList[0].DataTime //计算指标数据第一条的日期字符串
  197. if len(dateArr) > 0 {
  198. firstFromDataTimeStr := dateArr[0] //来源数据第一条的日期字符串
  199. firstExistDataTime, _ := time.ParseInLocation(utils.FormatDate, firstExistDataTimeStr, time.Local) //计算指标数据第一条的日期(time类型)
  200. firstFromDataTime, _ := time.ParseInLocation(utils.FormatDate, firstFromDataTimeStr, time.Local) //来源数据第一条的日期(time类型)
  201. nowDateStr := time.Now().Format(utils.FormatDate) //当天日期字符串
  202. nowDate, _ := time.ParseInLocation(utils.FormatDate, nowDateStr, firstFromDataTime.Location()) //当天日期(time类型)
  203. lastValue = fromDataMap[firstFromDataTimeStr]
  204. lastValueStr = decimal.NewFromFloat(lastValue).String()
  205. //第一步: 判断来源指标的开始时间与计算指标的开始时间是否相等,相等的话,那么就不需要对两个时间之间的数据做处理
  206. if firstExistDataTimeStr != firstFromDataTimeStr {
  207. if firstExistDataTime.Before(firstFromDataTime) { //如果计算指标第一条数据的开始时间 早于 来源指标的第一条开始时间,那么需要对两个时间之间的计算指标数据做 删除处理
  208. for _, v := range existDataList {
  209. if v.DataTime == firstFromDataTimeStr {
  210. if tmpLastValue, ok := fromDataMap[firstFromDataTimeStr]; ok { //来源指标当天的数据
  211. lastValue = tmpLastValue
  212. lastValueStr = decimal.NewFromFloat(lastValue).String()
  213. }
  214. break
  215. }
  216. removeDateList = append(removeDateList, v.DataTime)
  217. }
  218. } else {
  219. for _, v := range dateArr { //如果计算指标第一条数据的开始时间 晚于 来源指标的第一条开始时间,那么需要对两个时间之间的计算指标数据做 新增处理
  220. vDataTime, _ := time.ParseInLocation(utils.FormatDate, v, time.Local) //当前日期(time类型)
  221. if firstExistDataTime.Equal(vDataTime) || firstExistDataTime.Before(vDataTime) {
  222. if tmpLastValue, ok := fromDataMap[v]; ok { //来源指标当天的数据
  223. lastValue = tmpLastValue
  224. lastValueStr = decimal.NewFromFloat(lastValue).String()
  225. }
  226. break
  227. }
  228. currentDate, _ := time.ParseInLocation(utils.FormatDate, v, time.Local)
  229. timestamp := currentDate.UnixNano() / 1e6
  230. timestampStr := fmt.Sprintf("%d", timestamp)
  231. addSql += GetAddSql(edbInfoIdStr, edbCode, v, timestampStr, lastValueStr)
  232. // 实际数据的值
  233. if fromEdbInfo.LatestDate == v {
  234. latestValue = lastValue
  235. }
  236. isAdd = true
  237. }
  238. }
  239. }
  240. //第二步 剩余数据每天修改
  241. day := int(nowDate.Sub(firstExistDataTime).Hours() / float64(24))
  242. //第三步: 已经入库的数据处理
  243. for _, v := range existDataList {
  244. existDataMap[v.DataTime] = v
  245. }
  246. for k := day; k >= 0; k-- {
  247. needDay := nowDate.AddDate(0, 0, -k)
  248. needDayStr := needDay.Format(utils.FormatDate)
  249. tmpExistData, ok := existDataMap[needDayStr]
  250. if ok {
  251. if tmpLastValue, ok := fromDataMap[tmpExistData.DataTime]; ok { //来源指标当天的数据
  252. lastValue = tmpLastValue
  253. //lastValueStr = decimal.NewFromFloat(lastValue).String()
  254. lastValueStr = fmt.Sprintf("%.4f", lastValue)
  255. }
  256. if fromEdbInfo.LatestDate == tmpExistData.DataTime {
  257. latestValue = lastValue
  258. }
  259. //如果对应的值不匹配
  260. if tmpExistData.Value != lastValueStr {
  261. err = ModifyEdbDataById(source, tmpExistData.EdbDataId, lastValueStr)
  262. if err != nil {
  263. return
  264. }
  265. }
  266. } else {
  267. timestamp := needDay.UnixNano() / 1e6
  268. timestampStr := fmt.Sprintf("%d", timestamp)
  269. addSql += GetAddSql(edbInfoIdStr, edbCode, needDayStr, timestampStr, lastValueStr)
  270. if fromEdbInfo.LatestDate == needDayStr {
  271. latestValue = lastValue
  272. }
  273. isAdd = true
  274. }
  275. }
  276. } else {
  277. //如果没有来源指标数据,那么已经入库的计算指标数据需要全部删除
  278. tableName := GetEdbDataTableName(source)
  279. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ?`, tableName)
  280. _, err = to.Raw(sql, edbInfoId).Exec()
  281. if err != nil {
  282. err = fmt.Errorf("删除所有的变频指标数据失败,Err:" + err.Error())
  283. return
  284. }
  285. //for _, v := range existDataList {
  286. // removeDateList = append(removeDateList, v.DataTime)
  287. //}
  288. }
  289. } else {
  290. existMap := make(map[string]string)
  291. dataLen := len(dataList)
  292. for i := 0; i < dataLen; i++ {
  293. //当期
  294. currentItem := dataList[i]
  295. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  296. var day int
  297. var preItem *EdbInfoSearchData
  298. var preDate time.Time
  299. if i == 0 {
  300. day = int(time.Now().Sub(currentDate).Hours() / float64(24))
  301. preDate = time.Now()
  302. } else {
  303. j := i - 1
  304. if j < dataLen {
  305. preItem = dataList[j]
  306. preDate, _ = time.ParseInLocation(utils.FormatDate, preItem.DataTime, time.Local)
  307. day = int(preDate.Sub(currentDate).Hours() / float64(24))
  308. utils.FileLog.Info("preItem.DataTime:" + preItem.DataTime + ";currentItem.DataTime" + currentItem.DataTime)
  309. }
  310. }
  311. for k := 0; k <= day; k++ {
  312. needDay := preDate.AddDate(0, 0, -k)
  313. needDayStr := needDay.Format(utils.FormatDate)
  314. existKey := edbCode + needDayStr
  315. if _, ok := existMap[existKey]; !ok {
  316. timestamp := needDay.UnixNano() / 1e6
  317. timestampStr := fmt.Sprintf("%d", timestamp)
  318. valStr := decimal.NewFromFloat(currentItem.Value).String()
  319. addSql += GetAddSql(edbInfoIdStr, edbCode, needDayStr, timestampStr, valStr)
  320. if fromEdbInfo.LatestDate == needDayStr {
  321. latestValue = currentItem.Value
  322. }
  323. isAdd = true
  324. }
  325. existMap[existKey] = needDayStr
  326. }
  327. existKey := edbCode + currentItem.DataTime
  328. if _, ok := existMap[existKey]; !ok {
  329. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  330. timestamp := currentDate.UnixNano() / 1e6
  331. timestampStr := fmt.Sprintf("%d", timestamp)
  332. valStr := decimal.NewFromFloat(currentItem.Value).String()
  333. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, valStr)
  334. if fromEdbInfo.LatestDate == currentItem.DataTime {
  335. latestValue = currentItem.Value
  336. }
  337. isAdd = true
  338. }
  339. existMap[existKey] = currentItem.DataTime
  340. }
  341. }
  342. // 删除不需要的指标数据
  343. if len(removeDateList) > 0 {
  344. removeDateStr := strings.Join(removeDateList, `","`)
  345. removeDateStr = `"` + removeDateStr + `"`
  346. //如果拼接指标变更了,那么需要删除所有的指标数据
  347. tableName := GetEdbDataTableName(source)
  348. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  349. _, err = to.Raw(sql, edbInfoId).Exec()
  350. if err != nil {
  351. err = fmt.Errorf("删除不存在的变频指标数据失败,Err:" + err.Error())
  352. return
  353. }
  354. }
  355. if isAdd {
  356. addSql = strings.TrimRight(addSql, ",")
  357. _, err = to.Raw(addSql).Exec()
  358. }
  359. return
  360. }