neck_ring_estrus.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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()
  55. e.CowEstrusWarning(pastureId, xToday, nowTime)
  56. e.UpdateNewNeckRingEstrus(pastureId, nowTime)
  57. return nil
  58. }
  59. // CowEstrusWarning 发情预警
  60. func (e *Entry) CowEstrusWarning(pastureId int64, xToday *XToday, nowTime time.Time) {
  61. isAlreadIds := make([]int64, 0)
  62. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  63. if err := e.DB.Model(new(model.NeckActiveHabit)).
  64. Where("heat_date <= ?", 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("is_estrus = ?", pasturePb.IsShow_No).
  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. isAlreadIds = append(isAlreadIds, habit.Id)
  78. cft := calculateCFT(habit)
  79. if cft < float32(xToday.ActiveLow-XAdjust21) {
  80. continue
  81. }
  82. zaplog.Info("CowEstrusWarning", zap.Any("cft", cft), zap.Any("habit", habit))
  83. if neckActiveHabitMap[habit.CowId] == nil {
  84. neckActiveHabitMap[habit.CowId] = make([]*model.NeckActiveHabit, 0)
  85. }
  86. neckActiveHabitMap[habit.CowId] = append(neckActiveHabitMap[habit.CowId], habit)
  87. }
  88. neckRingEstrusList := make([]*model.NeckRingEstrus, 0)
  89. for cowId, cowHabitList := range neckActiveHabitMap {
  90. // 最近3天最大发情记录,小于该变化趋势的不再插入
  91. before3Data := e.GetBeforeThreeDaysCowEstrus(cowId, nowTime.AddDate(0, 0, -2).Format(model.LayoutTime))
  92. // 判断最近50天内是否存在发情记录(发情等级>=2),如果18~25天@xadjust21,如果36~50天@xadjust42
  93. cow21Estrus := e.GetTwoEstrus(pastureId, cowId, nowTime.AddDate(0, 0, -100).Format(model.LayoutTime), nowTime.AddDate(0, 0, -2).Format(model.LayoutTime))
  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. cft := calculateCFT(habit)
  108. if cft > maxCft {
  109. maxCft = cft
  110. }
  111. if habit.FilterHigh > maxHigh {
  112. maxHigh = habit.FilterHigh
  113. }
  114. // 获取最新的 CreateTime
  115. activeTimeParse, _ := util.TimeParseLocal(model.LayoutTime, habit.ActiveTime)
  116. if activeTimeParse.After(lastActiveDate) {
  117. lastActiveDate = activeTimeParse
  118. }
  119. }
  120. b48 := float64(0)
  121. if len(before3Data.ActiveTime) > 0 {
  122. t3, _ := util.TimeParseLocal(model.LayoutTime, before3Data.ActiveTime)
  123. b48 = t3.Sub(lastActiveDate).Hours()
  124. }
  125. if (int32(maxCft) > before3Data.DayHigh || before3Data.CowId == 0 || b48 > B48) && int32(maxCft)+cow21Estrus.HadJust > xToday.ActiveLow {
  126. level := calculateActiveLevel(maxCft, cow21Estrus, xToday)
  127. cowInfo, err := e.GetCowById(pastureId, cowId)
  128. if err != nil || cowInfo == nil {
  129. zaplog.Error("CowEstrusWarning", zap.Any("FindCowInfoByCowId", cowId))
  130. continue
  131. }
  132. isShow := pasturePb.IsShow_Ok
  133. if cowInfo != nil && cowInfo.IsPregnant == pasturePb.IsShow_Ok && level == pasturePb.EstrusLevel_Low {
  134. isShow = pasturePb.IsShow_No
  135. }
  136. dayHigh := int32(maxCft) + cow21Estrus.HadJust
  137. lastEstrusDate := cow21Estrus.ActiveDate
  138. checkResult := getResult(before3Data, maxCft, cow21Estrus)
  139. isPeak := pasturePb.IsShow_Ok
  140. activeTime := lastActiveDate.Format(model.LayoutTime)
  141. if e.HistoryNeckRingEstrus(pastureId, cowInfo.NeckRingNumber, activeTime) {
  142. continue
  143. }
  144. zaplog.Info("CowEstrusWarning",
  145. zap.Any("level", level),
  146. zap.Any("b48", b48),
  147. zap.Any("checkResult", checkResult),
  148. zap.Any("isShow", isShow),
  149. zap.Any("isPeak", isPeak),
  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. )
  159. newNeckRingEstrus := model.NewNeckRingEstrus(pastureId, cowInfo, level, int32(maxCft), checkResult, isShow)
  160. newNeckRingEstrus.LastTime = lastEstrusDate
  161. newNeckRingEstrus.ActiveTime = activeTime
  162. newNeckRingEstrus.DayHigh = dayHigh
  163. newNeckRingEstrus.MaxHigh = maxHigh
  164. newNeckRingEstrus.IsPeak = isPeak
  165. neckRingEstrusList = append(neckRingEstrusList, newNeckRingEstrus)
  166. }
  167. }
  168. zaplog.Info("CowEstrusWarning", zap.Any("neckRingEstrusList", neckRingEstrusList))
  169. if len(neckRingEstrusList) > 0 {
  170. if err := e.DB.Model(new(model.NeckRingEstrus)).Create(neckRingEstrusList).Error; err != nil {
  171. zaplog.Error("CowEstrusWarningNew", zap.Any("eventEstrusList", neckRingEstrusList), zap.Any("err", err))
  172. }
  173. }
  174. if len(isAlreadIds) > 0 {
  175. if err := e.DB.Model(new(model.NeckActiveHabit)).
  176. Where("id IN (?)", isAlreadIds).
  177. Update("is_estrus", pasturePb.IsShow_Ok).Error; err != nil {
  178. zaplog.Error("CowEstrusWarning", zap.Any("err", err))
  179. }
  180. }
  181. }
  182. func (e *Entry) UpdateNewNeckRingEstrus(pastureId int64, nowTime time.Time) {
  183. // 更新牛只首次发情时间
  184. e.UpdateEstrusFirstTime1(pastureId, nowTime)
  185. e.UpdateEstrusIsPeak(pastureId, nowTime)
  186. e.UpdateEstrusFirstTime2(pastureId, nowTime)
  187. e.UpdateEstrusFirstTime3(pastureId, nowTime)
  188. }
  189. // UpdateEstrusFirstTime1 更新牛只首次发情时间
  190. func (e *Entry) UpdateEstrusFirstTime1(pastureId int64, xToday time.Time) {
  191. neckRingEstrusList := e.FindNeckRingEstrusByFirstTimeEmpty(pastureId)
  192. for _, v := range neckRingEstrusList {
  193. cowEstrusStartData := e.FindCowEstrusFirstTime1(pastureId, v.CowId, xToday)
  194. if cowEstrusStartData != nil && cowEstrusStartData.FirstTime != "" {
  195. if err := e.DB.Model(new(model.NeckRingEstrus)).
  196. Where("id = ?", v.Id).
  197. Update("first_time", cowEstrusStartData.FirstTime).Error; err != nil {
  198. zaplog.Error("UpdateEstrusFirstTime1",
  199. zap.Any("v", v),
  200. zap.Any("err", err),
  201. zap.Any("cowEstrusStartData", cowEstrusStartData),
  202. )
  203. }
  204. }
  205. }
  206. }
  207. func (e *Entry) UpdateEstrusFirstTime2(pastureId int64, xToday time.Time) {
  208. neckRingEstrusList := e.FindNeckRingEstrusByFirstTimeEmpty(pastureId)
  209. for _, v := range neckRingEstrusList {
  210. zaplog.Info("UpdateEstrusFirstTime2", zap.Any("v", v))
  211. }
  212. }
  213. func (e *Entry) UpdateEstrusFirstTime3(pastureId int64, xToday time.Time) {
  214. neckRingEstrusList := e.FindNeckRingEstrusByFirstTimeEmpty(pastureId)
  215. for _, v := range neckRingEstrusList {
  216. activeTime, _ := util.TimeParseLocal(model.LayoutTime, v.ActiveTime)
  217. if activeTime.After(xToday.AddDate(0, 0, -2)) {
  218. if err := e.DB.Model(new(model.NeckRingEstrus)).
  219. Where("id = ?", v.Id).
  220. Update("first_time", v.ActiveTime).Error; err != nil {
  221. zaplog.Error("UpdateEstrusFirstTime1", zap.Any("v", v), zap.Any("err", err))
  222. }
  223. }
  224. }
  225. }
  226. func (e *Entry) UpdateEstrusIsPeak(pastureId int64, xToday time.Time) {
  227. neckRingEstrusList := make([]*model.NeckRingEstrus, 0)
  228. if err := e.DB.Model(new(model.NeckRingEstrus)).
  229. Where("first_time != ?", "").
  230. Where("is_peak = ?", pasturePb.IsShow_Ok).
  231. Where("is_show = ?", pasturePb.IsShow_Ok).
  232. Where("pasture_id = ?", pastureId).
  233. Find(&neckRingEstrusList).Error; err != nil {
  234. zaplog.Error("UpdateEstrusIsPeak", zap.Any("Find", err))
  235. }
  236. for _, estrus := range neckRingEstrusList {
  237. activeTime, _ := util.TimeParseLocal(model.LayoutTime, estrus.ActiveTime)
  238. if activeTime.Before(xToday) || activeTime.After(xToday.AddDate(0, 0, 1)) {
  239. continue
  240. }
  241. var exists bool
  242. if err := e.DB.Model(new(model.NeckRingEstrus)).
  243. Where("cow_id = ?", estrus.CowId).
  244. Where("first_time != ?", "").
  245. Where("active_time BETWEEN ? AND ?", xToday, xToday.AddDate(0, 0, 1)).
  246. Where("active_time BETWEEN ? AND ?", estrus.FirstTime, activeTime.Add(-2*time.Hour)).
  247. Select("1").
  248. Limit(1).
  249. Scan(&exists).Error; err != nil {
  250. zaplog.Error("UpdateEstrusIsPeak", zap.Any("exists", err))
  251. continue
  252. }
  253. if exists {
  254. if err := e.DB.Model(estrus).
  255. Update("is_peak", pasturePb.IsShow_No).Error; err != nil {
  256. zaplog.Error("UpdateEstrusIsPeak", zap.Any("v", estrus), zap.Any("err", err))
  257. }
  258. }
  259. }
  260. }
  261. // FindCowEstrusFirstTime1 查找牛只昨天是否有发情数据
  262. func (e *Entry) FindCowEstrusFirstTime1(pastureId, cowId int64, xToday time.Time) *EstrusStartData {
  263. firstTimeEventEstrus := &EstrusStartData{}
  264. if err := e.DB.Model(new(model.NeckRingEstrus)).
  265. Select("cow_id,MIN(STR_TO_DATE(first_time, '%Y-%m-%d %H:%i:%s')) as first_time").
  266. Where("active_time BETWEEN ? AND ?",
  267. fmt.Sprintf("%s 00:00:00", xToday.AddDate(0, 0, -1).Format(model.LayoutDate2)),
  268. fmt.Sprintf("%s 23:59:59", xToday.Format(model.LayoutDate2)),
  269. ).Where("pasture_id = ?", pastureId).
  270. Where("cow_id = ?", cowId).
  271. First(&firstTimeEventEstrus).Error; err != nil {
  272. return nil
  273. }
  274. return firstTimeEventEstrus
  275. }
  276. func (e *Entry) HistoryNeckRingEstrus(pastureId int64, neckRingNumber string, activeTime string) bool {
  277. var count int64
  278. if err := e.DB.Model(new(model.NeckRingEstrus)).
  279. Where("pasture_id = ?", pastureId).
  280. Where("neck_ring_number = ?", neckRingNumber).
  281. Where("active_time = ?", activeTime).
  282. Count(&count).Error; err != nil {
  283. return false
  284. }
  285. return count > 0
  286. }
  287. // calculateCFT 计算cft值
  288. func calculateCFT(habit *model.NeckActiveHabit) (cft float32) {
  289. if habit.ChangeAdjust >= 10 {
  290. cft = (float32(habit.ChangeFilter) - float32(habit.ChangeAdjust) + 3) * float32(habit.FilterCorrect) / 100
  291. } else {
  292. cft = float32(habit.ChangeFilter) * float32(habit.FilterCorrect) / 100
  293. }
  294. switch {
  295. case habit.RuminaFilter > MaxRuminaAdJust:
  296. cft -= float32(5)
  297. case habit.RuminaFilter > 0:
  298. cft -= float32(habit.RuminaFilter) * 0.25
  299. case habit.RuminaFilter < -MaxRuminaAdJust:
  300. cft -= -MaxRuminaAdJust * RumtoHeat
  301. default:
  302. cft -= float32(habit.RuminaFilter) * RumtoHeat
  303. }
  304. return cft
  305. }
  306. // calculateActiveLevel 计算活动量等级
  307. func calculateActiveLevel(cft float32, cowEstrus *CowEstrus, xToday *XToday) pasturePb.EstrusLevel_Kind {
  308. if int32(cft)+cowEstrus.HadJust < xToday.ActiveMiddle {
  309. return pasturePb.EstrusLevel_Low
  310. } else if int32(cft)+cowEstrus.HadJust >= xToday.ActiveHigh {
  311. return pasturePb.EstrusLevel_Middle
  312. } else {
  313. return pasturePb.EstrusLevel_High
  314. }
  315. }
  316. // getResult 根据b3数据计算结果
  317. func getResult(b3 *model.NeckRingEstrus, cft float32, cowEstrus *CowEstrus) pasturePb.CheckResult_Kind {
  318. result := pasturePb.CheckResult_Pending
  319. if b3.CheckResult == pasturePb.CheckResult_Correct {
  320. result = pasturePb.CheckResult_Correct
  321. }
  322. if b3.CheckResult == pasturePb.CheckResult_Fail && b3.DayHigh > int32(cft)+cowEstrus.HadJust {
  323. result = pasturePb.CheckResult_Fail
  324. }
  325. return result
  326. }