neck_ring_estrus.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. "go.uber.org/zap"
  11. "gitee.com/xuyiping_admin/pkg/xerr"
  12. )
  13. const (
  14. MaxRuminaAdJust = 20
  15. XAdjust21 = 15
  16. XAdjust42 = 10
  17. RumtoHeat = 0.5
  18. MinCalvingAge = 20
  19. MinLact = 0
  20. NormalChangJust = 10
  21. B48 = 48
  22. )
  23. func (e *Entry) UpdateCowEstrus() (err error) {
  24. pastureList := e.FindPastureList()
  25. if pastureList == nil || len(pastureList) == 0 {
  26. return nil
  27. }
  28. for _, pasture := range pastureList {
  29. if err = e.EntryCowEstrus(pasture.Id); err != nil {
  30. zaplog.Error("EntryCrontab", zap.Any("PastureUpdateCowEstrus", err), zap.Any("pasture", pasture))
  31. }
  32. zaplog.Info("PastureUpdateCowEstrus-success", zap.Any("pasture", pasture.Id))
  33. }
  34. return nil
  35. }
  36. func (e *Entry) EntryCowEstrus(pastureId int64) (err error) {
  37. xToday := &XToday{}
  38. systemConfigureList, err := e.FindSystemNeckRingConfigure(pastureId)
  39. if err != nil {
  40. return xerr.WithStack(err)
  41. }
  42. if systemConfigureList == nil || len(systemConfigureList) == 0 {
  43. return nil
  44. }
  45. for _, v := range systemConfigureList {
  46. switch v.Name {
  47. case model.ActiveLow:
  48. xToday.ActiveLow = int32(v.Value)
  49. case model.ActiveMiddle:
  50. xToday.ActiveMiddle = int32(v.Value)
  51. case model.ActiveHigh:
  52. xToday.ActiveHigh = int32(v.Value)
  53. }
  54. }
  55. nowTime := time.Now().Local()
  56. e.CowEstrusWarning(pastureId, xToday, nowTime)
  57. e.UpdateNewNeckRingEstrus(pastureId, xToday, nowTime)
  58. return nil
  59. }
  60. // CowEstrusWarning 发情预警
  61. func (e *Entry) CowEstrusWarning(pastureId int64, xToday *XToday, nowTime time.Time) {
  62. cft := xToday.ActiveLow - XAdjust21
  63. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  64. habitStartDate := nowTime.AddDate(0, 0, -1).Format(model.LayoutDate2)
  65. habitEndDate := nowTime.Format(model.LayoutDate2)
  66. if err := e.DB.Model(new(model.NeckActiveHabit)).
  67. Where("heat_date BETWEEN ? AND ?", habitStartDate, habitEndDate). // todo 查询的时间范围可以优化成当前时间的前12个小时的
  68. Where("pasture_id = ?", pastureId).
  69. Where("filter_high > 0 AND change_filter > ?", model.DefaultChangeFilter).
  70. Where("cow_id > ?", 0).
  71. Where("cft >= ?", cft).
  72. Where(e.DB.Where("calving_age >= ?", MinCalvingAge).Or("lact = ?", MinLact)). // 排除产后20天内的发情牛
  73. Order("cow_id").
  74. Find(&neckActiveHabitList).Error; err != nil {
  75. zaplog.Error("CowEstrusWarning", zap.Any("Find", err))
  76. return
  77. }
  78. neckActiveHabitMap := make(map[int64][]*model.NeckActiveHabit)
  79. for _, habit := range neckActiveHabitList {
  80. if neckActiveHabitMap[habit.CowId] == nil {
  81. neckActiveHabitMap[habit.CowId] = make([]*model.NeckActiveHabit, 0)
  82. }
  83. neckActiveHabitMap[habit.CowId] = append(neckActiveHabitMap[habit.CowId], habit)
  84. }
  85. neckRingEstrusList := make([]*model.NeckRingEstrus, 0)
  86. for cowId, cowHabitList := range neckActiveHabitMap {
  87. // 最近3天最大发情记录,小于该变化趋势的不再插入
  88. before3StartDate := nowTime.AddDate(0, 0, -2).Format(model.LayoutTime)
  89. before3Data := e.GetBeforeThreeDaysCowEstrus(pastureId, cowId, before3StartDate)
  90. // 判断最近50天内是否存在发情记录(发情等级>=2),如果18~25天@xadjust21,如果36~50天@xadjust42
  91. cow21EstrusStartDate := nowTime.AddDate(0, 0, -100).Format(model.LayoutTime)
  92. cow21EstrusEndDate := nowTime.AddDate(0, 0, -2).Format(model.LayoutTime)
  93. cow21Estrus := e.GetTwoEstrus(pastureId, cowId, cow21EstrusStartDate, cow21EstrusEndDate)
  94. if cow21Estrus.ActiveDate != "" {
  95. activeDateTime, _ := util.TimeParseLocal(model.LayoutTime, cow21Estrus.ActiveDate)
  96. if activeDateTime.Unix() >= nowTime.AddDate(0, 0, -25).Unix() && activeDateTime.Unix() <= nowTime.AddDate(0, 0, -18).Unix() {
  97. cow21Estrus.HadJust = XAdjust21
  98. }
  99. if activeDateTime.Unix() >= nowTime.AddDate(0, 0, -50).Unix() && activeDateTime.Unix() <= nowTime.AddDate(0, 0, -36).Unix() {
  100. cow21Estrus.HadJust = XAdjust42
  101. }
  102. }
  103. maxCft := float32(0)
  104. maxHigh := int32(0)
  105. lastActiveDate := time.Time{}
  106. for _, habit := range cowHabitList {
  107. if habit.Cft > maxCft {
  108. maxCft = habit.Cft
  109. }
  110. if habit.FilterHigh > maxHigh {
  111. maxHigh = habit.FilterHigh
  112. }
  113. // 获取最新的 CreateTime
  114. activeTimeParse, _ := util.TimeParseLocal(model.LayoutTime, habit.ActiveTime)
  115. if activeTimeParse.After(lastActiveDate) {
  116. lastActiveDate = activeTimeParse
  117. }
  118. }
  119. b48 := float64(0)
  120. if len(before3Data.ActiveTime) > 0 {
  121. t3, _ := util.TimeParseLocal(model.LayoutTime, before3Data.ActiveTime)
  122. b48 = t3.Sub(lastActiveDate).Hours()
  123. }
  124. if (int32(maxCft) > before3Data.DayHigh || before3Data.CowId == 0 || b48 > B48) && int32(maxCft)+cow21Estrus.HadJust > xToday.ActiveLow {
  125. level := calculateActiveLevel(maxCft, cow21Estrus, xToday)
  126. cowInfo, err := e.GetCowById(pastureId, cowId)
  127. if err != nil || cowInfo == nil {
  128. zaplog.Error("CowEstrusWarning", zap.Any("FindCowInfoByCowId", cowId))
  129. continue
  130. }
  131. if cowInfo.Sex == pasturePb.Genders_Male {
  132. continue
  133. }
  134. isShow := pasturePb.IsShow_Ok
  135. if cowInfo != nil && cowInfo.IsPregnant == pasturePb.IsShow_Ok && level == pasturePb.EstrusLevel_Low {
  136. isShow = pasturePb.IsShow_No
  137. }
  138. dayHigh := int32(maxCft) + cow21Estrus.HadJust
  139. lastEstrusDate := cow21Estrus.ActiveDate
  140. checkResult := getResult(before3Data, maxCft, cow21Estrus)
  141. activeTime := lastActiveDate.Format(model.LayoutTime)
  142. if e.HistoryNeckRingEstrus(pastureId, cowInfo.NeckRingNumber, activeTime) {
  143. continue
  144. }
  145. zaplog.Info("CowEstrusWarning",
  146. zap.Any("level", level),
  147. zap.Any("b48", b48),
  148. zap.Any("checkResult", checkResult),
  149. zap.Any("isShow", isShow),
  150. zap.Any("lastEstrusDate", lastEstrusDate),
  151. zap.Any("activeDate", lastActiveDate),
  152. zap.Any("dayHigh", dayHigh),
  153. zap.Any("maxCft", maxCft),
  154. zap.Any("before3Data", before3Data),
  155. zap.Any("cowEstrus", cow21Estrus),
  156. zap.Any("cowInfo", cowInfo),
  157. zap.Any("cowHabitList", cowHabitList),
  158. zap.Any("pasture", pastureId),
  159. )
  160. newNeckRingEstrus := model.NewNeckRingEstrus(pastureId, cowInfo, level, int32(maxCft), checkResult, isShow)
  161. newNeckRingEstrus.LastTime = lastEstrusDate
  162. newNeckRingEstrus.ActiveTime = activeTime
  163. newNeckRingEstrus.DayHigh = dayHigh
  164. newNeckRingEstrus.MaxHigh = maxHigh
  165. newNeckRingEstrus.IsPeak = pasturePb.IsShow_No
  166. neckRingEstrusList = append(neckRingEstrusList, newNeckRingEstrus)
  167. }
  168. }
  169. zaplog.Info("CowEstrusWarning", zap.Any("neckRingEstrusList", neckRingEstrusList))
  170. if len(neckRingEstrusList) > 0 {
  171. if err := e.DB.Model(new(model.NeckRingEstrus)).
  172. Create(neckRingEstrusList).Error; err != nil {
  173. zaplog.Error("CowEstrusWarningNew", zap.Any("eventEstrusList", neckRingEstrusList), zap.Any("err", err))
  174. }
  175. }
  176. }
  177. // UpdateNewNeckRingEstrus 更新牛只首次发情时间和是否是高峰期
  178. func (e *Entry) UpdateNewNeckRingEstrus(pastureId int64, xToday *XToday, nowTime time.Time) {
  179. e.UpdateEstrusFirstTime1(pastureId)
  180. e.UpdateEstrusFirstTime2(pastureId, xToday)
  181. e.UpdateEstrusFirstTime3(pastureId, nowTime)
  182. e.UpdateEstrusIsPeak(pastureId)
  183. }
  184. // UpdateEstrusFirstTime1 更新牛只首次发情时间
  185. func (e *Entry) UpdateEstrusFirstTime1(pastureId int64) {
  186. // 获取牛只首次发情时间为空的记录
  187. neckRingEstrusList := e.FindNeckRingEstrusByFirstTimeEmpty(pastureId)
  188. zaplog.Info("UpdateEstrusFirstTime1", zap.Any("neckRingEstrusList", neckRingEstrusList))
  189. for _, v := range neckRingEstrusList {
  190. cowEstrusStartData := e.FindCowEstrusFirstTime1(pastureId, v)
  191. zaplog.Info("UpdateEstrusFirstTime1", zap.Any("cowEstrusStartData", cowEstrusStartData))
  192. if cowEstrusStartData != nil && cowEstrusStartData.FirstTime != "" {
  193. if err := e.DB.Model(new(model.NeckRingEstrus)).
  194. Where("id = ?", v.Id).
  195. Update("first_time", cowEstrusStartData.FirstTime).Error; err != nil {
  196. zaplog.Error("UpdateEstrusFirstTime1",
  197. zap.Any("v", v),
  198. zap.Any("err", err),
  199. zap.Any("cowEstrusStartData", cowEstrusStartData),
  200. )
  201. }
  202. }
  203. }
  204. }
  205. func (e *Entry) UpdateEstrusFirstTime2(pastureId int64, xToday *XToday) {
  206. neckRingEstrusList := e.FindNeckRingEstrusByFirstTimeEmpty(pastureId)
  207. for _, v := range neckRingEstrusList {
  208. if v.FirstTime != "" {
  209. continue
  210. }
  211. // 获取牛只最近12小时内的活动记录
  212. activeTime, _ := util.TimeParseLocal(model.LayoutTime, v.ActiveTime)
  213. startTime := activeTime.Add(-12 * time.Hour)
  214. // 查询符合条件的活动记录
  215. var firstTime string
  216. if err := e.DB.Model(new(model.NeckActiveHabit)).
  217. Select("MIN(active_time) as first_time").
  218. Where("pasture_id = ?", pastureId).
  219. Where("cow_id = ?", v.CowId).
  220. Where("active_time BETWEEN ? AND ?", startTime.Format(model.LayoutTime), v.ActiveTime).
  221. Where("cft >= ?", xToday.ActiveLow).
  222. Scan(&firstTime).Error; err != nil {
  223. zaplog.Error("UpdateEstrusFirstTime2", zap.Any("FindFirstTime", err))
  224. continue
  225. }
  226. if firstTime != "" {
  227. if err := e.DB.Model(new(model.NeckRingEstrus)).
  228. Where("id = ?", v.Id).
  229. Update("first_time", firstTime).Error; err != nil {
  230. zaplog.Error("UpdateEstrusFirstTime2", zap.Any("Update", err))
  231. }
  232. }
  233. }
  234. }
  235. func (e *Entry) UpdateEstrusFirstTime3(pastureId int64, xToday time.Time) {
  236. neckRingEstrusList := e.FindNeckRingEstrusByFirstTimeEmpty(pastureId)
  237. for _, v := range neckRingEstrusList {
  238. activeTime, _ := util.TimeParseLocal(model.LayoutTime, v.ActiveTime)
  239. if activeTime.After(xToday.AddDate(0, 0, -2)) {
  240. if err := e.DB.Model(new(model.NeckRingEstrus)).
  241. Where("id = ?", v.Id).
  242. Update("first_time", v.ActiveTime).Error; err != nil {
  243. zaplog.Error("UpdateEstrusFirstTime1", zap.Any("v", v), zap.Any("err", err))
  244. }
  245. }
  246. }
  247. }
  248. func (e *Entry) UpdateEstrusIsPeak(pastureId int64) {
  249. neckRingEstrusList := make([]*model.NeckRingEstrus, 0)
  250. nowTime := time.Now().Local()
  251. firstTime := fmt.Sprintf("%s 00:00:00", nowTime.AddDate(0, 0, -3).Format(model.LayoutDate2))
  252. if err := e.DB.Model(new(model.NeckRingEstrus)).
  253. Where("first_time >= ?", firstTime).
  254. Where("active_time != ?", "").
  255. Where("pasture_id = ?", pastureId).
  256. Find(&neckRingEstrusList).Error; err != nil {
  257. zaplog.Error("UpdateEstrusIsPeak", zap.Any("Find", err))
  258. }
  259. if len(neckRingEstrusList) <= 0 {
  260. return
  261. }
  262. neckRingEstrusFirstMap := make(map[string][]*model.NeckRingEstrus)
  263. for _, v := range neckRingEstrusList {
  264. prefix := fmt.Sprintf("%s_%d", v.FirstTime, v.CowId)
  265. if neckRingEstrusFirstMap[prefix] == nil {
  266. neckRingEstrusFirstMap[prefix] = make([]*model.NeckRingEstrus, 0)
  267. }
  268. neckRingEstrusFirstMap[prefix] = append(neckRingEstrusFirstMap[prefix], v)
  269. }
  270. peakIsShow := make([]int64, 0)
  271. for _, estrusItems := range neckRingEstrusFirstMap {
  272. eLen := len(estrusItems)
  273. if eLen <= 0 {
  274. continue
  275. }
  276. // 倒序排序
  277. sort.Slice(estrusItems, func(i, j int) bool {
  278. return estrusItems[i].ActiveTime < estrusItems[j].ActiveTime
  279. })
  280. // 判断是否是高峰期,和当前时间相比,如果超过2个小就是高峰期
  281. lastItem := estrusItems[eLen-1]
  282. lastActiveTime := util.DateTimeParseLocalUnix2(lastItem.ActiveTime)
  283. sub := nowTime.Sub(lastActiveTime).Hours()
  284. if sub > 4 && lastItem.IsPeak == pasturePb.IsShow_No {
  285. peakIsShow = append(peakIsShow, lastItem.Id)
  286. }
  287. zaplog.Info("UpdateEstrusIsPeak01",
  288. zap.Any("pastureId", pastureId),
  289. zap.Any("estrusItems", estrusItems),
  290. zap.Any("peakIsShow", peakIsShow),
  291. zap.Any("lastActiveTime", lastActiveTime),
  292. zap.Any("sub", sub),
  293. zap.Any("nowTime", nowTime.Format(model.LayoutTime)),
  294. )
  295. }
  296. if len(peakIsShow) > 0 {
  297. if err := e.DB.Model(new(model.NeckRingEstrus)).
  298. Where("id IN ?", peakIsShow).
  299. Where("pasture_id = ?", pastureId).
  300. Update("is_peak", pasturePb.IsShow_Ok).Error; err != nil {
  301. zaplog.Error("UpdateEstrusIsPeak", zap.Any("Update", err))
  302. }
  303. }
  304. }
  305. // FindCowEstrusFirstTime1 查找牛只昨天是否有发情数据
  306. func (e *Entry) FindCowEstrusFirstTime1(pastureId int64, neckRingEstrus *model.NeckRingEstrus) *EstrusStartData {
  307. firstTimeEventEstrus := &EstrusStartData{}
  308. activeAt := util.DateTimeParseLocalUnix2(neckRingEstrus.ActiveTime)
  309. startDate := fmt.Sprintf("%s 00:00:00", activeAt.AddDate(0, 0, -1).Format(model.LayoutDate2))
  310. if err := e.DB.Model(new(model.NeckRingEstrus)).
  311. Select("cow_id,first_time").
  312. Where("active_time BETWEEN ? AND ?", startDate, neckRingEstrus.ActiveTime).
  313. Where("pasture_id = ?", pastureId).
  314. Where("cow_id = ?", neckRingEstrus.CowId).
  315. Where("id != ?", neckRingEstrus.Id).
  316. Order("first_time,id ASC").
  317. First(&firstTimeEventEstrus).Error; err != nil {
  318. return nil
  319. }
  320. return firstTimeEventEstrus
  321. }
  322. func (e *Entry) HistoryNeckRingEstrus(pastureId int64, neckRingNumber string, activeTime string) bool {
  323. var count int64
  324. if err := e.DB.Model(new(model.NeckRingEstrus)).
  325. Where("pasture_id = ?", pastureId).
  326. Where("neck_ring_number = ?", neckRingNumber).
  327. Where("active_time = ?", activeTime).
  328. Count(&count).Error; err != nil {
  329. return false
  330. }
  331. return count > 0
  332. }
  333. // CalculateCFT 计算cft值
  334. func CalculateCFT(habit *model.NeckActiveHabit) (cft float32) {
  335. if habit.ChangeAdjust >= 10 {
  336. cft = (float32(habit.ChangeFilter) - float32(habit.ChangeAdjust) + 3) * float32(habit.FilterCorrect) / 100
  337. } else {
  338. cft = float32(habit.ChangeFilter) * float32(habit.FilterCorrect) / 100
  339. }
  340. switch {
  341. case habit.RuminaFilter > MaxRuminaAdJust:
  342. cft -= float32(5)
  343. case habit.RuminaFilter > 0:
  344. cft -= float32(habit.RuminaFilter) * 0.25
  345. case habit.RuminaFilter < -MaxRuminaAdJust:
  346. cft -= -MaxRuminaAdJust * RumtoHeat
  347. default:
  348. cft -= float32(habit.RuminaFilter) * RumtoHeat
  349. }
  350. return cft
  351. }
  352. // calculateActiveLevel 计算活动量等级
  353. func calculateActiveLevel(cft float32, cowEstrus *CowEstrus, xToday *XToday) pasturePb.EstrusLevel_Kind {
  354. if int32(cft)+cowEstrus.HadJust < xToday.ActiveMiddle {
  355. return pasturePb.EstrusLevel_Low
  356. } else if int32(cft)+cowEstrus.HadJust >= xToday.ActiveHigh {
  357. return pasturePb.EstrusLevel_Middle
  358. } else {
  359. return pasturePb.EstrusLevel_High
  360. }
  361. }
  362. // getResult 根据b3数据计算结果
  363. func getResult(b3 *model.NeckRingEstrus, cft float32, cowEstrus *CowEstrus) pasturePb.CheckResult_Kind {
  364. result := pasturePb.CheckResult_Pending
  365. if b3.CheckResult == pasturePb.CheckResult_Correct {
  366. result = pasturePb.CheckResult_Correct
  367. }
  368. if b3.CheckResult == pasturePb.CheckResult_Fail && b3.DayHigh > int32(cft)+cowEstrus.HadJust {
  369. result = pasturePb.CheckResult_Fail
  370. }
  371. return result
  372. }