neck_ring_calculate.go 20 KB

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