predict_edb_data_calculate_ljzzy.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. //查找实际日期, 如果实际日期不是月末值,则把上个月末日期作为实际日期
  206. for yk, yv := range yearMap {
  207. for i := 1; i <= 12; i++ {
  208. if dataCurrentItem, ok := yv[i]; ok {
  209. if i == 1 {
  210. if latestDateStr < dataCurrentItem.DataTime { //假如最新的实际值不是1月末
  211. if lastYearDate, ok1 := yearMap[yk-1]; ok1 {
  212. if latestDateStr > lastYearDate[12].DataTime { //同时最新的实际值不是1月末,也不是上一年的12月末
  213. latestDateStr = lastYearDate[12].DataTime
  214. }
  215. }
  216. }
  217. }else if i == 2 {
  218. dataOne := strconv.Itoa(yk) + "-01-31"
  219. if latestDateStr > dataOne && latestDateStr < dataCurrentItem.DataTime {
  220. latestDateStr = dataOne
  221. }
  222. }else{
  223. if dataPreItem, ok2 := yv[i-1]; ok2 {
  224. if latestDateStr > dataPreItem.DataTime && latestDateStr < dataCurrentItem.DataTime {
  225. latestDateStr = dataPreItem.DataTime
  226. }
  227. }
  228. }
  229. }
  230. }
  231. }
  232. for yk, yv := range yearMap {
  233. _, oneMonthOk := yv[1]
  234. _, twoMonthOk := yv[2]
  235. if !oneMonthOk && !twoMonthOk {
  236. continue
  237. }
  238. for i := 1; i <= 12; i++ {
  239. fmt.Println(yk, i, yv[i])
  240. dataCurrentItem := yv[i]
  241. var date string
  242. var val float64
  243. if dataCurrentItem != nil {
  244. if i == 1 || i == 2 {
  245. if _, mok := yv[1]; mok { //1月有值
  246. if i == 1 {
  247. date = dataCurrentItem.DataTime
  248. val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
  249. }
  250. if i == 2 {
  251. dataOneItem := yv[1]
  252. date = dataCurrentItem.DataTime
  253. twoMonth := decimal.NewFromFloat(dataCurrentItem.Value)
  254. oneMonth := decimal.NewFromFloat(dataOneItem.Value)
  255. val, _ = twoMonth.Sub(oneMonth).Float64()
  256. }
  257. } else { //1月无值
  258. dataTwoItem := yv[2]
  259. if i == 1 {
  260. date = strconv.Itoa(yk) + "-01-31"
  261. a := decimal.NewFromFloat(dataTwoItem.Value)
  262. b := decimal.NewFromFloat(2.0)
  263. val, _ = a.Div(b).Float64()
  264. }
  265. if i == 2 {
  266. //1月无值:1月=2月/2
  267. {
  268. date = strconv.Itoa(yk) + "-01-31"
  269. a := decimal.NewFromFloat(dataTwoItem.Value)
  270. b := decimal.NewFromFloat(2.0)
  271. val, _ = a.Div(b).Float64()
  272. tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  273. if !isAdd {
  274. isAdd = newAdd
  275. }
  276. addSql = tmpSql
  277. if tmpErr != nil {
  278. err = tmpErr
  279. return
  280. }
  281. if latestDateStr == date {
  282. latestValue= val
  283. }
  284. }
  285. //end 1月无值
  286. date = dataCurrentItem.DataTime
  287. a := decimal.NewFromFloat(dataTwoItem.Value)
  288. b := decimal.NewFromFloat(2.0)
  289. val, _ = a.Div(b).Float64()
  290. }
  291. }
  292. } else {
  293. dataPreItem := yv[i-1]
  294. if dataPreItem != nil {
  295. date = dataCurrentItem.DataTime
  296. //val = dataCurrentItem.Value - dataPreItem.Value
  297. a := decimal.NewFromFloat(dataCurrentItem.Value)
  298. b := decimal.NewFromFloat(dataPreItem.Value)
  299. val, _ = a.Sub(b).Float64()
  300. }
  301. }
  302. }
  303. if date != "" {
  304. //saveValue := utils.SubFloatToString(val, 4)
  305. ////判断数据是否存在
  306. //if existVal, ok := dataMap[date]; !ok {
  307. // dataTime, _ := time.Parse(utils.FormatDate, date)
  308. // timestamp := dataTime.UnixNano() / 1e6
  309. // timeStr := fmt.Sprintf("%d", timestamp)
  310. // if _, existOk := existDataMap[date]; !existOk {
  311. // addSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, saveValue)
  312. // isAdd = true
  313. // }
  314. // existDataMap[date] = date
  315. //} else {
  316. // if existVal != saveValue {
  317. // sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  318. // sql = fmt.Sprintf(sql, dataTableName)
  319. // _, err = to.Raw(sql, saveValue, edbInfoId, date).Exec()
  320. // if err != nil {
  321. // return err
  322. // }
  323. // }
  324. //}
  325. tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  326. if !isAdd {
  327. isAdd = newAdd
  328. }
  329. addSql = tmpSql
  330. if tmpErr != nil {
  331. err = tmpErr
  332. return
  333. }
  334. if latestDateStr == date {
  335. latestValue= val
  336. }
  337. }
  338. }
  339. }
  340. if isAdd {
  341. addSql = strings.TrimRight(addSql, ",")
  342. _, err = to.Raw(addSql).Exec()
  343. if err != nil {
  344. fmt.Println("refreshAllPredictCalculateLjzzy add Err", err.Error())
  345. return
  346. }
  347. }
  348. return
  349. }