estrus_warning.go 9.8 KB

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