neck_ring_calculate.go 22 KB

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