neck_ring_calculate.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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. if len(processIds) <= 0 {
  44. return nil
  45. }
  46. e.WeeklyUpdateActiveHabit(pastureId, processIds, xToday)
  47. // 二次更新滤波
  48. e.SecondUpdateChangeFilter(pastureId, processIds, xToday)
  49. // 活动量校正系数和健康评分
  50. e.FilterCorrectAndScoreUpdate(pastureId, processIds, xToday)
  51. // 更新 ChangeFilter
  52. e.UpdateChangeFilter(pastureId, processIds)
  53. // 更新 FilterCorrect
  54. e.UpdateFilterCorrect(pastureId, processIds)
  55. // 插入群体校正表
  56. e.UpdateChangeAdJust(pastureId, processIds)
  57. // 更新 Cft
  58. e.UpdateCft(pastureId, processIds)
  59. // 更新所有的显示状态为否的记录为是
  60. e.UpdateIsShow(pastureId, processIds)
  61. // 健康预警
  62. e.HealthWarning(pastureId, processIds)
  63. return nil
  64. }
  65. // FirstFilterUpdate 首次更新活动滤波
  66. func (e *Entry) FirstFilterUpdate(pastureId int64, xToDay *XToday) (processIds []int64, err error) {
  67. limit := e.Cfg.NeckRingLimit
  68. if limit <= 0 {
  69. limit = defaultLimit
  70. }
  71. firstHeatDate := time.Now().Local().AddDate(0, 0, int(xToDay.BeforeDayNeckRing)*-1).Format(model.LayoutDate2)
  72. querySql := `SELECT * FROM neck_active_habit WHERE pasture_id = ? AND is_show = ? AND heat_date >= ? AND high >= ?
  73. UNION
  74. SELECT * FROM neck_active_habit WHERE pasture_id = ? AND is_show = ? AND heat_date >= ? AND rumina >= ?
  75. ORDER BY active_time,neck_ring_number,frameid LIMIT ?`
  76. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  77. if err = e.DB.Raw(
  78. querySql,
  79. pastureId, pasturePb.IsShow_No, firstHeatDate, xToDay.High,
  80. pastureId, pasturePb.IsShow_No, firstHeatDate, xToDay.Rumina,
  81. limit,
  82. ).Find(&newNeckActiveHabitList).Error; err != nil {
  83. return nil, xerr.WithStack(err)
  84. }
  85. // 活动量滤波
  86. for _, v := range newNeckActiveHabitList {
  87. // 4小时数据不全的不参与滤波
  88. activeTime, _ := util.TimeParseLocal(model.LayoutTime, v.ActiveTime)
  89. if v.RecordCount != model.DefaultRecordCount && time.Now().Local().Sub(activeTime).Hours() <= 4 {
  90. continue
  91. }
  92. // 过滤牛只未绑定的脖环的数据
  93. cowInfo := e.GetCowInfoByNeckRingNumber(v.PastureId, v.NeckRingNumber)
  94. if cowInfo == nil || cowInfo.Id <= 0 {
  95. v.UpdateIsShowOk()
  96. if err = e.DB.Model(new(model.NeckActiveHabit)).
  97. Select("is_show").
  98. Where("id = ?", v.Id).
  99. Updates(v).Error; err != nil {
  100. zaplog.Error("EntryUpdateActiveHabit", zap.Any("error", err))
  101. }
  102. continue
  103. }
  104. frameId := v.Frameid
  105. heatDate := v.HeatDate
  106. if v.Frameid == 0 {
  107. frameId = 11
  108. heatDateParse, _ := util.TimeParseLocal(model.LayoutDate2, heatDate)
  109. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  110. } else {
  111. frameId -= 1
  112. }
  113. firstFilterData := e.FindFilterData(pastureId, v.NeckRingNumber, heatDate, frameId)
  114. if v.FilterHigh > 0 {
  115. firstFilterData.FilterHigh = v.FilterHigh
  116. } else {
  117. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  118. firstFilterData.FilterHigh = int32(computeIfPositiveElse(float64(v.High), float64(firstFilterData.FilterHigh), 0.23, 0.77))
  119. } else {
  120. firstFilterData.FilterHigh = v.High
  121. }
  122. }
  123. if v.FilterRumina > 0 {
  124. firstFilterData.FilterRumina = v.FilterRumina
  125. } else {
  126. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  127. firstFilterData.FilterRumina = int32(computeIfPositiveElse(float64(v.Rumina), float64(firstFilterData.FilterRumina), 0.33, 0.67))
  128. } else {
  129. firstFilterData.FilterRumina = v.Rumina
  130. }
  131. }
  132. if v.FilterChew > 0 {
  133. firstFilterData.FilterChew = v.FilterChew
  134. } else {
  135. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  136. firstFilterData.FilterChew = int32(computeIfPositiveElse(float64(v.Rumina+v.Intake), float64(firstFilterData.FilterChew), 0.33, 0.67))
  137. } else {
  138. firstFilterData.FilterChew = v.Rumina + v.Intake
  139. }
  140. }
  141. cowWeeklyActive := cowInfo.WeeklyActive
  142. if cowWeeklyActive <= 0 {
  143. cowWeeklyActive = v.WeekHigh
  144. }
  145. processIds = append(processIds, v.Id)
  146. // 更新过滤值
  147. if err = e.DB.Model(new(model.NeckActiveHabit)).
  148. Select("filter_high", "filter_rumina", "filter_chew", "cow_id", "lact", "calving_age", "ear_number", "pen_id", "week_high").
  149. Where("id = ?", v.Id).
  150. Updates(map[string]interface{}{
  151. "filter_high": firstFilterData.FilterHigh,
  152. "filter_rumina": firstFilterData.FilterRumina,
  153. "filter_chew": firstFilterData.FilterChew,
  154. "cow_id": cowInfo.Id,
  155. "lact": cowInfo.Lact,
  156. "calving_age": cowInfo.CalvingAge,
  157. "ear_number": cowInfo.EarNumber,
  158. "pen_id": cowInfo.PenId,
  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. if err := e.DB.Model(new(model.NeckActiveHabit)).
  234. Select("change_filter", "rumina_filter", "chew_filter").
  235. Where("id = ?", v.Id).
  236. Updates(map[string]interface{}{
  237. "change_filter": int32(changeFilter),
  238. "rumina_filter": int32(ruminaFilter),
  239. "chew_filter": int32(chewFilter),
  240. }).Error; err != nil {
  241. zaplog.Error("SecondUpdateChangeFilter", zap.Any("error", err), zap.Any("secondFilterData", secondFilterData))
  242. }
  243. }
  244. }
  245. // FilterCorrectAndScoreUpdate 计算活动量变化趋势校正值(活跃度校正)和健康评分
  246. func (e *Entry) FilterCorrectAndScoreUpdate(pastureId int64, processIds []int64, xToday *XToday) {
  247. beginDayDate := time.Now().Local()
  248. before7DayDate := beginDayDate.AddDate(0, 0, -7).Format(model.LayoutDate2)
  249. before1DayDate := beginDayDate.AddDate(0, 0, -1).Format(model.LayoutDate2)
  250. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  251. if err := e.DB.Model(new(model.NeckActiveHabit)).
  252. Where("id IN (?)", processIds).
  253. Where("pasture_id = ?", pastureId).
  254. Find(&neckActiveHabitList).Error; err != nil {
  255. zaplog.Error("ActivityVolumeChanges-1", zap.Any("error", err), zap.Any("xToday", xToday))
  256. return
  257. }
  258. for _, v := range neckActiveHabitList {
  259. cowScore := calculateScore(v)
  260. if err := e.DB.Model(new(model.NeckActiveHabit)).
  261. Where("id = ?", v.Id).
  262. Update("score", cowScore).Error; err != nil {
  263. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  264. }
  265. activityVolume := &ActivityVolume{}
  266. if err := e.DB.Model(new(model.NeckActiveHabit)).
  267. Select("neck_ring_number", "AVG(IF(change_filter>=60, 60, change_filter)) as avg_filter",
  268. "ROUND(STD(IF(change_filter>=60, 60, change_filter))) as std_filter", "COUNT(1) as nb").
  269. Where("heat_date BETWEEN ? AND ?", before7DayDate, before1DayDate).
  270. Where("pasture_id = ?", pastureId).
  271. Where(e.DB.Where("high > ?", 12).Or("rumina >= ?", xToday.Rumina)).
  272. Where("active_time <= ?", beginDayDate.Add(-12*time.Hour).Format(model.LayoutTime)).
  273. Where("change_filter > ?", MinChangeFilter).
  274. Where("neck_ring_number = ?", v.NeckRingNumber).
  275. Having("nb >= ?", DefaultNb).
  276. First(&activityVolume).Error; err != nil {
  277. zaplog.Error("ActivityVolumeChanges-0", zap.Any("error", err), zap.Any("xToday", xToday), zap.Any("v", v))
  278. continue
  279. }
  280. if activityVolume != nil && activityVolume.NeckRingNumber != "" {
  281. filterCorrect := model.DefaultFilterCorrect - int(math.Round(activityVolume.AvgFilter/3+float64(int(math.Round(activityVolume.StdFilter))/2)))
  282. // 活动量校正系数
  283. if err := e.DB.Model(new(model.NeckActiveHabit)).
  284. Where("id = ?", v.Id).
  285. Update("filter_correct", filterCorrect).Error; err != nil {
  286. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  287. continue
  288. }
  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, processIds []int64) {
  320. neckRingPenChangeList := make([]*model.NeckRingPenChange, 0)
  321. yesterday := time.Now().Local().AddDate(0, 0, -1).Format(model.LayoutDate2)
  322. if err := e.DB.Model(new(model.NeckActiveHabit)).
  323. Select(`heat_date,frameid,pen_id,COUNT(*) AS cow_count,ROUND(AVG(change_high)) AS change_high,ROUND(AVG(change_filter)) AS change_filter`).
  324. Where("pasture_id = ?", pastureId).
  325. Where("heat_date >= ?", yesterday).
  326. Where("cow_id > ?", 0).
  327. Where("pen_id > ?", 0).
  328. Group("heat_date,frameid,pen_id").
  329. Order("heat_date,frameid,pen_id").
  330. Find(&neckRingPenChangeList).Error; err != nil {
  331. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("pastureId", pastureId))
  332. }
  333. for _, v := range neckRingPenChangeList {
  334. var count int64
  335. if err := e.DB.Model(new(model.NeckRingPenChange)).
  336. Where("pasture_id = ?", pastureId).
  337. Where("heat_date = ?", v.HeatDate).
  338. Where("frameid = ?", v.Frameid).
  339. Where("pen_id = ?", v.PenId).
  340. Count(&count).Error; err != nil {
  341. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("v", v), zap.Any("pastureId", pastureId))
  342. }
  343. // 有就更新,没有就新增
  344. if count > 0 {
  345. if err := e.DB.Model(new(model.NeckRingPenChange)).
  346. Where("pasture_id = ?", pastureId).
  347. Where("heat_date = ?", v.HeatDate).
  348. Where("frameid = ?", v.Frameid).
  349. Where("pen_id = ?", v.PenId).
  350. Updates(map[string]interface{}{
  351. "cow_count": v.CowCount,
  352. "change_high": v.ChangeHigh,
  353. "change_filter": v.ChangeFilter,
  354. }).Error; err != nil {
  355. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("v", v), zap.Any("pastureId", pastureId))
  356. }
  357. } else {
  358. neckRingPenChange := model.NewNeckRingPenChange(pastureId, v.HeatDate, v.CowCount, v.Frameid, v.PenId, v.ChangeHigh, v.ChangeFilter)
  359. if err := e.DB.Model(new(model.NeckRingPenChange)).
  360. Create(neckRingPenChange).Error; err != nil {
  361. zaplog.Error("UpdateChangeAdJust",
  362. zap.Any("error", err),
  363. zap.Any("neckRingPenChange", neckRingPenChange),
  364. zap.Any("pastureId", pastureId),
  365. )
  366. }
  367. }
  368. }
  369. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  370. if err := e.DB.Model(new(model.NeckActiveHabit)).
  371. Where("id IN (?)", processIds).
  372. Where("pasture_id = ?", pastureId).
  373. Find(&neckActiveHabitList).Error; err != nil {
  374. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err))
  375. }
  376. if len(neckActiveHabitList) <= 0 {
  377. return
  378. }
  379. for _, v := range neckActiveHabitList {
  380. neckRingPenChange := &model.NeckRingPenChange{}
  381. if err := e.DB.Model(new(model.NeckRingPenChange)).
  382. Where("pasture_id = ?", pastureId).
  383. Where("heat_date = ?", v.HeatDate).
  384. Where("frameid = ?", v.Frameid).
  385. Where("pen_id = ?", v.PenId).
  386. First(&neckRingPenChange).Error; err != nil {
  387. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("v", v), zap.Any("pastureId", pastureId))
  388. continue
  389. }
  390. if neckRingPenChange == nil || neckRingPenChange.Id <= 0 {
  391. continue
  392. }
  393. if neckRingPenChange.ChangeFilter < 10 {
  394. continue
  395. }
  396. if err := e.DB.Model(new(model.NeckActiveHabit)).
  397. Where("id = ?", v.Id).
  398. Update("change_adjust", neckRingPenChange.ChangeFilter).Error; err != nil {
  399. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("v", v), zap.Any("neckRingPenChange", neckRingPenChange))
  400. }
  401. }
  402. }
  403. func (e *Entry) UpdateCft(pastureId int64, processIds []int64) {
  404. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  405. if err := e.DB.Model(new(model.NeckActiveHabit)).
  406. Where("id IN (?)", processIds).
  407. Where("pasture_id = ?", pastureId).
  408. Where("is_show = ?", pasturePb.IsShow_No).
  409. Find(&neckActiveHabitList).Error; err != nil {
  410. zaplog.Error("UpdateCft-1", zap.Any("error", err))
  411. }
  412. for _, v := range neckActiveHabitList {
  413. cft := CalculateCFT(v)
  414. if err := e.DB.Model(new(model.NeckActiveHabit)).
  415. Where("id = ?", v.Id).
  416. Where("neck_ring_number = ?", v.NeckRingNumber).
  417. Update("cft", strconv.FormatFloat(float64(cft), 'f', 2, 64)).Error; err != nil {
  418. zaplog.Error("UpdateCft-2", zap.Any("error", err))
  419. }
  420. }
  421. }
  422. func (e *Entry) UpdateIsShow(pastureId int64, processIds []int64) {
  423. if err := e.DB.Model(new(model.NeckActiveHabit)).
  424. Where("id IN (?)", processIds).
  425. Where("pasture_id = ?", pastureId).
  426. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  427. zaplog.Error("UpdateChangeAdJust-2", zap.Any("error", err))
  428. }
  429. }
  430. func (e *Entry) XToday(pastureId int64) (*XToday, error) {
  431. xToday := &XToday{}
  432. systemConfigureList, err := e.FindSystemNeckRingConfigure(pastureId)
  433. if err != nil {
  434. return nil, xerr.WithStack(err)
  435. }
  436. if len(systemConfigureList) <= 0 {
  437. return nil, nil
  438. }
  439. for _, v := range systemConfigureList {
  440. switch v.Name {
  441. case model.MaxHabit:
  442. xToday.LastMaxHabitId = v.Value
  443. case model.High:
  444. xToday.High = int32(v.Value)
  445. case model.Rumina:
  446. xToday.Rumina = int32(v.Value)
  447. case model.XRuminaDisc:
  448. xToday.XRuminaDisc = int32(v.Value)
  449. case model.XChangeDiscount:
  450. xToday.XChangeDiscount = int32(v.Value)
  451. case model.WeeklyActive:
  452. xToday.WeeklyActive = int32(v.Value)
  453. case model.BeforeDayNeckRing:
  454. xToday.BeforeDayNeckRing = int32(v.Value)
  455. }
  456. }
  457. return xToday, nil
  458. }
  459. // WeeklyUpdateActiveHabit 时间点周平均值计算
  460. func (e *Entry) WeeklyUpdateActiveHabit(pastureId int64, processIds []int64, xToDay *XToday) {
  461. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  462. if err := e.DB.Model(new(model.NeckActiveHabit)).
  463. Where("id IN (?)", processIds).
  464. Order("heat_date,neck_ring_number,frameid").
  465. Find(&newNeckActiveHabitList).Error; err != nil {
  466. zaplog.Error("WeeklyUpdateActiveHabit", zap.Any("error", err), zap.Any("processIds", processIds))
  467. }
  468. if len(newNeckActiveHabitList) <= 0 {
  469. return
  470. }
  471. e.HabitUpdateActiveHabit(pastureId, newNeckActiveHabitList, xToDay)
  472. e.SumUpdateActiveHabit(pastureId, newNeckActiveHabitList, xToDay)
  473. e.ActiveChange(pastureId, processIds, xToDay)
  474. e.Before3DaysNeckActiveHabit(pastureId, processIds)
  475. }
  476. func (e *Entry) HabitUpdateActiveHabit(pastureId int64, newNeckActiveHabitList []*model.NeckActiveHabit, xToDay *XToday) {
  477. for _, v := range newNeckActiveHabitList {
  478. // 前七天的
  479. weekHabitData := e.FindWeekHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  480. // 更新过滤值
  481. if err := e.DB.Model(new(model.NeckActiveHabit)).
  482. Select("high_habit", "rumina_habit", "chew_habit", "intake_habit", "inactive_habit").
  483. Where("id = ?", v.Id).
  484. Updates(map[string]interface{}{
  485. "high_habit": weekHabitData.HighHabit,
  486. "rumina_habit": weekHabitData.RuminaHabit,
  487. "chew_habit": weekHabitData.ChewHabit,
  488. "intake_habit": weekHabitData.IntakeHabit,
  489. "inactive_habit": weekHabitData.InactiveHabit,
  490. }).Error; err != nil {
  491. zaplog.Error("WeeklyUpdateActiveHabit",
  492. zap.Error(err),
  493. zap.Any("NeckActiveHabit", v),
  494. zap.Any("pastureId", pastureId),
  495. )
  496. }
  497. }
  498. }
  499. // SumUpdateActiveHabit -- 累计24小时数值
  500. func (e *Entry) SumUpdateActiveHabit(pastureId int64, newNeckActiveHabitList []*model.NeckActiveHabit, xToDay *XToday) {
  501. for _, v := range newNeckActiveHabitList {
  502. sumHabitData := e.FindSumHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  503. // 更新过滤值
  504. if err := e.DB.Model(new(model.NeckActiveHabit)).
  505. Select("sum_rumina", "sum_intake", "sum_inactive", "sum_active", "sum_max_high", "sum_min_high", "sum_min_chew").
  506. Where("id = ?", v.Id).
  507. Updates(map[string]interface{}{
  508. "sum_rumina": sumHabitData.SumRumina,
  509. "sum_intake": sumHabitData.SumIntake,
  510. "sum_inactive": sumHabitData.SumInactive,
  511. "sum_active": sumHabitData.SumActive,
  512. "sum_max_high": sumHabitData.SumMaxHigh,
  513. "sum_min_high": sumHabitData.SumMinHigh,
  514. "sum_min_chew": sumHabitData.SumMinChew,
  515. }).Error; err != nil {
  516. zaplog.Error("WeeklyUpdateActiveHabit",
  517. zap.Any("err", err),
  518. zap.Any("NeckActiveHabit", v),
  519. zap.Any("pastureId", pastureId),
  520. )
  521. }
  522. }
  523. }
  524. // ActiveChange -- 变化百分比
  525. func (e *Entry) ActiveChange(pastureId int64, processIds []int64, xToDay *XToday) {
  526. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  527. if err := e.DB.Model(new(model.NeckActiveHabit)).
  528. Where("pasture_id = ?", pastureId).
  529. Where("id IN (?)", processIds).
  530. Where("high_habit > ?", 0).
  531. Where(e.DB.Where("high >= ?", xToDay.High).Or("rumina >= ?", xToDay.Rumina)).
  532. Find(&newNeckActiveHabitList).Error; err != nil {
  533. zaplog.Error("ActiveChange", zap.Any("error", err), zap.Any("processIds", processIds))
  534. }
  535. for _, v := range newNeckActiveHabitList {
  536. changeHigh := calculateChangeHigh(v, xToDay.WeeklyActive)
  537. changeRumina := int32(0)
  538. changeChew := int32(0)
  539. if v.RuminaHabit != 0 {
  540. changeRumina = int32(math.Round(float64(v.FilterRumina-v.RuminaHabit) / float64(v.RuminaHabit) * 100))
  541. }
  542. if v.ChewHabit != 0 {
  543. changeChew = int32(math.Round(float64(v.FilterChew-v.ChewHabit) / float64(v.ChewHabit) * 100))
  544. }
  545. // 更新过滤值
  546. if err := e.DB.Model(new(model.NeckActiveHabit)).
  547. Select("change_high", "change_rumina", "change_chew").
  548. Where("id = ?", v.Id).
  549. Updates(map[string]interface{}{
  550. "change_high": changeHigh,
  551. "change_rumina": changeRumina,
  552. "change_chew": changeChew,
  553. }).Error; err != nil {
  554. zaplog.Error("ActiveChange",
  555. zap.Any("err", err),
  556. zap.Any("NeckActiveHabit", v),
  557. )
  558. }
  559. }
  560. }
  561. func (e *Entry) Before3DaysNeckActiveHabit(pastureId int64, processIds []int64) {
  562. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  563. if err := e.DB.Model(new(model.NeckActiveHabit)).
  564. Where("id IN (?)", processIds).
  565. Order("heat_date,neck_ring_number,frameid").
  566. Find(&newNeckActiveHabitList).Error; err != nil {
  567. zaplog.Error("Before3DaysNeckActiveHabit", zap.Any("error", err), zap.Any("processIds", processIds))
  568. }
  569. for _, v := range newNeckActiveHabitList {
  570. before3DaysNeckActiveHabit := e.FindBefore3DaysNeckActiveHabit(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid)
  571. if before3DaysNeckActiveHabit.SumRumina == 0 && before3DaysNeckActiveHabit.SumIntake == 0 {
  572. continue
  573. }
  574. // 更新过滤值
  575. if err := e.DB.Model(new(model.NeckActiveHabit)).
  576. Select("before_three_sum_rumina", "before_three_sum_intake").
  577. Where("id = ?", v.Id).
  578. Updates(map[string]interface{}{
  579. "before_three_sum_rumina": before3DaysNeckActiveHabit.SumRumina,
  580. "before_three_sum_intake": before3DaysNeckActiveHabit.SumIntake,
  581. }).Error; err != nil {
  582. zaplog.Error("Before3DaysNeckActiveHabit",
  583. zap.Error(err),
  584. zap.Any("NeckActiveHabit", v),
  585. zap.Any("pastureId", pastureId),
  586. )
  587. }
  588. }
  589. }
  590. // calculateChangeHigh 计算活动量变化
  591. func calculateChangeHigh(data *model.NeckActiveHabit, weeklyActive int32) int32 {
  592. highDiff := data.FilterHigh - data.HighHabit
  593. changeHigh := int32(0)
  594. if highDiff > 0 {
  595. denominator := float64(data.WeekHigh)*0.6 + float64(data.HighHabit)*0.2 + float64(weeklyActive)*0.2
  596. changeHigh = int32(math.Round((float64(highDiff) / denominator) * 100))
  597. } else {
  598. changeHigh = int32(math.Round(float64(highDiff) / float64(data.HighHabit) * 100))
  599. }
  600. return changeHigh
  601. }