estrus_warning.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package crontab
  2. import (
  3. "fmt"
  4. "kpt-pasture/model"
  5. "kpt-pasture/util"
  6. "sort"
  7. "time"
  8. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  9. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  10. "gitee.com/xuyiping_admin/pkg/xerr"
  11. "go.uber.org/zap"
  12. )
  13. // NeckRingEstrusWarning 脖环发情预警
  14. func (e *Entry) NeckRingEstrusWarning() (err 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.UpdateNeckRingWarning(pasture.Id); err != nil {
  21. zaplog.Error("UpdateNeckRingWarning", zap.Any("NeckRingEstrusWarning", err), zap.Any("pasture", pasture))
  22. }
  23. }
  24. return nil
  25. }
  26. func (e *Entry) UpdateNeckRingWarning(pastureId int64) (err error) {
  27. // 先删除历史数据
  28. if err = e.DB.Model(new(model.NeckRingEstrusWarning)).
  29. Where("pasture_id = ?", pastureId).
  30. Delete(new(model.NeckRingEstrusWarning)).Error; err != nil {
  31. return xerr.WithStack(err)
  32. }
  33. // 计算时间范围
  34. now := time.Now()
  35. startTime := now.Add(-24 * time.Hour)
  36. neckRingEstrusList := make([]*model.NeckRingEstrus, 0)
  37. if err = e.DB.Table(fmt.Sprintf("%s as a", new(model.NeckRingEstrus).TableName())).
  38. Select("a.*").
  39. Joins("JOIN cow as b ON a.cow_id = b.id AND a.pasture_id = b.pasture_id").
  40. Where("a.pasture_id = ?", pastureId).
  41. Where("a.active_time >= ?", startTime.Format(model.LayoutTime)).
  42. Where("a.active_level >= ?", pasturePb.EstrusLevel_Low).
  43. Where("a.check_result IN (?)", []pasturePb.CheckResult_Kind{pasturePb.CheckResult_Pending, pasturePb.CheckResult_Correct}).
  44. Where("a.is_show = ?", pasturePb.IsShow_Ok).
  45. Where("a.is_peak >= ?", pasturePb.IsShow_Ok).
  46. Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
  47. Find(&neckRingEstrusList).Error; err != nil {
  48. return xerr.WithStack(err)
  49. }
  50. zaplog.Info("UpdateNeckRingWarning", zap.Any("neckRingEstrusList", neckRingEstrusList))
  51. if len(neckRingEstrusList) == 0 {
  52. return nil
  53. }
  54. neckRingEstrusWarningList := e.GroupAndProcessData(neckRingEstrusList)
  55. zaplog.Info("UpdateNeckRingWarning", zap.Any("neckRingEstrusWarningList", neckRingEstrusWarningList))
  56. if len(neckRingEstrusWarningList) > 0 {
  57. if err = e.DB.CreateInBatches(neckRingEstrusWarningList, 50).Error; err != nil {
  58. return xerr.WithStack(err)
  59. }
  60. } else {
  61. return nil
  62. }
  63. minId := e.getMinId(pastureId)
  64. // 更新HighChange字段
  65. // e.UpdateHighChange(pastureId,minId)
  66. // 更新IsPeak字段
  67. e.UpdateNeckRingWarningIsPeak(pastureId, minId)
  68. return nil
  69. }
  70. func (e *Entry) UpdateNeckRingWarningIsPeak(pastureId, minId int64) {
  71. sqlQuery := e.DB.Table(fmt.Sprintf("%s as a", new(model.NeckActiveHabit).TableName())).
  72. Select("1").
  73. Where("a.id >= ?", minId).
  74. Where("a.cow_id = b.cow_id").
  75. Where("a.created_at > UNIX_TIMESTAMP(b.date_time)")
  76. if err := e.DB.Table(fmt.Sprintf("%s as b", new(model.NeckRingEstrusWarning).TableName())).
  77. Where("b.pasture_id = ?", pastureId).
  78. Where("EXISTS (?)", sqlQuery).
  79. Update("is_peak", pasturePb.IsShow_Ok).Error; err != nil {
  80. zaplog.Error("UpdateNeckRingWarningIsPeak", zap.Any("err", err))
  81. }
  82. }
  83. func (e *Entry) UpdateHighChange(pastureId, minId int64) {
  84. estrusWarningList, err := e.GetCowHighChange(pastureId, minId)
  85. if err != nil {
  86. zaplog.Error("UpdateHighChange", zap.Any("err", err))
  87. return
  88. }
  89. zaplog.Info("UpdateHighChange", zap.Any("estrusWarningList", estrusWarningList))
  90. for _, v := range estrusWarningList {
  91. neckRingEstrusWarning := &model.NeckRingEstrusWarning{}
  92. if err = e.DB.Model(new(model.NeckRingEstrusWarning)).
  93. Where("neck_ring_estrus_id = ?", v.NeckRingEstrusId).
  94. Find(neckRingEstrusWarning).Error; err != nil {
  95. zaplog.Error("UpdateHighChange", zap.Any("Find", err), zap.Any("v", v))
  96. continue
  97. }
  98. if v.Nb1 <= model.MinNb1 {
  99. count := e.getCowHigh(pastureId, v.CowId, minId, v.DateTime)
  100. if count <= 0 {
  101. if err = e.DB.Model(new(model.NeckRingEstrusWarning)).
  102. Where("neck_ring_estrus_id = ?", v.NeckRingEstrusId).
  103. Where("cow_id = ?", v.CowId).
  104. Where("pasture_id = ?", pastureId).Delete(new(model.NeckRingEstrusWarning)).Error; err != nil {
  105. zaplog.Error("UpdateHighChange", zap.Any("Delete", err), zap.Any("v", v))
  106. }
  107. continue
  108. }
  109. }
  110. if err = e.DB.Model(new(model.NeckRingEstrusWarning)).
  111. Where("neck_ring_estrus_id = ?", v.NeckRingEstrusId).
  112. Updates(map[string]interface{}{
  113. "warning_kind": pasturePb.Warning_Estrus,
  114. "high_change": v.HighChange,
  115. }).Error; err != nil {
  116. zaplog.Error("UpdateHighChange", zap.Any("Updates", err), zap.Any("v", v))
  117. continue
  118. }
  119. }
  120. }
  121. func (e *Entry) GroupAndProcessData(records []*model.NeckRingEstrus) []*model.NeckRingEstrusWarning {
  122. groups := make(map[int64]*model.GroupEstrusData)
  123. // 分组处理
  124. for _, record := range records {
  125. // 从关联的Cow表获取信息(这里需要根据实际关联方式调整)
  126. // 假设已通过JOIN获取到CowID等信息
  127. // 实际实现可能需要预加载Cow信息
  128. key := record.CowId
  129. if _, exist := groups[key]; !exist {
  130. groups[key] = &model.GroupEstrusData{
  131. CowId: record.CowId,
  132. PastureId: record.PastureId,
  133. Records: make([]*model.NeckRingEstrus, 0),
  134. EarNumber: record.EarNumber,
  135. NeckRingNumber: record.NeckRingNumber,
  136. Moved: false,
  137. }
  138. }
  139. // 检查是否在移牛列表中
  140. if moved := e.getRecentMovedCows(record.PastureId, record.CowId); moved {
  141. groups[key].Moved = true
  142. }
  143. groups[key].Records = append(groups[key].Records, record)
  144. }
  145. // 处理每个分组
  146. var neckRingEstrusWarningList []*model.NeckRingEstrusWarning
  147. for _, group := range groups {
  148. if len(group.Records) == 0 {
  149. continue
  150. }
  151. // 排序记录
  152. sort.Slice(group.Records, func(i, j int) bool {
  153. return group.Records[i].Id > group.Records[j].Id
  154. })
  155. // 计算字段
  156. latest := group.Records[0]
  157. maxId := findMaxId(group.Records)
  158. firstTime := findMaxTime(group.Records, func(r *model.NeckRingEstrus) string { return r.FirstTime })
  159. dateTime := findMaxTime(group.Records, func(r *model.NeckRingEstrus) string { return r.ActiveTime })
  160. neckRingEstrusWarning := model.NewNeckRingEstrusWarning(
  161. maxId, group.PastureId, group.CowId, group.EarNumber, group.NeckRingNumber,
  162. firstTime, dateTime, latest.LastTime, pasturePb.Warning_Estrus, latest.ActiveLevel,
  163. )
  164. neckRingEstrusWarningList = append(neckRingEstrusWarningList, neckRingEstrusWarning)
  165. }
  166. return neckRingEstrusWarningList
  167. }
  168. func (e *Entry) GetCowHighChange(pastureId, minId int64) ([]*model.EstrusWarning, error) {
  169. nowTime := time.Now().Add(-48 * time.Hour)
  170. estrusWarningList := make([]*model.EstrusWarning, 0)
  171. if err := e.DB.Table(fmt.Sprintf("%s as a", new(model.NeckActiveHabit).TableName())).
  172. Select(
  173. "GROUP_CONCAT(IF(ROUND(a.change_filter*a.filter_correct/100,0)=-99,'',ROUND(a.change_filter*a.filter_correct/100,0)) ) as high_change",
  174. "b.neck_ring_estrus_id", "b.cow_id", "b.date_time", "COUNT(a.change_filter>-99) as nb1",
  175. "COUNT(a.change_filter=-99 AND a.created_at>=(STR_TO_DATE(b.date_time,'%Y-%m-%d %H:%i:%s') -INTERVAL 48 HOUR )) as nb2").
  176. Joins("JOIN neck_ring_estrus_warning as b ON a.cow_id = b.cow_id AND a.pasture_id = b.pasture_id").
  177. Where("a.id > ?", minId).
  178. Where("a.pasture_id = ?", pastureId).
  179. Where("a.created_at > ?", nowTime.Unix()).
  180. Group("b.neck_ring_estrus_id").
  181. Having("nb1 <= ? AND nb2 >= ?", model.Nb1, model.Nb2).
  182. Find(&estrusWarningList).
  183. Error; err != nil {
  184. return nil, xerr.WithStack(err)
  185. }
  186. return estrusWarningList, nil
  187. }
  188. // getRecentMovedCows 辅助函数:检查是否在移牛事件
  189. func (e *Entry) getRecentMovedCows(pastureId, cowId int64) bool {
  190. var count int64
  191. startDate := time.Now().AddDate(0, 0, -2)
  192. table := &model.EventCowLog{CowId: cowId}
  193. if err := e.DB.Table(table.TableName()).
  194. Where("cow_id = ?", cowId).
  195. Where("pasture_id = ?", pastureId).
  196. Where("event_type = ?", pasturePb.EventType_Transfer_Ben).
  197. Where("event_at >= ?", startDate.Unix()).
  198. Count(&count).Error; err != nil {
  199. return false
  200. }
  201. if count > 0 {
  202. return true
  203. }
  204. return false
  205. }
  206. func (e *Entry) getMinId(pastureId int64) int64 {
  207. var minId int64
  208. nowTime := time.Now().AddDate(0, 0, -2).Format(model.LayoutDate2)
  209. if err := e.DB.Model(new(model.NeckActiveHabit)).
  210. Select("MIN(id) as id").
  211. Where("heat_date = ?", nowTime).
  212. Where("pasture_id = ?", pastureId).
  213. Scan(&minId).Error; err != nil {
  214. return 1
  215. }
  216. return minId
  217. }
  218. func (e *Entry) getCowHigh(pastureId, cowId, minId int64, dateTime string) int64 {
  219. dateTimeUnix, _ := util.TimeParseLocal(model.LayoutTime, dateTime)
  220. dateTimeUnixStart := time.Time{}
  221. if dateTimeUnix.IsZero() {
  222. dateTimeUnixStart = time.Now().Add(-22 * time.Hour)
  223. } else {
  224. dateTimeUnixStart = dateTimeUnix.Add(-22 * time.Hour)
  225. }
  226. var count int64
  227. if err := e.DB.Model(new(model.NeckActiveHabit)).
  228. Select("COUNT(0) as count").
  229. Where("created_at BETWEEN ? AND ?", dateTimeUnixStart.Unix(), dateTimeUnix).
  230. Where("pasture_id = ?", pastureId).
  231. Where("cow_id = ?", cowId).
  232. Where("id >= ?", minId).
  233. Scan(&count).Error; err != nil {
  234. return 0
  235. }
  236. return count
  237. }
  238. // 辅助函数:计算最大时间
  239. func findMaxTime(records []*model.NeckRingEstrus, getter func(*model.NeckRingEstrus) string) string {
  240. var max time.Time
  241. for _, r := range records {
  242. t1 := getter(r)
  243. if t1 == "" {
  244. continue
  245. }
  246. t, err := util.TimeParseLocal(model.LayoutTime, t1)
  247. if err != nil {
  248. continue
  249. }
  250. if t.After(max) {
  251. max = t
  252. }
  253. }
  254. if max.IsZero() {
  255. return ""
  256. }
  257. return max.Format(model.LayoutTime)
  258. }
  259. func findMaxId(records []*model.NeckRingEstrus) int64 {
  260. maxId := int64(0)
  261. for _, v := range records {
  262. if v.Id > maxId {
  263. maxId = v.Id
  264. }
  265. }
  266. return maxId
  267. }