neck_ring_calculate.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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, int(xToDay.BeforeDayNeckRing)*-1).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. cowScore := calculateScore(v)
  271. if err := e.DB.Model(new(model.NeckActiveHabit)).
  272. Where("id = ?", v.Id).
  273. Update("score", cowScore).Error; err != nil {
  274. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  275. }
  276. activityVolume := &ActivityVolume{}
  277. if err := e.DB.Model(new(model.NeckActiveHabit)).
  278. Select("neck_ring_number", "AVG(IF(change_filter>=60, 60, change_filter)) as avg_filter",
  279. "ROUND(STD(IF(change_filter>=60, 60, change_filter))) as std_filter", "COUNT(1) as nb").
  280. Where("heat_date BETWEEN ? AND ?", before7DayDate, before1DayDate).
  281. Where("pasture_id = ?", pastureId).
  282. Where(e.DB.Where("high > ?", 12).Or("rumina >= ?", xToday.Rumina)).
  283. Where("active_time <= ?", beginDayDate.Add(-12*time.Hour).Format(model.LayoutTime)).
  284. Where("change_filter > ?", MinChangeFilter).
  285. Where("neck_ring_number = ?", v.NeckRingNumber).
  286. Having("nb >= ?", DefaultNb).
  287. First(&activityVolume).Error; err != nil {
  288. zaplog.Error("ActivityVolumeChanges-0", zap.Any("error", err), zap.Any("xToday", xToday), zap.Any("v", v))
  289. continue
  290. }
  291. if activityVolume != nil && activityVolume.NeckRingNumber != "" {
  292. //filterCorrect := model.DefaultFilterCorrect - int(math.Floor(activityVolume.AvgFilter/3+float64(activityVolume.StdFilter)/2))
  293. filterCorrect := model.DefaultFilterCorrect - int(math.Round(activityVolume.AvgFilter/3+float64(int(math.Round(activityVolume.StdFilter))/2)))
  294. // 活动量校正系数
  295. if err := e.DB.Model(new(model.NeckActiveHabit)).
  296. Where("id = ?", v.Id).
  297. //Where("neck_ring_number = ?", v.NeckRingNumber).
  298. Update("filter_correct", filterCorrect).Error; err != nil {
  299. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  300. continue
  301. }
  302. }
  303. }
  304. }
  305. func (e *Entry) UpdateChangeFilter(pastureId int64, processIds []int64) {
  306. if err := e.DB.Model(new(model.NeckActiveHabit)).
  307. Where("id IN (?)", processIds).
  308. Where("pasture_id = ?", pastureId).
  309. Where("is_show = ?", pasturePb.IsShow_No).
  310. Where("change_filter = ?", model.InitChangeFilter).
  311. Updates(map[string]interface{}{
  312. "change_filter": model.DefaultChangeFilter,
  313. "rumina_filter": model.DefaultRuminaFilter,
  314. "chew_filter": model.DefaultChewFilter,
  315. }).Error; err != nil {
  316. zaplog.Error("UpdateChangeFilter", zap.Any("change_filter", err))
  317. }
  318. }
  319. func (e *Entry) UpdateFilterCorrect(pastureId int64, processIds []int64) {
  320. if err := e.DB.Model(new(model.NeckActiveHabit)).
  321. Where("id IN (?)", processIds).
  322. Where("pasture_id = ?", pastureId).
  323. Where("change_filter < ?", 0).
  324. Where("filter_correct < ?", model.DefaultFilterCorrect).
  325. Updates(map[string]interface{}{
  326. "filter_correct": model.DefaultFilterCorrect,
  327. }).Error; err != nil {
  328. zaplog.Error("UpdateFilterCorrect", zap.Any("filter_correct", err))
  329. }
  330. }
  331. // UpdateChangeAdJust 更新群体校正数据
  332. func (e *Entry) UpdateChangeAdJust(pastureId int64, xToday *XToday) {
  333. res := make([]*model.NeckRingBarChange, 0)
  334. oneDayAgo := time.Now().Local().AddDate(0, 0, -1).Format(model.LayoutDate2)
  335. if err := e.DB.Table(fmt.Sprintf("%s as h", new(model.NeckActiveHabit).TableName())).
  336. Select(`h.neck_ring_number,h.heat_date, h.frameid, c.pen_id, c.pen_name, COUNT(*) as nb,
  337. ROUND(AVG(h.change_high)) as change_high, ROUND(AVG(h.change_filter)) as change_filter`).
  338. Joins("JOIN cow as c ON h.cow_id = c.id").
  339. Where("h.pasture_id = ?", pastureId).
  340. Where("h.heat_date >= ?", oneDayAgo).
  341. Where("h.cow_id > ?", 0).
  342. Where("c.pen_id > ?", 0).
  343. Group("h.heat_date, h.frameid, c.pen_id").
  344. Order("h.heat_date, h.frameid, c.pen_id").
  345. Find(&res).Error; err != nil {
  346. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("xToday", xToday))
  347. }
  348. for _, v := range res {
  349. if math.Abs(float64(v.ChangeFilter)) < 10 {
  350. continue
  351. }
  352. if err := e.DB.Model(new(model.NeckActiveHabit)).
  353. Where("pasture_id = ?", pastureId).
  354. Where("neck_ring_number = ?", v.NeckRingNumber).
  355. Where("heat_date = ?", v.HeatDate).
  356. //Where("pen_id = ?", v.PenId).
  357. Where("frameid = ?", v.FrameId).
  358. Update("change_adjust", v.ChangeFilter).Error; err != nil {
  359. zaplog.Error("UpdateChangeAdJust-1", zap.Any("error", err), zap.Any("xToday", xToday))
  360. }
  361. }
  362. }
  363. func (e *Entry) UpdateCft(pastureId int64, processIds []int64) {
  364. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  365. if err := e.DB.Model(new(model.NeckActiveHabit)).
  366. Where("id IN (?)", processIds).
  367. Where("pasture_id = ?", pastureId).
  368. Where("is_show = ?", pasturePb.IsShow_No).
  369. Find(&neckActiveHabitList).Error; err != nil {
  370. zaplog.Error("UpdateCft-1", zap.Any("error", err))
  371. }
  372. for _, v := range neckActiveHabitList {
  373. cft := CalculateCFT(v)
  374. if err := e.DB.Model(new(model.NeckActiveHabit)).
  375. Where("id = ?", v.Id).
  376. Where("neck_ring_number = ?", v.NeckRingNumber).
  377. Update("cft", strconv.FormatFloat(float64(cft), 'f', 2, 64)).Error; err != nil {
  378. zaplog.Error("UpdateCft-2", zap.Any("error", err))
  379. }
  380. }
  381. }
  382. func (e *Entry) UpdateIsShow(pastureId int64, processIds []int64) {
  383. if err := e.DB.Model(new(model.NeckActiveHabit)).
  384. Where("id IN (?)", processIds).
  385. Where("pasture_id = ?", pastureId).
  386. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  387. zaplog.Error("UpdateChangeAdJust-2", zap.Any("error", err))
  388. }
  389. }
  390. func (e *Entry) XToday(pastureId int64) (*XToday, error) {
  391. xToday := &XToday{}
  392. systemConfigureList, err := e.FindSystemNeckRingConfigure(pastureId)
  393. if err != nil {
  394. return nil, xerr.WithStack(err)
  395. }
  396. if len(systemConfigureList) <= 0 {
  397. return nil, nil
  398. }
  399. for _, v := range systemConfigureList {
  400. switch v.Name {
  401. case model.MaxHabit:
  402. xToday.LastMaxHabitId = v.Value
  403. case model.High:
  404. xToday.High = int32(v.Value)
  405. case model.Rumina:
  406. xToday.Rumina = int32(v.Value)
  407. case model.XRuminaDisc:
  408. xToday.XRuminaDisc = int32(v.Value)
  409. case model.XChangeDiscount:
  410. xToday.XChangeDiscount = int32(v.Value)
  411. case model.WeeklyActive:
  412. xToday.WeeklyActive = int32(v.Value)
  413. case model.BeforeDayNeckRing:
  414. xToday.BeforeDayNeckRing = int32(v.Value)
  415. }
  416. }
  417. return xToday, nil
  418. }
  419. // WeeklyUpdateActiveHabit 时间点周平均值计算
  420. func (e *Entry) WeeklyUpdateActiveHabit(pastureId int64, processIds []int64, xToDay *XToday) {
  421. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  422. if err := e.DB.Model(new(model.NeckActiveHabit)).
  423. Where("id IN (?)", processIds).
  424. Order("heat_date,neck_ring_number,frameid").
  425. Find(&newNeckActiveHabitList).Error; err != nil {
  426. zaplog.Error("WeeklyUpdateActiveHabit", zap.Any("error", err), zap.Any("processIds", processIds))
  427. }
  428. if len(newNeckActiveHabitList) <= 0 {
  429. return
  430. }
  431. e.HabitUpdateActiveHabit(pastureId, newNeckActiveHabitList, xToDay)
  432. e.SumUpdateActiveHabit(pastureId, newNeckActiveHabitList, xToDay)
  433. e.ActiveChange(pastureId, processIds, xToDay)
  434. e.Before3DaysNeckActiveHabit(pastureId, processIds)
  435. }
  436. func (e *Entry) HabitUpdateActiveHabit(pastureId int64, newNeckActiveHabitList []*model.NeckActiveHabit, xToDay *XToday) {
  437. for _, v := range newNeckActiveHabitList {
  438. // 前七天的
  439. weekHabitData := e.FindWeekHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  440. // 更新过滤值
  441. if err := e.DB.Model(new(model.NeckActiveHabit)).
  442. Select("high_habit", "rumina_habit", "chew_habit", "intake_habit", "inactive_habit").
  443. Where("id = ?", v.Id).
  444. Updates(map[string]interface{}{
  445. "high_habit": weekHabitData.HighHabit,
  446. "rumina_habit": weekHabitData.RuminaHabit,
  447. "chew_habit": weekHabitData.ChewHabit,
  448. "intake_habit": weekHabitData.IntakeHabit,
  449. "inactive_habit": weekHabitData.InactiveHabit,
  450. }).Error; err != nil {
  451. zaplog.Error("WeeklyUpdateActiveHabit",
  452. zap.Error(err),
  453. zap.Any("NeckActiveHabit", v),
  454. zap.Any("pastureId", pastureId),
  455. )
  456. }
  457. }
  458. }
  459. // SumUpdateActiveHabit -- 累计24小时数值
  460. func (e *Entry) SumUpdateActiveHabit(pastureId int64, newNeckActiveHabitList []*model.NeckActiveHabit, xToDay *XToday) {
  461. for _, v := range newNeckActiveHabitList {
  462. sumHabitData := e.FindSumHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  463. // 更新过滤值
  464. if err := e.DB.Model(new(model.NeckActiveHabit)).
  465. Select("sum_rumina", "sum_intake", "sum_inactive", "sum_active", "sum_max_high", "sum_min_high", "sum_min_chew").
  466. Where("id = ?", v.Id).
  467. Updates(map[string]interface{}{
  468. "sum_rumina": sumHabitData.SumRumina,
  469. "sum_intake": sumHabitData.SumIntake,
  470. "sum_inactive": sumHabitData.SumInactive,
  471. "sum_active": sumHabitData.SumActive,
  472. "sum_max_high": sumHabitData.SumMaxHigh,
  473. "sum_min_high": sumHabitData.SumMinHigh,
  474. "sum_min_chew": sumHabitData.SumMinChew,
  475. }).Error; err != nil {
  476. zaplog.Error("WeeklyUpdateActiveHabit",
  477. zap.Any("err", err),
  478. zap.Any("NeckActiveHabit", v),
  479. zap.Any("pastureId", pastureId),
  480. )
  481. }
  482. }
  483. }
  484. // ActiveChange -- 变化百分比
  485. func (e *Entry) ActiveChange(pastureId int64, processIds []int64, xToDay *XToday) {
  486. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  487. if err := e.DB.Model(new(model.NeckActiveHabit)).
  488. Where("pasture_id = ?", pastureId).
  489. Where("id IN (?)", processIds).
  490. Where("high_habit > ?", 0).
  491. Where(e.DB.Where("high >= ?", xToDay.High).Or("rumina >= ?", xToDay.Rumina)).
  492. Find(&newNeckActiveHabitList).Error; err != nil {
  493. zaplog.Error("ActiveChange", zap.Any("error", err), zap.Any("processIds", processIds))
  494. }
  495. for _, v := range newNeckActiveHabitList {
  496. changeHigh := calculateChangeHigh(v, xToDay.WeeklyActive)
  497. changeRumina := int32(0)
  498. changeChew := int32(0)
  499. if v.RuminaHabit != 0 {
  500. changeRumina = int32(math.Round(float64(v.FilterRumina-v.RuminaHabit) / float64(v.RuminaHabit) * 100))
  501. }
  502. if v.ChewHabit != 0 {
  503. changeChew = int32(math.Round(float64(v.FilterChew-v.ChewHabit) / float64(v.ChewHabit) * 100))
  504. }
  505. // 更新过滤值
  506. if err := e.DB.Model(new(model.NeckActiveHabit)).
  507. Select("change_high", "change_rumina", "change_chew").
  508. Where("id = ?", v.Id).
  509. Updates(map[string]interface{}{
  510. "change_high": changeHigh,
  511. "change_rumina": changeRumina,
  512. "change_chew": changeChew,
  513. }).Error; err != nil {
  514. zaplog.Error("ActiveChange",
  515. zap.Any("err", err),
  516. zap.Any("NeckActiveHabit", v),
  517. )
  518. }
  519. }
  520. }
  521. func (e *Entry) Before3DaysNeckActiveHabit(pastureId int64, processIds []int64) {
  522. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  523. if err := e.DB.Model(new(model.NeckActiveHabit)).
  524. Where("id IN (?)", processIds).
  525. Order("heat_date,neck_ring_number,frameid").
  526. Find(&newNeckActiveHabitList).Error; err != nil {
  527. zaplog.Error("Before3DaysNeckActiveHabit", zap.Any("error", err), zap.Any("processIds", processIds))
  528. }
  529. for _, v := range newNeckActiveHabitList {
  530. before3DaysNeckActiveHabit := e.FindBefore3DaysNeckActiveHabit(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid)
  531. if before3DaysNeckActiveHabit.SumRumina == 0 && before3DaysNeckActiveHabit.SumIntake == 0 {
  532. continue
  533. }
  534. // 更新过滤值
  535. if err := e.DB.Model(new(model.NeckActiveHabit)).
  536. Select("before_three_sum_rumina", "before_three_sum_intake").
  537. Where("id = ?", v.Id).
  538. Updates(map[string]interface{}{
  539. "before_three_sum_rumina": before3DaysNeckActiveHabit.SumRumina,
  540. "before_three_sum_intake": before3DaysNeckActiveHabit.SumIntake,
  541. }).Error; err != nil {
  542. zaplog.Error("Before3DaysNeckActiveHabit",
  543. zap.Error(err),
  544. zap.Any("NeckActiveHabit", v),
  545. zap.Any("pastureId", pastureId),
  546. )
  547. }
  548. }
  549. }
  550. // calculateChangeHigh 计算活动量变化
  551. func calculateChangeHigh(data *model.NeckActiveHabit, weeklyActive int32) int32 {
  552. highDiff := data.FilterHigh - data.HighHabit
  553. changeHigh := int32(0)
  554. if highDiff > 0 {
  555. denominator := float64(data.WeekHigh)*0.6 + float64(data.HighHabit)*0.2 + float64(weeklyActive)*0.2
  556. changeHigh = int32(math.Round((float64(highDiff) / denominator) * 100))
  557. } else {
  558. changeHigh = int32(math.Round(float64(highDiff) / float64(data.HighHabit) * 100))
  559. }
  560. return changeHigh
  561. }