neck_ring_estrus.go 14 KB

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