estrus_warning.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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.AddDate(0, 0, -1)
  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 >= ?", fmt.Sprintf("%s 00:00:00", startTime.Format(model.LayoutDate2))).
  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. e.UpdateNeckRingWarningIsPeak(pastureId, minId)
  67. return nil
  68. }
  69. func (e *Entry) UpdateNeckRingWarningIsPeak(pastureId, minId int64) {
  70. sqlQuery := e.DB.Table(fmt.Sprintf("%s as a", new(model.NeckActiveHabit).TableName())).
  71. Select("1").
  72. Where("a.id >= ?", minId).
  73. Where("a.cow_id = b.cow_id").
  74. Where("a.created_at > UNIX_TIMESTAMP(b.date_time)")
  75. if err := e.DB.Table(fmt.Sprintf("%s as b", new(model.NeckRingEstrusWarning).TableName())).
  76. Where("b.pasture_id = ?", pastureId).
  77. Where("EXISTS (?)", sqlQuery).Update("is_peak", pasturePb.IsShow_Ok).Error; err != nil {
  78. zaplog.Error("UpdateNeckRingWarningIsPeak", zap.Any("err", err))
  79. }
  80. }
  81. func (e *Entry) UpdateHighChange(pastureId, minId int64) {
  82. estrusWarningList, err := e.GetCowHighChange(pastureId, minId)
  83. if err != nil {
  84. zaplog.Error("UpdateHighChange", zap.Any("err", err))
  85. return
  86. }
  87. zaplog.Info("UpdateHighChange", zap.Any("estrusWarningList", estrusWarningList))
  88. for _, v := range estrusWarningList {
  89. neckRingEstrusWarning := &model.NeckRingEstrusWarning{}
  90. if err = e.DB.Model(new(model.NeckRingEstrusWarning)).
  91. Where("neck_ring_estrus_id = ?", v.NeckRingEstrusId).
  92. Find(neckRingEstrusWarning).Error; err != nil {
  93. zaplog.Error("UpdateHighChange", zap.Any("Find", err), zap.Any("v", v))
  94. continue
  95. }
  96. if v.Nb1 <= model.MinNb1 {
  97. count := e.getCowHigh(pastureId, v.CowId, minId, v.DateTime)
  98. if count <= 0 {
  99. if err = e.DB.Model(new(model.NeckRingEstrusWarning)).
  100. Where("neck_ring_estrus_id = ?", v.NeckRingEstrusId).
  101. Where("cow_id = ?", v.CowId).
  102. Where("pasture_id = ?", pastureId).Delete(new(model.NeckRingEstrusWarning)).Error; err != nil {
  103. zaplog.Error("UpdateHighChange", zap.Any("Delete", err), zap.Any("v", v))
  104. }
  105. continue
  106. }
  107. }
  108. if err = e.DB.Model(new(model.NeckRingEstrusWarning)).
  109. Where("neck_ring_estrus_id = ?", v.NeckRingEstrusId).
  110. Updates(map[string]interface{}{
  111. "warning_kind": pasturePb.Warning_Estrus,
  112. "high_change": v.HighChange,
  113. }).Error; err != nil {
  114. zaplog.Error("UpdateHighChange", zap.Any("Updates", err), zap.Any("v", v))
  115. continue
  116. }
  117. }
  118. }
  119. func (e *Entry) GroupAndProcessData(records []*model.NeckRingEstrus) []*model.NeckRingEstrusWarning {
  120. groups := make(map[int64]*model.GroupEstrusData)
  121. // 分组处理
  122. for _, record := range records {
  123. // 从关联的Cow表获取信息(这里需要根据实际关联方式调整)
  124. // 假设已通过JOIN获取到CowID等信息
  125. // 实际实现可能需要预加载Cow信息
  126. key := record.CowId
  127. if _, exist := groups[key]; !exist {
  128. groups[key] = &model.GroupEstrusData{
  129. CowId: record.CowId,
  130. PastureId: record.PastureId,
  131. Records: make([]*model.NeckRingEstrus, 0),
  132. EarNumber: record.EarNumber,
  133. NeckRingNumber: record.NeckRingNumber,
  134. Moved: false,
  135. }
  136. }
  137. // 检查是否在移牛列表中
  138. // 假设通过CowID判断,需要根据实际关联关系调整
  139. /*if _, moved := movedCows[record.CowId]; moved {
  140. groups[key].Moved = true
  141. }*/
  142. groups[key].Records = append(groups[key].Records, record)
  143. }
  144. // 处理每个分组
  145. var neckRingEstrusWarningList []*model.NeckRingEstrusWarning
  146. for _, group := range groups {
  147. if len(group.Records) == 0 {
  148. continue
  149. }
  150. // 排序记录
  151. sort.Slice(group.Records, func(i, j int) bool {
  152. return group.Records[i].Id > group.Records[j].Id
  153. })
  154. // 计算字段
  155. latest := group.Records[0]
  156. maxId := findMaxId(group.Records)
  157. firstTime := findMaxTime(group.Records, func(r *model.NeckRingEstrus) string { return r.FirstTime })
  158. dateTime := findMaxTime(group.Records, func(r *model.NeckRingEstrus) string { return r.ActiveTime })
  159. neckRingEstrusWarning := model.NewNeckRingEstrusWarning(
  160. maxId, group.PastureId, group.CowId, group.EarNumber, group.NeckRingNumber,
  161. firstTime, dateTime, latest.LastTime, pasturePb.Warning_Estrus, latest.ActiveLevel,
  162. )
  163. neckRingEstrusWarningList = append(neckRingEstrusWarningList, neckRingEstrusWarning)
  164. }
  165. return neckRingEstrusWarningList
  166. }
  167. func (e *Entry) GetCowHighChange(pastureId, minId int64) ([]*model.EstrusWarning, error) {
  168. nowTime := time.Now().Add(-48 * time.Hour)
  169. estrusWarningList := make([]*model.EstrusWarning, 0)
  170. if err := e.DB.Table(fmt.Sprintf("%s as a", new(model.NeckActiveHabit).TableName())).
  171. Select(
  172. "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",
  173. "b.neck_ring_estrus_id", "b.cow_id", "b.date_time", "COUNT(a.change_filter>-99) as nb1",
  174. "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").
  175. Joins("JOIN neck_ring_estrus_warning as b ON a.cow_id = b.cow_id AND a.pasture_id = b.pasture_id").
  176. Where("a.id > ?", minId).
  177. Where("a.pasture_id = ?", pastureId).
  178. Where("a.created_at > ?", nowTime.Unix()).
  179. Group("b.neck_ring_estrus_id").
  180. Having("nb1 <= ? AND nb2 >= ?", model.Nb1, model.Nb2).
  181. Find(&estrusWarningList).
  182. Error; err != nil {
  183. return nil, xerr.WithStack(err)
  184. }
  185. return estrusWarningList, nil
  186. }
  187. // getRecentMovedCows 辅助函数:检查是否在移牛事件
  188. func (e *Entry) getRecentMovedCows(pastureId, cowId int64) bool {
  189. var count int64
  190. startDate := time.Now().AddDate(0, 0, -2)
  191. table := &model.EventCowLog{CowId: cowId}
  192. if err := e.DB.Table(table.TableName()).
  193. Where("cow_id = ?", cowId).
  194. Where("pasture = ?", pastureId).
  195. Where("event_type = ?", pasturePb.EventType_Transfer_Ben).
  196. Where("event_at >= ?", startDate.Unix()).
  197. Count(&count).Error; err != nil {
  198. return false
  199. }
  200. if count > 0 {
  201. return true
  202. }
  203. return false
  204. }
  205. func (e *Entry) getMinId(pastureId int64) int64 {
  206. var minId int64
  207. nowTime := time.Now().AddDate(0, 0, -2).Format(model.LayoutDate2)
  208. if err := e.DB.Model(new(model.NeckActiveHabit)).
  209. Select("MIN(id) as id").
  210. Where("heat_date = ?", nowTime).
  211. Where("pasture_id = ?", pastureId).
  212. Scan(&minId).Error; err != nil {
  213. return 1
  214. }
  215. return minId
  216. }
  217. func (e *Entry) getCowHigh(pastureId, cowId, minId int64, dateTime string) int64 {
  218. dateTimeUnix, _ := util.TimeParseLocal(model.LayoutTime, dateTime)
  219. dateTimeUnixStart := time.Time{}
  220. if dateTimeUnix.IsZero() {
  221. dateTimeUnixStart = time.Now().Add(-22 * time.Hour)
  222. } else {
  223. dateTimeUnixStart = dateTimeUnix.Add(-22 * time.Hour)
  224. }
  225. var count int64
  226. if err := e.DB.Model(new(model.NeckActiveHabit)).
  227. Select("COUNT(0) as count").
  228. Where("created_at BETWEEN ? AND ?", dateTimeUnixStart.Unix(), dateTimeUnix).
  229. Where("pasture_id = ?", pastureId).
  230. Where("cow_id = ?", cowId).
  231. Where("id >= ?", minId).
  232. Scan(&count).Error; err != nil {
  233. return 0
  234. }
  235. return count
  236. }
  237. // 辅助函数:计算最大时间
  238. func findMaxTime(records []*model.NeckRingEstrus, getter func(*model.NeckRingEstrus) string) string {
  239. var max time.Time
  240. for _, r := range records {
  241. t1 := getter(r)
  242. if t1 == "" {
  243. continue
  244. }
  245. t, err := util.TimeParseLocal(model.LayoutTime, t1)
  246. if err != nil {
  247. continue
  248. }
  249. if t.After(max) {
  250. max = t
  251. }
  252. }
  253. if max.IsZero() {
  254. return ""
  255. }
  256. return max.Format(model.LayoutTime)
  257. }
  258. func findMaxId(records []*model.NeckRingEstrus) int64 {
  259. maxId := int64(0)
  260. for _, v := range records {
  261. if v.Id > maxId {
  262. maxId = v.Id
  263. }
  264. }
  265. return maxId
  266. }