neck_ring_calculate.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. package crontab
  2. import (
  3. "fmt"
  4. "kpt-pasture/model"
  5. "kpt-pasture/util"
  6. "math"
  7. "strconv"
  8. "time"
  9. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  10. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  11. "gitee.com/xuyiping_admin/pkg/xerr"
  12. "go.uber.org/zap"
  13. )
  14. func (e *Entry) NeckRingCalculate() error {
  15. pastureList := e.FindPastureList()
  16. if pastureList == nil || len(pastureList) == 0 {
  17. return nil
  18. }
  19. for _, pasture := range pastureList {
  20. if err := e.EntryUpdateActiveHabit(pasture.Id); err != nil {
  21. zaplog.Error("NeckRingCalculate", zap.Any("err", err), zap.Any("pasture", pasture))
  22. }
  23. zaplog.Info(fmt.Sprintf("NeckRingCalculate Success %d", pasture.Id))
  24. }
  25. return nil
  26. }
  27. func (e *Entry) EntryUpdateActiveHabit(pastureId int64) (err error) {
  28. // 获取这段执行数据内最大日期和最小日期
  29. xToday, err := e.XToday(pastureId)
  30. if err != nil {
  31. return xerr.WithStack(err)
  32. }
  33. // 未配置的滤波数据不参与计算
  34. if xToday == nil {
  35. return nil
  36. }
  37. var processIds []int64
  38. // 更新活动滤波
  39. processIds, err = e.FirstFilterUpdate(pastureId, xToday)
  40. if err != nil {
  41. zaplog.Error("NeckRingCalculate", zap.Any("pastureId", pastureId), zap.Any("FirstFilterUpdate", err), zap.Any("xToday", xToday))
  42. }
  43. zaplog.Info("NeckRingCalculate", zap.Any("pastureId", pastureId), zap.Any("xToday", xToday), zap.Any("processIds", processIds))
  44. if len(processIds) <= 0 {
  45. return nil
  46. }
  47. e.WeeklyUpdateActiveHabit(pastureId, processIds, xToday)
  48. // 二次更新滤波
  49. e.SecondUpdateChangeFilter(pastureId, processIds, xToday)
  50. // 活动量校正系数和健康评分
  51. e.FilterCorrectAndScoreUpdate(pastureId, processIds, xToday)
  52. // 更新 ChangeFilter
  53. e.UpdateChangeFilter(pastureId, processIds)
  54. // 更新 FilterCorrect
  55. e.UpdateFilterCorrect(pastureId, processIds)
  56. // 插入群体校正表
  57. e.UpdateChangeAdJust(pastureId, xToday)
  58. // 更新 Cft
  59. e.UpdateCft(pastureId, processIds)
  60. // 更新所有的显示状态为否的记录为是
  61. e.UpdateIsShow(pastureId, processIds)
  62. // 健康预警
  63. e.HealthWarning(pastureId, processIds)
  64. return nil
  65. }
  66. // FirstFilterUpdate 首次更新活动滤波
  67. func (e *Entry) FirstFilterUpdate(pastureId int64, xToDay *XToday) (processIds []int64, err error) {
  68. limit := e.Cfg.NeckRingLimit
  69. if limit <= 0 {
  70. limit = defaultLimit
  71. }
  72. firstHeatDate := time.Now().Local().AddDate(0, 0, -30).Format(model.LayoutDate2)
  73. querySql := `SELECT * FROM neck_active_habit WHERE pasture_id = ? AND is_show = ? AND heat_date >= ? AND high >= ?
  74. UNION
  75. SELECT * FROM neck_active_habit WHERE pasture_id = ? AND is_show = ? AND heat_date >= ? AND rumina >= ?
  76. ORDER BY active_time,neck_ring_number,frameid LIMIT ?`
  77. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  78. if err = e.DB.Raw(
  79. querySql,
  80. pastureId, pasturePb.IsShow_No, firstHeatDate, xToDay.High,
  81. pastureId, pasturePb.IsShow_No, firstHeatDate, xToDay.Rumina,
  82. limit,
  83. ).Find(&newNeckActiveHabitList).Error; err != nil {
  84. return nil, xerr.WithStack(err)
  85. }
  86. // 活动量滤波
  87. for _, v := range newNeckActiveHabitList {
  88. // 4小时数据不全的不参与滤波
  89. activeTime, _ := util.TimeParseLocal(model.LayoutTime, v.ActiveTime)
  90. if v.RecordCount != model.DefaultRecordCount && time.Now().Local().Sub(activeTime).Hours() <= 4 {
  91. continue
  92. }
  93. // 过滤牛只未绑定的脖环的数据
  94. cowInfo := e.GetCowInfoByNeckRingNumber(v.PastureId, v.NeckRingNumber)
  95. if cowInfo == nil || cowInfo.Id <= 0 {
  96. v.UpdateIsShowOk()
  97. if err = e.DB.Model(new(model.NeckActiveHabit)).
  98. Select("is_show").
  99. Where("id = ?", v.Id).
  100. Updates(v).Error; err != nil {
  101. zaplog.Error("EntryUpdateActiveHabit", zap.Any("error", err))
  102. }
  103. continue
  104. }
  105. frameId := v.Frameid
  106. heatDate := v.HeatDate
  107. if v.Frameid == 0 {
  108. frameId = 11
  109. heatDateParse, _ := util.TimeParseLocal(model.LayoutDate2, heatDate)
  110. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  111. } else {
  112. frameId -= 1
  113. }
  114. firstFilterData := e.FindFilterData(pastureId, v.NeckRingNumber, heatDate, frameId)
  115. if v.FilterHigh > 0 {
  116. firstFilterData.FilterHigh = v.FilterHigh
  117. } else {
  118. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  119. firstFilterData.FilterHigh = int32(computeIfPositiveElse(float64(v.High), float64(firstFilterData.FilterHigh), 0.23, 0.77))
  120. } else {
  121. firstFilterData.FilterHigh = v.High
  122. }
  123. }
  124. if v.FilterRumina > 0 {
  125. firstFilterData.FilterRumina = v.FilterRumina
  126. } else {
  127. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  128. firstFilterData.FilterRumina = int32(computeIfPositiveElse(float64(v.Rumina), float64(firstFilterData.FilterRumina), 0.33, 0.67))
  129. } else {
  130. firstFilterData.FilterRumina = v.Rumina
  131. }
  132. }
  133. if v.FilterChew > 0 {
  134. firstFilterData.FilterChew = v.FilterChew
  135. } else {
  136. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  137. firstFilterData.FilterChew = int32(computeIfPositiveElse(float64(v.Rumina+v.Intake), float64(firstFilterData.FilterChew), 0.33, 0.67))
  138. } else {
  139. firstFilterData.FilterChew = v.Rumina + v.Intake
  140. }
  141. }
  142. cowWeeklyActive := cowInfo.WeeklyActive
  143. if cowWeeklyActive <= 0 {
  144. cowWeeklyActive = v.WeekHigh
  145. }
  146. processIds = append(processIds, v.Id)
  147. // 更新过滤值
  148. if err = e.DB.Model(new(model.NeckActiveHabit)).
  149. Select("filter_high", "filter_rumina", "filter_chew", "cow_id", "lact", "calving_age", "ear_number", "week_high").
  150. Where("id = ?", v.Id).
  151. Updates(map[string]interface{}{
  152. "filter_high": firstFilterData.FilterHigh,
  153. "filter_rumina": firstFilterData.FilterRumina,
  154. "filter_chew": firstFilterData.FilterChew,
  155. "cow_id": cowInfo.Id,
  156. "lact": cowInfo.Lact,
  157. "calving_age": cowInfo.CalvingAge,
  158. "ear_number": cowInfo.EarNumber,
  159. "week_high": cowWeeklyActive,
  160. }).Error; err != nil {
  161. zaplog.Error("FirstFilterUpdate",
  162. zap.Any("error", err),
  163. zap.Any("firstFilterData", firstFilterData),
  164. zap.Any("NeckActiveHabit", v),
  165. zap.Any("cowInfo", cowInfo),
  166. zap.Any("xToday", xToDay),
  167. )
  168. }
  169. }
  170. return processIds, nil
  171. }
  172. // SecondUpdateChangeFilter 第二次更新变化趋势滤波
  173. func (e *Entry) SecondUpdateChangeFilter(pastureId int64, processIds []int64, xToday *XToday) {
  174. newChangeFilterList := make([]*ChangeFilterData, 0)
  175. if err := e.DB.Model(new(model.NeckActiveHabit)).
  176. Select("id", "neck_ring_number", "change_high", "change_filter", "rumina_filter", "change_rumina",
  177. "chew_filter", "change_chew", "heat_date", "frameid", "IF(lact = 0, 0.8, 1) as xlc_dis_count").
  178. Where("pasture_id = ?", pastureId).
  179. Where("id IN (?)", processIds).
  180. Where("change_filter = ?", model.InitChangeFilter).
  181. Where("change_high > ?", MinChangeHigh).
  182. Order("neck_ring_number,heat_date,frameid").
  183. Find(&newChangeFilterList).Error; err != nil {
  184. zaplog.Error("SecondUpdateChangeFilter", zap.Any("error", err))
  185. return
  186. }
  187. for _, v := range newChangeFilterList {
  188. frameId := v.Frameid
  189. heatDate := v.HeatDate
  190. if v.Frameid == 0 {
  191. frameId = 11
  192. heatDateParse, _ := util.TimeParseLocal(model.LayoutDate2, heatDate)
  193. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  194. } else {
  195. frameId -= 1
  196. }
  197. xChangeDiscount := float64(xToday.XChangeDiscount) / 10
  198. xRuminaDisc := float64(xToday.XRuminaDisc) / 10
  199. secondFilterData := e.FindFilterData(pastureId, v.NeckRingNumber, heatDate, frameId)
  200. if secondFilterData.ChangeFilter <= MinChangeFilter {
  201. secondFilterData.ChangeFilter = 0
  202. }
  203. if secondFilterData.RuminaFilter <= MinRuminaFilter {
  204. secondFilterData.RuminaFilter = 0
  205. }
  206. if secondFilterData.ChewFilter <= MinChewFilter {
  207. secondFilterData.ChewFilter = 0
  208. }
  209. changeFilter := float64(v.ChangeFilter)
  210. if v.ChangeFilter <= MinChangeFilter {
  211. changeFilter = float64(secondFilterData.ChangeFilter)*(1-xChangeDiscount*v.XlcDisCount) +
  212. math.Min(float64(v.ChangeHigh), float64(secondFilterData.ChangeFilter)+135)*xChangeDiscount*v.XlcDisCount
  213. }
  214. ruminaFilter := float64(v.RuminaFilter)
  215. discount := xRuminaDisc * v.XlcDisCount
  216. if math.Abs(float64(v.ChangeRumina)) > 60 {
  217. discount *= 0.5
  218. }
  219. ruminaFilter = float64(secondFilterData.RuminaFilter)*(1-discount) + float64(v.ChangeRumina)*discount
  220. if ruminaFilter > 50 {
  221. ruminaFilter = 50
  222. }
  223. chewFilter := float64(v.ChewFilter)
  224. chewFilterDiscount := float64(1)
  225. if math.Abs(float64(v.ChangeChew)) > 60 {
  226. chewFilterDiscount = 0.5
  227. }
  228. chewFilter = float64(secondFilterData.ChewFilter)*(1-xRuminaDisc*chewFilterDiscount) +
  229. float64(v.ChangeChew)*xRuminaDisc*chewFilterDiscount
  230. if chewFilter > 50 {
  231. chewFilter = 50
  232. }
  233. zaplog.Info("SecondUpdateChangeFilter",
  234. zap.Any("NeckActiveHabit", v),
  235. zap.Any("discount", discount),
  236. zap.Any("xChangeDiscount", xChangeDiscount),
  237. zap.Any("xRuminaDisc", xRuminaDisc),
  238. zap.Any("chewFilterDiscount", chewFilterDiscount),
  239. zap.Any("secondFilterData", secondFilterData),
  240. zap.Any("changeFilter", changeFilter),
  241. zap.Any("ruminaFilter", ruminaFilter),
  242. zap.Any("chewFilter", chewFilter),
  243. )
  244. if err := e.DB.Model(new(model.NeckActiveHabit)).
  245. Select("change_filter", "rumina_filter", "chew_filter").
  246. Where("id = ?", v.Id).
  247. Updates(map[string]interface{}{
  248. "change_filter": int32(changeFilter),
  249. "rumina_filter": int32(ruminaFilter),
  250. "chew_filter": int32(chewFilter),
  251. }).Error; err != nil {
  252. zaplog.Error("SecondUpdateChangeFilter", zap.Any("error", err), zap.Any("secondFilterData", secondFilterData))
  253. }
  254. }
  255. }
  256. // FilterCorrectAndScoreUpdate 计算活动量变化趋势校正值(活跃度校正)和健康评分
  257. func (e *Entry) FilterCorrectAndScoreUpdate(pastureId int64, processIds []int64, xToday *XToday) {
  258. beginDayDate := time.Now().Local()
  259. before7DayDate := beginDayDate.AddDate(0, 0, -7).Format(model.LayoutDate2)
  260. before1DayDate := beginDayDate.AddDate(0, 0, -1).Format(model.LayoutDate2)
  261. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  262. if err := e.DB.Model(new(model.NeckActiveHabit)).
  263. Where("id IN (?)", processIds).
  264. Where("pasture_id = ?", pastureId).
  265. Find(&neckActiveHabitList).Error; err != nil {
  266. zaplog.Error("ActivityVolumeChanges-1", zap.Any("error", err), zap.Any("xToday", xToday))
  267. return
  268. }
  269. for _, v := range neckActiveHabitList {
  270. activityVolume := &ActivityVolume{}
  271. if err := e.DB.Model(new(model.NeckActiveHabit)).
  272. Select("neck_ring_number", "AVG(IF(change_filter>=60, 60, change_filter)) as avg_filter",
  273. "ROUND(STD(IF(change_filter>=60, 60, change_filter))) as std_filter", "COUNT(1) as nb").
  274. Where("heat_date BETWEEN ? AND ?", before7DayDate, before1DayDate).
  275. Where("pasture_id = ?", pastureId).
  276. Where(e.DB.Where("high > ?", 12).Or("rumina >= ?", xToday.Rumina)).
  277. Where("active_time <= ?", beginDayDate.Add(-12*time.Hour).Format(model.LayoutTime)).
  278. Where("change_filter > ?", MinChangeFilter).
  279. Where("neck_ring_number = ?", v.NeckRingNumber).
  280. Having("nb >= ?", DefaultNb).
  281. First(&activityVolume).Error; err != nil {
  282. zaplog.Error("ActivityVolumeChanges-0", zap.Any("error", err), zap.Any("xToday", xToday))
  283. continue
  284. }
  285. if activityVolume != nil && activityVolume.NeckRingNumber != "" {
  286. //filterCorrect := model.DefaultFilterCorrect - int(math.Floor(activityVolume.AvgFilter/3+float64(activityVolume.StdFilter)/2))
  287. filterCorrect := model.DefaultFilterCorrect - int(math.Round(activityVolume.AvgFilter/3+float64(int(math.Round(activityVolume.StdFilter))/2)))
  288. // 活动量校正系数
  289. if err := e.DB.Model(new(model.NeckActiveHabit)).
  290. Where("id = ?", v.Id).
  291. Where("neck_ring_number = ?", v.NeckRingNumber).
  292. Update("filter_correct", filterCorrect).Error; err != nil {
  293. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  294. continue
  295. }
  296. }
  297. cowScore := calculateScore(v)
  298. if err := e.DB.Model(new(model.NeckActiveHabit)).
  299. Where("id = ?", v.Id).
  300. Update("score", cowScore).Error; err != nil {
  301. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  302. continue
  303. }
  304. }
  305. }
  306. func (e *Entry) UpdateChangeFilter(pastureId int64, processIds []int64) {
  307. if err := e.DB.Model(new(model.NeckActiveHabit)).
  308. Where("id IN (?)", processIds).
  309. Where("pasture_id = ?", pastureId).
  310. Where("is_show = ?", pasturePb.IsShow_No).
  311. Where("change_filter = ?", model.InitChangeFilter).
  312. Updates(map[string]interface{}{
  313. "change_filter": model.DefaultChangeFilter,
  314. "rumina_filter": model.DefaultRuminaFilter,
  315. "chew_filter": model.DefaultChewFilter,
  316. }).Error; err != nil {
  317. zaplog.Error("UpdateChangeFilter", zap.Any("change_filter", err))
  318. }
  319. }
  320. func (e *Entry) UpdateFilterCorrect(pastureId int64, processIds []int64) {
  321. if err := e.DB.Model(new(model.NeckActiveHabit)).
  322. Where("id IN (?)", processIds).
  323. Where("pasture_id = ?", pastureId).
  324. Where("change_filter < ?", 0).
  325. Where("filter_correct < ?", model.DefaultFilterCorrect).
  326. Updates(map[string]interface{}{
  327. "filter_correct": model.DefaultFilterCorrect,
  328. }).Error; err != nil {
  329. zaplog.Error("UpdateFilterCorrect", zap.Any("filter_correct", err))
  330. }
  331. }
  332. // UpdateChangeAdJust 更新群体校正数据
  333. func (e *Entry) UpdateChangeAdJust(pastureId int64, xToday *XToday) {
  334. res := make([]*model.NeckRingBarChange, 0)
  335. oneDayAgo := time.Now().Local().AddDate(0, 0, -1).Format(model.LayoutDate2)
  336. if err := e.DB.Table(fmt.Sprintf("%s as h", new(model.NeckActiveHabit).TableName())).
  337. Select(`h.neck_ring_number,h.heat_date, h.frameid, c.pen_id, c.pen_name, COUNT(*) as nb,
  338. ROUND(AVG(h.change_high)) as change_high, ROUND(AVG(h.change_filter)) as change_filter`).
  339. Joins("JOIN cow as c ON h.cow_id = c.id").
  340. Where("h.pasture_id = ?", pastureId).
  341. Where("h.heat_date >= ?", oneDayAgo).
  342. Where("h.cow_id > ?", 0).
  343. Where("c.pen_id > ?", 0).
  344. Group("h.heat_date, h.frameid, c.pen_id").
  345. Order("h.heat_date, h.frameid, c.pen_id").
  346. Find(&res).Error; err != nil {
  347. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("xToday", xToday))
  348. }
  349. for _, v := range res {
  350. if math.Abs(float64(v.ChangeFilter)) < 10 {
  351. continue
  352. }
  353. if err := e.DB.Model(new(model.NeckActiveHabit)).
  354. Where("pasture_id = ?", pastureId).
  355. Where("neck_ring_number = ?", v.NeckRingNumber).
  356. Where("heat_date = ?", v.HeatDate).
  357. //Where("pen_id = ?", v.PenId).
  358. Where("frameid = ?", v.FrameId).
  359. Update("change_adjust", v.ChangeFilter).Error; err != nil {
  360. zaplog.Error("UpdateChangeAdJust-1", zap.Any("error", err), zap.Any("xToday", xToday))
  361. }
  362. }
  363. }
  364. func (e *Entry) UpdateCft(pastureId int64, processIds []int64) {
  365. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  366. if err := e.DB.Model(new(model.NeckActiveHabit)).
  367. Where("id IN (?)", processIds).
  368. Where("pasture_id = ?", pastureId).
  369. Where("is_show = ?", pasturePb.IsShow_No).
  370. Find(&neckActiveHabitList).Error; err != nil {
  371. zaplog.Error("UpdateCft-1", zap.Any("error", err))
  372. }
  373. for _, v := range neckActiveHabitList {
  374. cft := CalculateCFT(v)
  375. if err := e.DB.Model(new(model.NeckActiveHabit)).
  376. Where("id = ?", v.Id).
  377. Where("neck_ring_number = ?", v.NeckRingNumber).
  378. Update("cft", strconv.FormatFloat(float64(cft), 'f', 2, 64)).Error; err != nil {
  379. zaplog.Error("UpdateCft-2", zap.Any("error", err))
  380. }
  381. }
  382. }
  383. func (e *Entry) UpdateIsShow(pastureId int64, processIds []int64) {
  384. if err := e.DB.Model(new(model.NeckActiveHabit)).
  385. Where("id IN (?)", processIds).
  386. Where("pasture_id = ?", pastureId).
  387. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  388. zaplog.Error("UpdateChangeAdJust-2", zap.Any("error", err))
  389. }
  390. }
  391. func (e *Entry) XToday(pastureId int64) (*XToday, error) {
  392. xToday := &XToday{}
  393. systemConfigureList, err := e.FindSystemNeckRingConfigure(pastureId)
  394. if err != nil {
  395. return nil, xerr.WithStack(err)
  396. }
  397. if len(systemConfigureList) <= 0 {
  398. return nil, nil
  399. }
  400. for _, v := range systemConfigureList {
  401. switch v.Name {
  402. case model.MaxHabit:
  403. xToday.LastMaxHabitId = v.Value
  404. case model.High:
  405. xToday.High = int32(v.Value)
  406. case model.Rumina:
  407. xToday.Rumina = int32(v.Value)
  408. case model.XRuminaDisc:
  409. xToday.XRuminaDisc = int32(v.Value)
  410. case model.XChangeDiscount:
  411. xToday.XChangeDiscount = int32(v.Value)
  412. case model.WeeklyActive:
  413. xToday.WeeklyActive = int32(v.Value)
  414. }
  415. }
  416. return xToday, nil
  417. }
  418. // WeeklyUpdateActiveHabit 时间点周平均值计算
  419. func (e *Entry) WeeklyUpdateActiveHabit(pastureId int64, processIds []int64, xToDay *XToday) {
  420. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  421. if err := e.DB.Model(new(model.NeckActiveHabit)).
  422. Where("id IN (?)", processIds).
  423. Order("heat_date,neck_ring_number,frameid").
  424. Find(&newNeckActiveHabitList).Error; err != nil {
  425. zaplog.Error("WeeklyUpdateActiveHabit", zap.Any("error", err), zap.Any("processIds", processIds))
  426. }
  427. if len(newNeckActiveHabitList) <= 0 {
  428. return
  429. }
  430. e.HabitUpdateActiveHabit(pastureId, newNeckActiveHabitList, xToDay)
  431. e.SumUpdateActiveHabit(pastureId, newNeckActiveHabitList, xToDay)
  432. e.ActiveChange(pastureId, processIds, xToDay)
  433. e.Before3DaysNeckActiveHabit(pastureId, processIds)
  434. }
  435. func (e *Entry) HabitUpdateActiveHabit(pastureId int64, newNeckActiveHabitList []*model.NeckActiveHabit, xToDay *XToday) {
  436. for _, v := range newNeckActiveHabitList {
  437. // 前七天的
  438. weekHabitData := e.FindWeekHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  439. // 更新过滤值
  440. if err := e.DB.Model(new(model.NeckActiveHabit)).
  441. Select("high_habit", "rumina_habit", "chew_habit", "intake_habit", "inactive_habit").
  442. Where("id = ?", v.Id).
  443. Updates(map[string]interface{}{
  444. "high_habit": weekHabitData.HighHabit,
  445. "rumina_habit": weekHabitData.RuminaHabit,
  446. "chew_habit": weekHabitData.ChewHabit,
  447. "intake_habit": weekHabitData.IntakeHabit,
  448. "inactive_habit": weekHabitData.InactiveHabit,
  449. }).Error; err != nil {
  450. zaplog.Error("WeeklyUpdateActiveHabit",
  451. zap.Error(err),
  452. zap.Any("NeckActiveHabit", v),
  453. zap.Any("pastureId", pastureId),
  454. )
  455. }
  456. }
  457. }
  458. // SumUpdateActiveHabit -- 累计24小时数值
  459. func (e *Entry) SumUpdateActiveHabit(pastureId int64, newNeckActiveHabitList []*model.NeckActiveHabit, xToDay *XToday) {
  460. for _, v := range newNeckActiveHabitList {
  461. sumHabitData := e.FindSumHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  462. // 更新过滤值
  463. if err := e.DB.Model(new(model.NeckActiveHabit)).
  464. Select("sum_rumina", "sum_intake", "sum_inactive", "sum_active", "sum_max_high", "sum_min_high", "sum_min_chew").
  465. Where("id = ?", v.Id).
  466. Updates(map[string]interface{}{
  467. "sum_rumina": sumHabitData.SumRumina,
  468. "sum_intake": sumHabitData.SumIntake,
  469. "sum_inactive": sumHabitData.SumInactive,
  470. "sum_active": sumHabitData.SumActive,
  471. "sum_max_high": sumHabitData.SumMaxHigh,
  472. "sum_min_high": sumHabitData.SumMinHigh,
  473. "sum_min_chew": sumHabitData.SumMinChew,
  474. }).Error; err != nil {
  475. zaplog.Error("WeeklyUpdateActiveHabit",
  476. zap.Any("err", err),
  477. zap.Any("NeckActiveHabit", v),
  478. zap.Any("pastureId", pastureId),
  479. )
  480. }
  481. }
  482. }
  483. // ActiveChange -- 变化百分比
  484. func (e *Entry) ActiveChange(pastureId int64, processIds []int64, xToDay *XToday) {
  485. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  486. if err := e.DB.Model(new(model.NeckActiveHabit)).
  487. Where("pasture_id = ?", pastureId).
  488. Where("id IN (?)", processIds).
  489. Where("high_habit > ?", 0).
  490. Where(e.DB.Where("high >= ?", xToDay.High).Or("rumina >= ?", xToDay.Rumina)).
  491. Find(&newNeckActiveHabitList).Error; err != nil {
  492. zaplog.Error("ActiveChange", zap.Any("error", err), zap.Any("processIds", processIds))
  493. }
  494. for _, v := range newNeckActiveHabitList {
  495. changeHigh := calculateChangeHigh(v, xToDay.WeeklyActive)
  496. changeRumina := int32(0)
  497. changeChew := int32(0)
  498. if v.RuminaHabit != 0 {
  499. changeRumina = int32(math.Round(float64(v.FilterRumina-v.RuminaHabit) / float64(v.RuminaHabit) * 100))
  500. }
  501. if v.ChewHabit != 0 {
  502. changeChew = int32(math.Round(float64(v.FilterChew-v.ChewHabit) / float64(v.ChewHabit) * 100))
  503. }
  504. // 更新过滤值
  505. if err := e.DB.Model(new(model.NeckActiveHabit)).
  506. Select("change_high", "change_rumina", "change_chew").
  507. Where("id = ?", v.Id).
  508. Updates(map[string]interface{}{
  509. "change_high": changeHigh,
  510. "change_rumina": changeRumina,
  511. "change_chew": changeChew,
  512. }).Error; err != nil {
  513. zaplog.Error("ActiveChange",
  514. zap.Any("err", err),
  515. zap.Any("NeckActiveHabit", v),
  516. )
  517. }
  518. }
  519. }
  520. func (e *Entry) Before3DaysNeckActiveHabit(pastureId int64, processIds []int64) {
  521. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  522. if err := e.DB.Model(new(model.NeckActiveHabit)).
  523. Where("id IN (?)", processIds).
  524. Order("heat_date,neck_ring_number,frameid").
  525. Find(&newNeckActiveHabitList).Error; err != nil {
  526. zaplog.Error("Before3DaysNeckActiveHabit", zap.Any("error", err), zap.Any("processIds", processIds))
  527. }
  528. for _, v := range newNeckActiveHabitList {
  529. before3DaysNeckActiveHabit := e.FindBefore3DaysNeckActiveHabit(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid)
  530. if before3DaysNeckActiveHabit.SumRumina == 0 && before3DaysNeckActiveHabit.SumIntake == 0 {
  531. continue
  532. }
  533. // 更新过滤值
  534. if err := e.DB.Model(new(model.NeckActiveHabit)).
  535. Select("before_three_sum_rumina", "before_three_sum_intake").
  536. Where("id = ?", v.Id).
  537. Updates(map[string]interface{}{
  538. "before_three_sum_rumina": before3DaysNeckActiveHabit.SumRumina,
  539. "before_three_sum_intake": before3DaysNeckActiveHabit.SumIntake,
  540. }).Error; err != nil {
  541. zaplog.Error("Before3DaysNeckActiveHabit",
  542. zap.Error(err),
  543. zap.Any("NeckActiveHabit", v),
  544. zap.Any("pastureId", pastureId),
  545. )
  546. }
  547. }
  548. }
  549. // calculateChangeHigh 计算活动量变化
  550. func calculateChangeHigh(data *model.NeckActiveHabit, weeklyActive int32) int32 {
  551. highDiff := data.FilterHigh - data.HighHabit
  552. changeHigh := int32(0)
  553. if highDiff > 0 {
  554. denominator := float64(data.WeekHigh)*0.6 + float64(data.HighHabit)*0.2 + float64(weeklyActive)*0.2
  555. changeHigh = int32(math.Round((float64(highDiff) / denominator) * 100))
  556. } else {
  557. changeHigh = int32(math.Round(float64(highDiff) / float64(data.HighHabit) * 100))
  558. }
  559. return changeHigh
  560. }