neck_ring_calculate.go 21 KB

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