estrus_warning.go 9.5 KB

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