predict_edb_data_calculate_ljzzy.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. // SavePredictCalculateLjzzy 累计值转月
  13. func SavePredictCalculateLjzzy(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("SavePredictCalculateLjzzy,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_LJZZY
  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. //修改指标信息
  78. edbInfo.EdbName = req.EdbName
  79. edbInfo.EdbNameSource = req.EdbName
  80. edbInfo.Frequency = req.Frequency
  81. edbInfo.Unit = req.Unit
  82. edbInfo.ClassifyId = req.ClassifyId
  83. edbInfo.ModifyTime = time.Now()
  84. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
  85. if err != nil {
  86. return
  87. }
  88. var existCondition string
  89. var existPars []interface{}
  90. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  91. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  92. var count int
  93. //判断计算指标是否被更换
  94. count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  95. if err != nil {
  96. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  97. return
  98. }
  99. if count > 0 { // 指标未被替换,无需重新计算
  100. return
  101. }
  102. //删除,计算指标关联的,基础指标的关联关系
  103. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  104. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  105. if err != nil {
  106. return
  107. }
  108. //清空原有数据
  109. sql = ` DELETE FROM edb_data_predict_calculate_ljzzy WHERE edb_info_id = ? `
  110. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  111. if err != nil {
  112. return
  113. }
  114. //关联关系
  115. {
  116. calculateMappingItem := &EdbInfoCalculateMapping{
  117. EdbInfoCalculateMappingId: 0,
  118. EdbInfoId: edbInfo.EdbInfoId,
  119. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_LJZZY,
  120. SourceName: "预测累计值转月值",
  121. EdbCode: edbInfo.EdbCode,
  122. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  123. FromEdbCode: fromEdbInfo.EdbCode,
  124. FromEdbName: fromEdbInfo.EdbName,
  125. FromSource: fromEdbInfo.Source,
  126. FromSourceName: fromEdbInfo.SourceName,
  127. FromTag: "",
  128. Sort: 1,
  129. CreateTime: time.Now(),
  130. ModifyTime: time.Now(),
  131. }
  132. _, err = to.Insert(calculateMappingItem)
  133. if err != nil {
  134. return
  135. }
  136. }
  137. }
  138. //计算数据
  139. latestDateStr, latestValue, err = refreshAllPredictCalculateLjzzy(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
  140. return
  141. }
  142. // RefreshAllPredictCalculateLjzzy 刷新全部累计值转月数据
  143. func RefreshAllPredictCalculateLjzzy(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (latestDateStr string, latestValue float64, err error) {
  144. o := orm.NewOrm()
  145. to, err := o.Begin()
  146. if err != nil {
  147. return
  148. }
  149. defer func() {
  150. if err != nil {
  151. fmt.Println("refreshAllPredictCalculateLjzzy,Err:" + err.Error())
  152. _ = to.Rollback()
  153. } else {
  154. _ = to.Commit()
  155. }
  156. }()
  157. // 计算数据
  158. latestDateStr, latestValue, err = refreshAllPredictCalculateLjzzy(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate)
  159. return
  160. }
  161. func refreshAllPredictCalculateLjzzy(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (latestDateStr string, latestValue float64, err error) {
  162. edbInfoIdStr := strconv.Itoa(edbInfoId)
  163. dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 1, startDate)
  164. if err != nil {
  165. return
  166. }
  167. latestDateStr = fromEdbInfo.LatestDate
  168. yearMap := make(map[int]map[int]*EdbInfoSearchData)
  169. dataLen := len(dataList)
  170. for i := 0; i < dataLen; i++ {
  171. item := dataList[i]
  172. //日其中获取年
  173. var itemDate time.Time
  174. itemDate, err = time.Parse(utils.FormatDate, item.DataTime)
  175. if err != nil {
  176. return
  177. }
  178. year := itemDate.Year()
  179. month := int(itemDate.Month())
  180. if monthMap, yok := yearMap[year]; yok {
  181. monthMap[month] = item
  182. yearMap[year] = monthMap
  183. } else {
  184. monthMap = make(map[int]*EdbInfoSearchData)
  185. monthMap[month] = item
  186. yearMap[year] = monthMap
  187. }
  188. }
  189. addSql := ` INSERT INTO edb_data_predict_calculate_ljzzy(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  190. var isAdd bool
  191. //获取指标所有数据
  192. existDataList := make([]*EdbData, 0)
  193. dataTableName := GetEdbDataTableName(source)
  194. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  195. sql = fmt.Sprintf(sql, dataTableName)
  196. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  197. if err != nil {
  198. return
  199. }
  200. dataMap := make(map[string]string)
  201. for _, v := range existDataList {
  202. dataMap[v.DataTime] = v.Value
  203. }
  204. existDataMap := make(map[string]string)
  205. for yk, yv := range yearMap {
  206. _, oneMonthOk := yv[1]
  207. _, twoMonthOk := yv[2]
  208. if !oneMonthOk && !twoMonthOk {
  209. continue
  210. }
  211. for i := 1; i <= 12; i++ {
  212. fmt.Println(yk, i, yv[i])
  213. dataCurrentItem := yv[i]
  214. var date string
  215. var val float64
  216. if dataCurrentItem != nil {
  217. if i == 1 || i == 2 {
  218. if _, mok := yv[1]; mok { //1月有值
  219. if i == 1 {
  220. date = dataCurrentItem.DataTime
  221. val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
  222. }
  223. if i == 2 {
  224. dataOneItem := yv[1]
  225. date = dataCurrentItem.DataTime
  226. twoMonth := decimal.NewFromFloat(dataCurrentItem.Value)
  227. oneMonth := decimal.NewFromFloat(dataOneItem.Value)
  228. val, _ = twoMonth.Sub(oneMonth).Float64()
  229. }
  230. } else { //1月无值
  231. dataTwoItem := yv[2]
  232. if i == 1 {
  233. date = strconv.Itoa(yk) + "-01-31"
  234. a := decimal.NewFromFloat(dataTwoItem.Value)
  235. b := decimal.NewFromFloat(2.0)
  236. val, _ = a.Div(b).Float64()
  237. }
  238. if i == 2 {
  239. //1月无值:1月=2月/2
  240. {
  241. date = strconv.Itoa(yk) + "-01-31"
  242. a := decimal.NewFromFloat(dataTwoItem.Value)
  243. b := decimal.NewFromFloat(2.0)
  244. val, _ = a.Div(b).Float64()
  245. tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  246. if !isAdd {
  247. isAdd = newAdd
  248. }
  249. addSql = tmpSql
  250. if tmpErr != nil {
  251. err = tmpErr
  252. return
  253. }
  254. if fromEdbInfo.LatestDate == date {
  255. latestValue= val
  256. }
  257. }
  258. //end 1月无值
  259. date = dataCurrentItem.DataTime
  260. a := decimal.NewFromFloat(dataTwoItem.Value)
  261. b := decimal.NewFromFloat(2.0)
  262. val, _ = a.Div(b).Float64()
  263. }
  264. }
  265. } else {
  266. dataPreItem := yv[i-1]
  267. if dataPreItem != nil {
  268. date = dataCurrentItem.DataTime
  269. //val = dataCurrentItem.Value - dataPreItem.Value
  270. a := decimal.NewFromFloat(dataCurrentItem.Value)
  271. b := decimal.NewFromFloat(dataPreItem.Value)
  272. val, _ = a.Sub(b).Float64()
  273. }
  274. }
  275. }
  276. if date != "" {
  277. //saveValue := utils.SubFloatToString(val, 4)
  278. ////判断数据是否存在
  279. //if existVal, ok := dataMap[date]; !ok {
  280. // dataTime, _ := time.Parse(utils.FormatDate, date)
  281. // timestamp := dataTime.UnixNano() / 1e6
  282. // timeStr := fmt.Sprintf("%d", timestamp)
  283. // if _, existOk := existDataMap[date]; !existOk {
  284. // addSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, saveValue)
  285. // isAdd = true
  286. // }
  287. // existDataMap[date] = date
  288. //} else {
  289. // if existVal != saveValue {
  290. // sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  291. // sql = fmt.Sprintf(sql, dataTableName)
  292. // _, err = to.Raw(sql, saveValue, edbInfoId, date).Exec()
  293. // if err != nil {
  294. // return err
  295. // }
  296. // }
  297. //}
  298. tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  299. if !isAdd {
  300. isAdd = newAdd
  301. }
  302. addSql = tmpSql
  303. if tmpErr != nil {
  304. err = tmpErr
  305. return
  306. }
  307. if fromEdbInfo.LatestDate == date {
  308. latestValue= val
  309. }
  310. }
  311. }
  312. }
  313. if isAdd {
  314. addSql = strings.TrimRight(addSql, ",")
  315. _, err = to.Raw(addSql).Exec()
  316. if err != nil {
  317. fmt.Println("refreshAllPredictCalculateLjzzy add Err", err.Error())
  318. return
  319. }
  320. }
  321. return
  322. }