neck_ring_calculate.go 20 KB

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