health_warning.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. zaplog.Info("HealthWarning", zap.Any("healthWarningList", healthWarningList))
  65. for _, v := range healthWarningList {
  66. startAt := util.TimeParseLocalUnix(v.HeatDate)
  67. endAt := util.TimeParseLocalEndUnix(v.HeatDate)
  68. isMove := e.isEventCowLog(pastureId, v.CowId, startAt, endAt, pasturePb.EventType_Transfer_Ben)
  69. if isMove {
  70. v.IsTransferGroup = pasturePb.IsShow_Ok
  71. }
  72. isDryMilk := e.isEventCowLog(pastureId, v.CowId, startAt, endAt, pasturePb.EventType_Dry_Milk)
  73. if isDryMilk {
  74. v.IsDryMilk = pasturePb.IsShow_Ok
  75. }
  76. isImmunization := e.isEventCowLog(pastureId, v.CowId, startAt, endAt, pasturePb.EventType_Immunication)
  77. if isImmunization {
  78. v.IsImmunization = pasturePb.IsShow_Ok
  79. }
  80. }
  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", zap.Any("UpdateNeckRingHealth", err), zap.Any("pasture", pasture))
  109. }
  110. }
  111. return nil
  112. }
  113. func (e *Entry) UpdateNeckRingHealth(pastureId int64) error {
  114. neckRingConfigureList, err := e.FindSystemNeckRingConfigure(pastureId)
  115. if err != nil {
  116. return xerr.WithStack(err)
  117. }
  118. healthValue := int32(0)
  119. for _, v := range neckRingConfigureList {
  120. if v.Name != model.HealthWarning {
  121. continue
  122. }
  123. healthValue = int32(v.Value)
  124. }
  125. newNeckRingHealthWarningList, err := e.FindNewNeckRingHealthWarning(pastureId, healthValue)
  126. if err != nil {
  127. return xerr.WithStack(err)
  128. }
  129. if len(newNeckRingHealthWarningList) > 0 {
  130. if err = e.DB.Model(new(model.NeckRingHealthWarning)).
  131. Create(&newNeckRingHealthWarningList).Error; err != nil {
  132. zaplog.Error("UpdateNeckRingHealth",
  133. zap.Any("error", err),
  134. zap.Any("newNeckRingHealthWarningList", newNeckRingHealthWarningList))
  135. }
  136. }
  137. return nil
  138. }
  139. func calculateNewScore(data *model.NeckRingHealth) int32 {
  140. otherScore := int32(0)
  141. otherScore += calculateMilkFilterScore(data.FilterMilk, data.MaxHigh)
  142. if data.IsTransferGroup == pasturePb.IsShow_Ok {
  143. otherScore += 3
  144. }
  145. if data.IsDryMilk == pasturePb.IsShow_Ok {
  146. otherScore += 5
  147. }
  148. if data.IsImmunization == pasturePb.IsShow_Ok {
  149. otherScore += 12
  150. }
  151. return data.Score + otherScore
  152. }
  153. func calculateMilkFilterScore(milkFilter int32, maxHigh int32) int32 {
  154. // 处理NULL值,默认为0
  155. milkFilterValue := int32(0)
  156. if milkFilter != 0 {
  157. milkFilterValue = milkFilter
  158. }
  159. // 计算系数:如果maxHigh>50则为0.5,否则为1
  160. coefficient := 1.0
  161. if maxHigh > 50 {
  162. coefficient = 0.5
  163. }
  164. // 计算中间值:milkFilterValue * 0.3 * coefficient
  165. intermediateValue := float64(milkFilterValue) * 0.3 * coefficient
  166. // 四舍五入
  167. roundedValue := math.Round(intermediateValue)
  168. // 取最小值(roundedValue和0中的较小值)
  169. result := int32(math.Min(roundedValue, 0))
  170. return result
  171. }
  172. func (e *Entry) FindNewNeckRingHealthWarning(pastureId int64, healthValue int32) ([]*model.NeckRingHealthWarning, error) {
  173. nowTime := time.Now().Local()
  174. //endTime := nowTime.Format(model.LayoutDate2)
  175. startTime := nowTime.AddDate(0, 0, -1).Format(model.LayoutDate2)
  176. neckRingHealthList := make([]*model.NeckRingHealth, 0)
  177. if err := e.DB.Model(new(model.NeckRingHealth)).
  178. Select(`MAX(id) AS id,heat_date,neck_ring_number,cow_id,score,max_high,created_at,min_high,min_chew,
  179. min_intake,sum_chew,before_three_sum_chew`).
  180. Where("pasture_id = ?", pastureId).
  181. Where("heat_date >= ?", startTime).
  182. Group("neck_ring_number").
  183. Find(&neckRingHealthList).Error; err != nil {
  184. return nil, xerr.WithStack(err)
  185. }
  186. newNeckRingHealthWarningList := make([]*model.NeckRingHealthWarning, 0)
  187. for _, v := range neckRingHealthList {
  188. if v.HeatDate == "" || v.HeatDate != nowTime.Format(model.LayoutDate2) {
  189. continue
  190. }
  191. cowInfo, err := e.GetCowById(pastureId, v.CowId)
  192. if err != nil {
  193. continue
  194. }
  195. if cowInfo == nil {
  196. continue
  197. }
  198. newScore := calculateNewScore(v)
  199. if newScore > healthValue {
  200. continue
  201. }
  202. if e.HistoryNeckRingHealthWarning(pastureId, cowInfo.NeckRingNumber, v.HeatDate) {
  203. continue
  204. }
  205. if e.FindNeckRingError(pastureId, cowInfo.NeckRingNumber) {
  206. continue
  207. }
  208. newNeckRingHealthWarning := model.NewNeckRingHealthWarning(pastureId, v, cowInfo, newScore)
  209. zaplog.Info("newNeckRingHealthWarning",
  210. zap.Any("newNeckRingHealthWarning", newNeckRingHealthWarning),
  211. zap.Any("pastureId", pastureId),
  212. zap.Any("neckRingHealth", v),
  213. zap.Any("cowInfo", cowInfo),
  214. zap.Any("newScore", newScore),
  215. )
  216. newNeckRingHealthWarningList = append(newNeckRingHealthWarningList, newNeckRingHealthWarning)
  217. }
  218. return newNeckRingHealthWarningList, nil
  219. }
  220. func (e *Entry) HistoryNeckRingHealthWarning(pastureId int64, neckRingNumber string, heatDate string) bool {
  221. var count int64
  222. if err := e.DB.Model(new(model.NeckRingHealthWarning)).
  223. Where("pasture_id = ?", pastureId).
  224. Where("neck_ring_number = ?", neckRingNumber).
  225. Where("heat_date = ?", heatDate).
  226. Where("is_show = ?", pasturePb.IsShow_Ok).
  227. Count(&count).Error; err != nil {
  228. return false
  229. }
  230. return count > 0
  231. }
  232. func (e *Entry) FindNeckRingError(pastureId int64, neckRingNumber string) bool {
  233. var count int64
  234. if err := e.DB.Model(new(model.NeckRing)).
  235. Where("pasture_id = ?", pastureId).
  236. Where("neck_ring_number = ?", neckRingNumber).
  237. Where("status = ?", pasturePb.IsShow_No).
  238. Where("error_kind = ?", pasturePb.NeckRingNumberError_Suspected_Fall_Off).
  239. Count(&count).Error; err != nil {
  240. return false
  241. }
  242. return count > 0
  243. }