health_warning.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package crontab
  2. import (
  3. "kpt-pasture/model"
  4. "kpt-pasture/util"
  5. "math"
  6. "time"
  7. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  8. "gitee.com/xuyiping_admin/pkg/xerr"
  9. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  10. "go.uber.org/zap"
  11. )
  12. // HealthWarning 健康预警 create_jbq_update_2024
  13. func (e *Entry) HealthWarning(pastureId int64, processIds []int64) {
  14. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  15. if err := e.DB.Model(new(model.NeckActiveHabit)).
  16. Where("pasture_id = ?", pastureId).
  17. Where("id IN (?)", processIds).
  18. Where("score BETWEEN ? AND ?", model.MinScore, model.MaxScore).
  19. Order("neck_ring_number,heat_date,frameid").
  20. Find(&newNeckActiveHabitList).Error; err != nil {
  21. zaplog.Error("HealthWarning", zap.Any("error", err), zap.Any("processIds", processIds))
  22. }
  23. var (
  24. lastCowID int64 = 0
  25. lastHeatDate string = "2001-01-01"
  26. lastScore int32 = 100
  27. healthWarningList []*model.NeckRingHealth
  28. )
  29. for _, habit := range newNeckActiveHabitList {
  30. if habit.ChangeFilter <= -99 {
  31. habit.ChangeFilter = 0
  32. }
  33. if habit.ChewFilter <= -99 {
  34. habit.ChewFilter = 0
  35. }
  36. if habit.SumMinHigh <= -99 {
  37. habit.SumMinHigh = 0
  38. }
  39. if habit.SumMaxHigh <= -99 {
  40. habit.SumMaxHigh = 0
  41. }
  42. if habit.SumMinChew <= -99 {
  43. habit.SumMinChew = 0
  44. }
  45. sumChew := habit.SumRumina + habit.SumIntake
  46. chew3dago := habit.BeforeThreeSumRumina + habit.BeforeThreeSumIntake
  47. isWorse := 1
  48. if habit.CowId == lastCowID && habit.HeatDate == lastHeatDate && habit.Score >= lastScore {
  49. isWorse = 0
  50. }
  51. lastCowID = habit.CowId
  52. lastHeatDate = habit.HeatDate
  53. lastScore = habit.Score
  54. if isWorse == 1 {
  55. newHealthWarning := model.NewNeckRingHealth(habit, sumChew, chew3dago)
  56. healthWarningList = append(healthWarningList, newHealthWarning)
  57. }
  58. }
  59. if len(healthWarningList) > 0 {
  60. e.updateNeckRingHealth(pastureId, healthWarningList)
  61. }
  62. }
  63. func (e *Entry) updateNeckRingHealth(pastureId int64, healthWarningList []*model.NeckRingHealth) {
  64. for _, v := range healthWarningList {
  65. startAt := util.TimeParseLocalUnix(v.HeatDate)
  66. endAt := util.TimeParseLocalEndUnix(v.HeatDate)
  67. isMove := e.isEventCowLog(pastureId, v.CowId, startAt, endAt, pasturePb.EventType_Transfer_Ben)
  68. if isMove {
  69. v.IsTransferGroup = pasturePb.IsShow_Ok
  70. }
  71. isDryMilk := e.isEventCowLog(pastureId, v.CowId, startAt, endAt, pasturePb.EventType_Dry_Milk)
  72. if isDryMilk {
  73. v.IsDryMilk = pasturePb.IsShow_Ok
  74. }
  75. isImmunization := e.isEventCowLog(pastureId, v.CowId, startAt, endAt, pasturePb.EventType_Immunication)
  76. if isImmunization {
  77. v.IsImmunization = pasturePb.IsShow_Ok
  78. }
  79. }
  80. zaplog.Info("HealthWarning", zap.Any("healthWarningList", healthWarningList))
  81. if err := e.DB.Model(new(model.NeckRingHealth)).Create(&healthWarningList).Error; err != nil {
  82. zaplog.Error("HealthWarning", zap.Any("error", err), zap.Any("healthWarningList", healthWarningList))
  83. }
  84. }
  85. func (e *Entry) isEventCowLog(pastureId int64, CowId int64, startAt, endAt int64, eventType pasturePb.EventType_Kind) bool {
  86. var count int64
  87. eventCowLog := &model.EventCowLog{CowId: CowId}
  88. if err := e.DB.Table(eventCowLog.TableName()).
  89. Where("pasture_id = ?", pastureId).
  90. Where("cow_id = ?", CowId).
  91. Where("event_at BETWEEN ? AND ?", startAt, endAt).
  92. Where("event_type = ?", eventType).
  93. Count(&count).Error; err != nil {
  94. return false
  95. }
  96. return count > 0
  97. }
  98. func (e *Entry) NeckRingHealthWarning() error {
  99. pastureList := e.FindPastureList()
  100. if pastureList == nil || len(pastureList) == 0 {
  101. return nil
  102. }
  103. for _, pasture := range pastureList {
  104. e.DB.Model(new(model.NeckRingHealthWarning)).
  105. Where("pasture_id = ?", pasture.Id).
  106. Delete(new(model.NeckRingHealthWarning))
  107. if err := e.UpdateNeckRingHealth(pasture.Id); err != nil {
  108. zaplog.Error("NeckRingHealthWarning",
  109. zap.Any("UpdateNeckRingHealth", err),
  110. zap.Any("pasture", pasture),
  111. )
  112. }
  113. }
  114. return nil
  115. }
  116. func (e *Entry) UpdateNeckRingHealth(pastureId int64) error {
  117. neckRingConfigureList, err := e.FindSystemNeckRingConfigure(pastureId)
  118. if err != nil {
  119. return xerr.WithStack(err)
  120. }
  121. healthValue := int32(0)
  122. for _, v := range neckRingConfigureList {
  123. if v.Name != model.HealthWarning {
  124. continue
  125. }
  126. healthValue = int32(v.Value)
  127. }
  128. newNeckRingHealthWarningList, err := e.FindNewNeckRingHealthWarning(pastureId, healthValue)
  129. if err != nil {
  130. return xerr.WithStack(err)
  131. }
  132. if len(newNeckRingHealthWarningList) > 0 {
  133. if err = e.DB.Model(new(model.NeckRingHealthWarning)).
  134. Create(&newNeckRingHealthWarningList).Error; err != nil {
  135. zaplog.Error("UpdateNeckRingHealth",
  136. zap.Any("error", err),
  137. zap.Any("newNeckRingHealthWarningList", newNeckRingHealthWarningList),
  138. )
  139. }
  140. }
  141. return nil
  142. }
  143. func calculateNewScore(data *model.NeckRingHealth) int32 {
  144. otherScore := int32(0)
  145. otherScore += calculateMilkFilterScore(data.FilterMilk, data.MaxHigh)
  146. if data.IsTransferGroup == pasturePb.IsShow_Ok {
  147. otherScore += 3
  148. }
  149. if data.IsDryMilk == pasturePb.IsShow_Ok {
  150. otherScore += 5
  151. }
  152. if data.IsImmunization == pasturePb.IsShow_Ok {
  153. otherScore += 12
  154. }
  155. return data.Score + otherScore
  156. }
  157. func calculateMilkFilterScore(milkFilter int32, maxHigh int32) int32 {
  158. // 处理NULL值,默认为0
  159. milkFilterValue := int32(0)
  160. if milkFilter != 0 {
  161. milkFilterValue = milkFilter
  162. }
  163. // 计算系数:如果maxHigh>50则为0.5,否则为1
  164. coefficient := 1.0
  165. if maxHigh > 50 {
  166. coefficient = 0.5
  167. }
  168. // 计算中间值:milkFilterValue * 0.3 * coefficient
  169. intermediateValue := float64(milkFilterValue) * 0.3 * coefficient
  170. // 四舍五入
  171. roundedValue := math.Round(intermediateValue)
  172. // 取最小值(roundedValue和0中的较小值)
  173. result := int32(math.Min(roundedValue, 0))
  174. return result
  175. }
  176. func (e *Entry) FindNewNeckRingHealthWarning(pastureId int64, healthValue int32) ([]*model.NeckRingHealthWarning, error) {
  177. nowTime := time.Now().Local()
  178. //endTime := nowTime.Format(model.LayoutDate2)
  179. startTime := nowTime.AddDate(0, 0, -1).Format(model.LayoutDate2)
  180. neckRingHealthList := make([]*model.NeckRingHealth, 0)
  181. if err := e.DB.Model(new(model.NeckRingHealth)).
  182. Select(`MAX(id) AS id,heat_date,neck_ring_number,cow_id,score,max_high,created_at,min_high,min_chew,
  183. min_intake,sum_chew,before_three_sum_chew`).
  184. Where("pasture_id = ?", pastureId).
  185. Where("heat_date >= ?", startTime).
  186. Group("neck_ring_number").
  187. Find(&neckRingHealthList).Error; err != nil {
  188. return nil, xerr.WithStack(err)
  189. }
  190. newNeckRingHealthWarningList := make([]*model.NeckRingHealthWarning, 0)
  191. for _, v := range neckRingHealthList {
  192. if v.HeatDate == "" {
  193. continue
  194. }
  195. cowInfo, err := e.GetCowById(pastureId, v.CowId)
  196. if err != nil || cowInfo == nil {
  197. continue
  198. }
  199. newScore := calculateNewScore(v)
  200. zaplog.Info("calculateNewScore",
  201. zap.Any("newScore", newScore),
  202. zap.Any("v", v),
  203. zap.Any("healthValue", healthValue),
  204. zap.Any("cowInfo", cowInfo),
  205. )
  206. if newScore > healthValue {
  207. continue
  208. }
  209. if e.HistoryNeckRingHealthWarning(pastureId, cowInfo.NeckRingNumber, v.HeatDate) {
  210. continue
  211. }
  212. if e.FindNeckRingError(pastureId, cowInfo.NeckRingNumber) {
  213. continue
  214. }
  215. newNeckRingHealthWarning := model.NewNeckRingHealthWarning(pastureId, v, cowInfo, newScore)
  216. zaplog.Info("newNeckRingHealthWarning",
  217. zap.Any("newNeckRingHealthWarning", newNeckRingHealthWarning),
  218. zap.Any("pastureId", pastureId),
  219. zap.Any("neckRingHealth", v),
  220. zap.Any("cowInfo", cowInfo),
  221. zap.Any("newScore", newScore),
  222. )
  223. newNeckRingHealthWarningList = append(newNeckRingHealthWarningList, newNeckRingHealthWarning)
  224. }
  225. return newNeckRingHealthWarningList, nil
  226. }
  227. func (e *Entry) HistoryNeckRingHealthWarning(pastureId int64, neckRingNumber string, heatDate string) bool {
  228. var count int64
  229. if err := e.DB.Model(new(model.NeckRingHealthWarning)).
  230. Where("pasture_id = ?", pastureId).
  231. Where("neck_ring_number = ?", neckRingNumber).
  232. Where("heat_date = ?", heatDate).
  233. Where("is_show = ?", pasturePb.IsShow_Ok).
  234. Count(&count).Error; err != nil {
  235. return false
  236. }
  237. return count > 0
  238. }
  239. func (e *Entry) FindNeckRingError(pastureId int64, neckRingNumber string) bool {
  240. var count int64
  241. if err := e.DB.Model(new(model.NeckRing)).
  242. Where("pasture_id = ?", pastureId).
  243. Where("neck_ring_number = ?", neckRingNumber).
  244. Where("status = ?", pasturePb.IsShow_No).
  245. Where("error_kind = ?", pasturePb.NeckRingNumberError_Suspected_Fall_Off).
  246. Count(&count).Error; err != nil {
  247. return false
  248. }
  249. return count > 0
  250. }