neck_ring_handle.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. package crontab
  2. import (
  3. "fmt"
  4. "kpt-pasture/model"
  5. "kpt-pasture/util"
  6. "math"
  7. "sort"
  8. "time"
  9. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  10. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  11. "gitee.com/xuyiping_admin/pkg/xerr"
  12. "go.uber.org/zap"
  13. )
  14. const (
  15. MinChangeFilter = -99
  16. MinRuminaFilter = -99
  17. MinChewFilter = -99
  18. MinChangeHigh = -99
  19. DefaultNb = 30
  20. DefaultScore = 100
  21. )
  22. var (
  23. defaultLimit = int32(1000)
  24. isDelete bool
  25. mergeIsRunning bool
  26. calculateIsRunning bool
  27. )
  28. // NeckRingOriginalMergeData 把脖环数据合并成2个小时的
  29. func (e *Entry) NeckRingOriginalMergeData() (err error) {
  30. if mergeIsRunning {
  31. return nil
  32. }
  33. newTime := time.Now()
  34. mergeIsRunning = true
  35. defer func() {
  36. mergeIsRunning = false
  37. if newTime.Day()%15 == 0 && !isDelete {
  38. // 原始数据删除15天前的
  39. e.DB.Model(new(model.NeckRingOriginal)).
  40. Where("created_at < ?", newTime.AddDate(0, 0, -15).Unix()).
  41. Delete(new(model.NeckRingOriginal))
  42. e.DB.Model(new(model.NeckRingProcess)).
  43. Where("created_at < ?", newTime.AddDate(0, 0, -15).Unix()).
  44. Delete(new(model.NeckRingProcess))
  45. // 活动数据删除6个月前的数据
  46. e.DB.Model(new(model.NeckActiveHabit)).
  47. Where("created_at < ?", newTime.AddDate(0, -6, 0).Unix()).
  48. Delete(new(model.NeckActiveHabit))
  49. isDelete = true
  50. }
  51. }()
  52. limit := e.Cfg.NeckRingLimit
  53. if limit <= 0 {
  54. limit = defaultLimit
  55. }
  56. //createdAt := newTime.Add(-1 * time.Hour)
  57. //neckRingNumber := []string{"10026", "10027", "10028", "10029", "10030", "10031", "10032", "10033", "10034", "10035"}
  58. neckRingNumber := []string{"10027"}
  59. neckRingList := make([]*model.NeckRingOriginal, 0)
  60. if err = e.DB.Model(new(model.NeckRingOriginal)).
  61. Where("is_show = ?", pasturePb.IsShow_No).
  62. Where("neck_ring_number IN (?)", neckRingNumber).
  63. //Where("created_at <= ?", createdAt.Unix()).
  64. Order("active_date,frameid,neck_ring_number").
  65. Limit(int(limit)).Find(&neckRingList).Error; err != nil {
  66. return xerr.WithStack(err)
  67. }
  68. if len(neckRingList) <= 0 {
  69. return nil
  70. }
  71. // 计算合并
  72. neckActiveHabitList := e.recalculate(neckRingList)
  73. if len(neckActiveHabitList) <= 0 {
  74. return nil
  75. }
  76. for _, habit := range neckActiveHabitList {
  77. //更新脖环牛只相关信息 新数据直接插入
  78. historyNeckActiveHabit, ct := e.IsExistNeckActiveHabit(habit.NeckRingNumber, habit.HeatDate, habit.Frameid)
  79. if ct <= 0 {
  80. if err = e.DB.Create(habit).Error; err != nil {
  81. zaplog.Info("NeckRingOriginalMergeData-1",
  82. zap.Any("err", err),
  83. zap.Any("neckActiveHabit", habit),
  84. )
  85. }
  86. if err = e.UpdateNeckRingOriginalIsShow(habit); err != nil {
  87. zaplog.Error("NeckRingOriginalMergeData-2",
  88. zap.Any("err", err),
  89. zap.Any("neckActiveHabit", habit),
  90. )
  91. }
  92. continue
  93. }
  94. // 重新计算
  95. newNeckActiveHabit := e.againRecalculate(historyNeckActiveHabit)
  96. if newNeckActiveHabit != nil {
  97. if err = e.DB.Model(new(model.NeckActiveHabit)).
  98. Select("rumina", "intake", "inactive", "gasp", "other", "high", "active", "is_show").
  99. Where("id = ?", historyNeckActiveHabit.Id).
  100. Updates(newNeckActiveHabit).Error; err != nil {
  101. zaplog.Error("NeckRingOriginalMergeData-3",
  102. zap.Any("err", err),
  103. zap.Any("ct", ct),
  104. zap.Any("historyNeckActiveHabit", historyNeckActiveHabit),
  105. zap.Any("newNeckActiveHabit", newNeckActiveHabit),
  106. )
  107. }
  108. }
  109. }
  110. return nil
  111. }
  112. func (e *Entry) NeckRingCalculate() error {
  113. pastureList := e.FindPastureList()
  114. if pastureList == nil || len(pastureList) == 0 {
  115. return nil
  116. }
  117. if calculateIsRunning {
  118. return nil
  119. }
  120. defer func() {
  121. calculateIsRunning = false
  122. }()
  123. calculateIsRunning = true
  124. for _, pasture := range pastureList {
  125. if err := e.EntryUpdateActiveHabit(pasture.Id); err != nil {
  126. zaplog.Error("NeckRingCalculate", zap.Any("err", err), zap.Any("pasture", pasture))
  127. }
  128. zaplog.Info(fmt.Sprintf("NeckRingCalculate Success %d", pasture.Id))
  129. }
  130. return nil
  131. }
  132. // recalculate 合并计算
  133. func (e *Entry) recalculate(neckRingList []*model.NeckRingOriginal) []*model.NeckActiveHabit {
  134. originalMapData := make(map[string]*model.NeckRingOriginalMerge)
  135. // 合并成2个小时的
  136. for _, v := range neckRingList {
  137. xframeId := util.XFrameId(v.Frameid)
  138. mapKey := fmt.Sprintf("%s%s%s%s%d", v.NeckRingNumber, model.JoinKey, v.ActiveDate, model.JoinKey, xframeId) // 0001/2023-12-04/0 0001/2023-12-03/4
  139. if originalMapData[mapKey] == nil {
  140. originalMapData[mapKey] = new(model.NeckRingOriginalMerge)
  141. }
  142. originalMapData[mapKey].IsMageData(v, xframeId)
  143. }
  144. currTime := time.Now()
  145. // 算平均值
  146. for k, v := range originalMapData {
  147. // 过滤掉合并后不满6条数据
  148. if v.RecordCount < 6 {
  149. currMaxXframeId := util.FrameIdMapReverse[int32(currTime.Hour())]
  150. activeDateString := fmt.Sprintf("%s %02d:00:00", v.ActiveDate, v.XframeId*2+1)
  151. activeDate, _ := time.Parse(model.LayoutTime, activeDateString)
  152. if currMaxXframeId-v.XframeId <= 1 && currTime.Add(-1*time.Hour).Unix() < activeDate.Unix() {
  153. delete(originalMapData, k)
  154. }
  155. }
  156. if v.RecordCount > 6 {
  157. zaplog.Error("recalculate", zap.Any("k", k), zap.Any("v", v))
  158. delete(originalMapData, k)
  159. }
  160. v.SumAvg()
  161. }
  162. dataList := model.NeckRingOriginalMap(originalMapData).ForMatData()
  163. sort.Sort(model.NeckActiveHabitSlice(dataList))
  164. return dataList
  165. }
  166. func (e *Entry) againRecalculate(data *model.NeckActiveHabit) *model.NeckActiveHabit {
  167. originalList := make([]*model.NeckRingOriginal, 0)
  168. frameIds := util.FrameIds(data.Frameid)
  169. if err := e.DB.Model(new(model.NeckRingOriginal)).
  170. Where("neck_ring_number = ?", data.NeckRingNumber).
  171. Where("active_date = ?", data.HeatDate).
  172. Where("frameid IN (?)", frameIds).
  173. Find(&originalList).Error; err != nil {
  174. return nil
  175. }
  176. newDataList := e.recalculate(originalList)
  177. if len(newDataList) != 1 {
  178. return nil
  179. }
  180. res := newDataList[0]
  181. if res.Id <= 0 {
  182. return nil
  183. }
  184. res.IsShow = pasturePb.IsShow_No
  185. return res
  186. }
  187. func (e *Entry) EntryUpdateActiveHabit(pastureId int64) (err error) {
  188. // 获取这段执行数据内最大日期和最小日期
  189. xToday := &XToday{}
  190. systemConfigureList, err := e.GetSystemConfigure(pastureId)
  191. if err != nil {
  192. return xerr.WithStack(err)
  193. }
  194. for _, v := range systemConfigureList {
  195. switch v.Name {
  196. case model.MaxHabit:
  197. xToday.LastMaxHabitId = v.Value
  198. case model.High:
  199. xToday.High = int32(v.Value)
  200. case model.Rumina:
  201. xToday.Rumina = int32(v.Value)
  202. case model.XRuminaDisc:
  203. xToday.XRuminaDisc = int32(v.Value)
  204. case model.XChangeDiscount:
  205. xToday.XChangeDiscount = int32(v.Value)
  206. case model.WeeklyActive:
  207. xToday.WeeklyActive = int32(v.Value)
  208. }
  209. }
  210. currMaxHabit := &model.NeckActiveHabit{}
  211. if err = e.DB.Model(new(model.NeckActiveHabit)).
  212. Where("id > ?", xToday.LastMaxHabitId).
  213. Where("pasture_id = ?", pastureId).
  214. Where("is_show = ?", pasturePb.IsShow_No).
  215. Order("id desc").First(currMaxHabit).Error; err != nil {
  216. return xerr.WithStack(err)
  217. }
  218. if currMaxHabit.Id <= 0 || currMaxHabit.Id <= xToday.LastMaxHabitId {
  219. return nil
  220. }
  221. xToday.CurrMaxHabitId = currMaxHabit.Id
  222. defer func() {
  223. // 更新最后一次执行的id值
  224. if err == nil {
  225. e.DB.Model(new(model.SystemConfigure)).
  226. Where("name = ?", model.MaxHabit).
  227. Where("pasture_id = ?", pastureId).
  228. Update("value", currMaxHabit.Id)
  229. }
  230. }()
  231. var processIds []int64
  232. // 更新活动滤波
  233. processIds, err = e.FirstFilterUpdate(pastureId, xToday)
  234. if err != nil {
  235. zaplog.Error("NeckRingCalculate", zap.Any("FirstFilterUpdate", err), zap.Any("xToday", xToday))
  236. }
  237. if len(processIds) > 0 {
  238. if err = e.WeeklyUpdateActiveHabit(pastureId, processIds, xToday); err != nil {
  239. zaplog.Error("NeckRingCalculate", zap.Any("WeeklyUpdateActiveHabit", err), zap.Any("xToday", xToday))
  240. }
  241. // 二次更新滤波
  242. if err = e.SecondUpdateChangeFilter(pastureId, xToday); err != nil {
  243. zaplog.Error("NeckRingCalculate", zap.Any("SecondUpdateChangeFilter", err), zap.Any("xToday", xToday))
  244. }
  245. }
  246. // 活动量校正系数和健康评分
  247. if err = e.FilterCorrectAndScoreUpdate(pastureId, xToday); err != nil {
  248. zaplog.Error("NeckRingCalculate", zap.Any("ActivityVolumeChanges", err), zap.Any("xToday", xToday))
  249. }
  250. if err = e.DB.Model(new(model.NeckActiveHabit)).
  251. Where("id BETWEEN ? AND ?", xToday.LastMaxHabitId, xToday.CurrMaxHabitId).
  252. Where("pasture_id = ?", pastureId).
  253. Where("is_show = ?", pasturePb.IsShow_No).
  254. Where("change_filter = ?", model.InitChangeFilter).
  255. Updates(map[string]interface{}{
  256. "change_filter": model.DefaultChangeFilter,
  257. "rumina_filter": model.DefaultRuminaFilter,
  258. "chew_filter": model.DefaultChewFilter,
  259. }).Error; err != nil {
  260. zaplog.Error("EntryUpdateActiveHabit", zap.Any("change_filter", err), zap.Any("xToday", xToday))
  261. }
  262. if err = e.DB.Model(new(model.NeckActiveHabit)).
  263. Where("id BETWEEN ? AND ?", xToday.LastMaxHabitId, xToday.CurrMaxHabitId).
  264. Where("pasture_id = ?", pastureId).
  265. Where("change_filter < ?", 0).
  266. Where("filter_correct < ?", model.DefaultFilterCorrect).
  267. Updates(map[string]interface{}{
  268. "filter_correct": model.DefaultFilterCorrect,
  269. }).Error; err != nil {
  270. zaplog.Error("EntryUpdateActiveHabit", zap.Any("filter_correct", err), zap.Any("xToday", xToday))
  271. }
  272. // 插入群体校正表
  273. if err = e.UpdateChangeAdJust(pastureId, xToday); err != nil {
  274. zaplog.Error("EntryUpdateActiveHabit", zap.Any("UpdateChangeAdJust", err), zap.Any("xToday", xToday))
  275. }
  276. return nil
  277. }
  278. // FirstFilterUpdate 首次更新活动滤波
  279. func (e *Entry) FirstFilterUpdate(pastureId int64, xToDay *XToday) (processIds []int64, err error) {
  280. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  281. if err = e.DB.Model(new(model.NeckActiveHabit)).
  282. Where("id BETWEEN ? AND ?", xToDay.LastMaxHabitId, xToDay.CurrMaxHabitId).
  283. Where("pasture_id = ?", pastureId).
  284. Where("is_show = ?", pasturePb.IsShow_No).
  285. Where(e.DB.Where("high >= ?", xToDay.High).Or("rumina >= ?", xToDay.Rumina)).
  286. Order("heat_date,neck_ring_number,frameid").
  287. Limit(int(defaultLimit)).Find(&newNeckActiveHabitList).Error; err != nil {
  288. return nil, xerr.WithStack(err)
  289. }
  290. // 活动量滤波
  291. for _, v := range newNeckActiveHabitList {
  292. // 过滤牛只未绑定的脖环的数据
  293. cowInfo := e.GetCowInfoByNeckRingNumber(v.PastureId, v.NeckRingNumber)
  294. if cowInfo == nil || cowInfo.Id <= 0 {
  295. continue
  296. }
  297. frameId := v.Frameid
  298. heatDate := v.HeatDate
  299. if v.Frameid == 0 {
  300. frameId = 11
  301. heatDateParse, _ := time.Parse(model.LayoutDate2, heatDate)
  302. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  303. }
  304. firstFilterData := e.FindFirstFilter(pastureId, v.NeckRingNumber, heatDate, frameId)
  305. if v.FilterHigh > 0 {
  306. firstFilterData.FilterHigh = v.FilterHigh
  307. } else {
  308. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  309. firstFilterData.FilterHigh = int32(computeIfPositiveElse(float64(v.High), float64(firstFilterData.FilterHigh), 0.23, 0.77))
  310. } else {
  311. firstFilterData.FilterHigh = v.High
  312. }
  313. }
  314. if v.FilterRumina > 0 {
  315. firstFilterData.FilterRumina = v.FilterRumina
  316. } else {
  317. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  318. firstFilterData.FilterRumina = int32(computeIfPositiveElse(float64(v.Rumina), float64(firstFilterData.FilterRumina), 0.33, 0.67))
  319. } else {
  320. firstFilterData.FilterRumina = v.Rumina
  321. }
  322. }
  323. if v.FilterChew > 0 {
  324. firstFilterData.FilterChew = v.FilterChew
  325. } else {
  326. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  327. firstFilterData.FilterChew = int32(computeIfPositiveElse(float64(v.Rumina+v.Intake), float64(firstFilterData.FilterChew), 0.33, 0.67))
  328. } else {
  329. firstFilterData.FilterChew = v.Rumina + v.Intake
  330. }
  331. }
  332. processIds = append(processIds, v.Id)
  333. // 更新过滤值
  334. if err = e.DB.Model(new(model.NeckActiveHabit)).
  335. Select(
  336. "filter_high", "filter_rumina", "filter_chew", "cow_id", "lact", "calving_age",
  337. ).Where("id = ?", v.Id).
  338. Updates(map[string]interface{}{
  339. "filter_high": firstFilterData.FilterHigh,
  340. "filter_rumina": firstFilterData.FilterRumina,
  341. "filter_chew": firstFilterData.FilterChew,
  342. "cow_id": cowInfo.Id,
  343. "lact": cowInfo.Lact,
  344. "calving_age": cowInfo.CalvingAge,
  345. }).Error; err != nil {
  346. zaplog.Error("FirstFilterUpdate",
  347. zap.Any("error", err),
  348. zap.Any("firstFilterData", firstFilterData),
  349. zap.Any("NeckActiveHabit", v),
  350. zap.Any("cowInfo", cowInfo),
  351. zap.Any("xToday", xToDay),
  352. )
  353. }
  354. }
  355. return processIds, nil
  356. }
  357. func (e *Entry) WeeklyUpdateActiveHabit(pastureId int64, processIds []int64, xToDay *XToday) (err error) {
  358. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  359. if err = e.DB.Model(new(model.NeckActiveHabit)).
  360. Where("id IN (?)", processIds).
  361. Order("heat_date,neck_ring_number,frameid").
  362. Find(&newNeckActiveHabitList).Error; err != nil {
  363. return xerr.WithStack(err)
  364. }
  365. for _, v := range newNeckActiveHabitList {
  366. // 前七天的
  367. weekHabitData := e.FindWeekHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  368. highDiff := v.FilterHigh - weekHabitData.WeekHighHabit
  369. denominator := float64(v.WeekHigh)*0.6 + float64(weekHabitData.WeekHighHabit)*0.2 + float64(xToDay.WeeklyActive)*0.2
  370. if highDiff > 0 {
  371. v.ChangeHigh = int32(math.Round((float64(highDiff) / denominator) * 100))
  372. } else {
  373. v.ChangeHigh = int32(math.Round(float64(highDiff) / denominator * 100))
  374. }
  375. if weekHabitData.WeekRuminaHabit != 0 {
  376. v.ChangeRumina = int32(math.Round(float64(v.FilterRumina-weekHabitData.WeekRuminaHabit) / float64(weekHabitData.WeekRuminaHabit) * 100))
  377. } else {
  378. v.ChangeRumina = 0
  379. }
  380. if weekHabitData.WeekChewHabit != 0 {
  381. v.ChangeChew = int32(math.Round(float64(v.FilterChew-weekHabitData.WeekChewHabit) / float64(weekHabitData.WeekChewHabit) * 100))
  382. } else {
  383. v.ChangeChew = 0
  384. }
  385. sumHabitData := e.FindSumHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  386. before3DaysNeckActiveHabit := e.FindBefore3DaysNeckActiveHabit(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid)
  387. // 更新过滤值
  388. if err = e.DB.Model(new(model.NeckActiveHabit)).
  389. Select(
  390. "week_high_habit", "week_rumina_habit", "week_chew_habit", "week_intake_habit", "week_inactive_habit",
  391. "sum_rumina", "sum_intake", "sum_inactive", "sum_active", "sum_max_high", "sum_min_high", "sum_min_chew",
  392. "change_high", "change_rumina", "change_chew", "before_three_sum_rumina", "before_three_sum_intake",
  393. ).Where("id = ?", v.Id).
  394. Updates(map[string]interface{}{
  395. "week_high_habit": weekHabitData.WeekHighHabit,
  396. "week_rumina_habit": weekHabitData.WeekRuminaHabit,
  397. "week_chew_habit": weekHabitData.WeekChewHabit,
  398. "week_intake_habit": weekHabitData.WeekIntakeHabit,
  399. "week_inactive_habit": weekHabitData.WeekIntakeHabit,
  400. "sum_rumina": sumHabitData.SumRumina,
  401. "sum_intake": sumHabitData.SumIntake,
  402. "sum_inactive": sumHabitData.SumInactive,
  403. "sum_active": sumHabitData.SumActive,
  404. "sum_max_high": sumHabitData.SumMaxHigh,
  405. "sum_min_high": sumHabitData.SumMinHigh,
  406. "sum_min_chew": sumHabitData.SumMinChew,
  407. "change_high": v.ChangeHigh,
  408. "change_rumina": v.ChangeRumina,
  409. "change_chew": v.ChangeChew,
  410. "before_three_sum_rumina": before3DaysNeckActiveHabit.SumRumina,
  411. "before_three_sum_intake": before3DaysNeckActiveHabit.SumIntake,
  412. }).Error; err != nil {
  413. zaplog.Error("WeeklyUpdateActiveHabit",
  414. zap.Error(err),
  415. zap.Any("NeckActiveHabit", v),
  416. zap.Any("pastureId", pastureId),
  417. )
  418. }
  419. }
  420. return err
  421. }
  422. // SecondUpdateChangeFilter 第二次更新变化趋势滤波
  423. func (e *Entry) SecondUpdateChangeFilter(pastureId int64, xToday *XToday) (err error) {
  424. newChangeFilterList := make([]*ChangeFilterData, 0)
  425. if err = e.DB.Model(new(model.NeckActiveHabit)).
  426. Select("id", "neck_ring_number", "change_high", "change_filter", "rumina_filter", "change_rumina",
  427. "chew_filter", "change_chew", "heat_date", "frameid", "IF(lact = 0, 0.8, 1) as xlc_dis_count").
  428. Where("heat_date >= ?", time.Now().AddDate(0, 0, -2).Format(model.LayoutDate2)).
  429. Where("pasture_id = ?", pastureId).
  430. Where("change_filter = ?", model.InitChangeFilter).
  431. Where("change_high > ?", MinChangeHigh).
  432. Order("neck_ring_number,heat_date,frameid").
  433. Find(&newChangeFilterList).Error; err != nil {
  434. return xerr.WithStack(err)
  435. }
  436. for _, v := range newChangeFilterList {
  437. secondFilterData := &SecondFilterData{}
  438. frameId := v.FrameId
  439. heatDate := v.HeatDate
  440. if v.FrameId == 0 {
  441. frameId = 11
  442. heatDateParse, _ := time.Parse(model.LayoutDate2, heatDate)
  443. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  444. }
  445. if err = e.DB.Model(new(model.NeckActiveHabit)).
  446. Select("neck_ring_number", "filter_high", "filter_rumina", "filter_chew").
  447. Where("neck_ring_number = ?", v.NeckRingNumber).
  448. Where("heat_date = ?", heatDate).
  449. Where("frameid = ?", frameId).
  450. First(&secondFilterData).Error; err != nil {
  451. zaplog.Error("EntryUpdateActiveHabit", zap.Any("FirstFilterUpdate", err))
  452. }
  453. if v.ChangeFilter > MinChangeFilter {
  454. secondFilterData.ChangeFilter = float64(v.ChangeFilter)
  455. } else {
  456. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  457. secondFilterData.ChangeFilter = secondFilterData.ChangeFilter*(1-(float64(xToday.XChangeDiscount)/10)*v.XlcDisCount) +
  458. math.Min(float64(v.ChangeHigh), secondFilterData.ChangeFilter+135)*(float64(xToday.XChangeDiscount)/10)*v.XlcDisCount
  459. } else {
  460. secondFilterData.ChangeFilter = 0
  461. }
  462. }
  463. if v.RuminaFilter > MinRuminaFilter {
  464. secondFilterData.RuminaFilter = float64(v.ChangeFilter)
  465. } else {
  466. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  467. discount := float64(xToday.XRuminaDisc) / 10 * v.XlcDisCount
  468. if math.Abs(float64(v.ChangeRumina)) > 60 {
  469. discount *= 0.5
  470. }
  471. secondFilterData.RuminaFilter = secondFilterData.RuminaFilter*(1-discount) + float64(v.ChangeRumina)*discount
  472. } else {
  473. secondFilterData.RuminaFilter = 0
  474. }
  475. }
  476. secondFilterData.RuminaFilter = math.Min(50, secondFilterData.RuminaFilter)
  477. if v.ChewFilter > MinChewFilter {
  478. secondFilterData.ChewFilter = float64(v.ChangeChew)
  479. } else {
  480. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  481. discount := float64(xToday.XRuminaDisc) / 10
  482. if math.Abs(float64(v.ChangeChew)) > 60 {
  483. discount *= 0.5
  484. }
  485. secondFilterData.ChewFilter = secondFilterData.ChewFilter*(1-discount) + float64(v.ChangeChew)*discount
  486. } else {
  487. secondFilterData.ChewFilter = 0
  488. }
  489. }
  490. secondFilterData.ChewFilter = math.Min(50, secondFilterData.ChewFilter)
  491. if err = e.DB.Model(new(model.NeckActiveHabit)).
  492. Select("change_filter", "rumina_filter", "chew_filter").
  493. Where("id = ?", v.Id).
  494. Updates(map[string]interface{}{
  495. "change_filter": secondFilterData.ChangeFilter,
  496. "rumina_filter": secondFilterData.RuminaFilter,
  497. "chew_filter": secondFilterData.ChewFilter,
  498. }).Error; err != nil {
  499. zaplog.Error("SecondUpdateChangeFilter-1", zap.Any("error", err), zap.Any("xToday", xToday))
  500. }
  501. }
  502. return nil
  503. }
  504. // FilterCorrectAndScoreUpdate 计算活动量变化趋势校正值(活跃度校正)和健康评分
  505. func (e *Entry) FilterCorrectAndScoreUpdate(pastureId int64, xToday *XToday) error {
  506. beginDayDate := time.Now()
  507. before7DayDate := beginDayDate.AddDate(0, 0, -7).Format(model.LayoutDate2)
  508. before1DayDate := beginDayDate.AddDate(0, 0, -1).Format(model.LayoutDate2)
  509. activityVolumeList := make([]*ActivityVolume, 0)
  510. activityVolumeMap := make(map[string]*ActivityVolume)
  511. if err := e.DB.Model(new(model.NeckActiveHabit)).
  512. Select("neck_ring_number", "AVG(IF(change_filter>=60, 60, change_filter)) as avg_filter",
  513. "ROUND(STD(IF(change_filter>=60, 60, change_filter))) as std_filter", "COUNT(1) as nb").
  514. Where("heat_date BETWEEN ? AND ?", before7DayDate, before1DayDate).
  515. Where("pasture_id = ?", pastureId).
  516. Where(e.DB.Where("high > ?", xToday.High).Or("rumina >= ?", xToday.Rumina)).
  517. Where("active_time <= ?", beginDayDate.Add(-12*time.Hour).Format(model.LayoutTime)).
  518. Where("change_filter > ?", MinChangeFilter).
  519. Having("nb > ?", DefaultNb).
  520. Group("neck_ring_number").
  521. Find(&activityVolumeList).Error; err != nil {
  522. zaplog.Error("ActivityVolumeChanges-0", zap.Any("error", err), zap.Any("xToday", xToday))
  523. }
  524. if len(activityVolumeList) > 0 {
  525. for _, v := range activityVolumeList {
  526. activityVolumeMap[v.NeckRingNumber] = v
  527. }
  528. }
  529. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  530. if err := e.DB.Model(new(model.NeckActiveHabit)).
  531. Where("id <= ?", xToday.CurrMaxHabitId).
  532. Where("heat_date >= ?", before1DayDate).
  533. Where("pasture_id = ?", pastureId).
  534. Where(e.DB.Where("high > ?", xToday.High).Or("rumina > ?", xToday.Rumina)).
  535. Find(&neckActiveHabitList).Error; err != nil {
  536. zaplog.Error("ActivityVolumeChanges-1", zap.Any("error", err), zap.Any("xToday", xToday))
  537. return xerr.WithStack(err)
  538. }
  539. for _, v := range neckActiveHabitList {
  540. if filterCorrectMap, ok := activityVolumeMap[v.NeckRingNumber]; ok {
  541. filterCorrect := model.DefaultFilterCorrect - int(math.Floor(filterCorrectMap.AvgFilter/3+float64(filterCorrectMap.StdFilter)/2))
  542. // 活动量校正系数
  543. if err := e.DB.Model(new(model.NeckActiveHabit)).
  544. Where("id = ?", v.Id).
  545. Where("neck_ring_number = ?", v.NeckRingNumber).
  546. Update("filter_correct", filterCorrect).Error; err != nil {
  547. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  548. continue
  549. }
  550. }
  551. cowScore := calculateScore(v)
  552. if err := e.DB.Model(new(model.NeckActiveHabit)).
  553. Where("id = ?", v.Id).
  554. Update("score", cowScore).Error; err != nil {
  555. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  556. continue
  557. }
  558. }
  559. return nil
  560. }
  561. // UpdateChangeAdJust 更新群体校正数据
  562. func (e *Entry) UpdateChangeAdJust(pastureId int64, xToday *XToday) error {
  563. res := make([]*model.NeckRingBarChange, 0)
  564. oneDayAgo := time.Now().AddDate(0, 0, -1).Format(model.LayoutDate2)
  565. if err := e.DB.Table(fmt.Sprintf("%s as h", new(model.NeckActiveHabit).TableName())).
  566. Select("h.neck_ring_number,h.heat_date, h.frameid, c.pen_id, c.pen_name, COUNT(*) as nb, ROUND(AVG(h.change_high)) as change_high, ROUND(AVG(h.change_filter)) as change_filter").
  567. Joins("JOIN cow as c ON h.neck_ring_number = c.neck_ring_number").
  568. Where("h.pasture_id = ?", pastureId).
  569. Where("h.heat_date >= ?", oneDayAgo).
  570. Where("h.cow_id >= ?", 0).
  571. Group("h.heat_date, h.frameid, c.pen_id").
  572. Order("h.heat_date, h.frameid, c.pen_name").
  573. Find(&res).Error; err != nil {
  574. return xerr.WithStack(err)
  575. }
  576. for _, v := range res {
  577. if err := e.DB.Model(new(model.NeckActiveHabit)).
  578. Where("id > ?", xToday.LastMaxHabitId).
  579. Where("heat_date = ?", v.HeatDate).
  580. Where("frameid = ?", v.FrameId).
  581. Where("neck_ring_number = ?", v.NeckRingNumber).
  582. Update("change_adjust", v.ChangeHigh).Error; err != nil {
  583. zaplog.Error("UpdateChangeAdJust-1", zap.Any("error", err), zap.Any("xToday", xToday))
  584. }
  585. }
  586. // 更新所有的显示状态为否的记录为是
  587. if err := e.DB.Model(new(model.NeckActiveHabit)).
  588. Where("id BETWEEN ? AND ?", xToday.LastMaxHabitId, xToday.CurrMaxHabitId).
  589. Where("pasture_id = ?", pastureId).
  590. Where("is_show = ?", pasturePb.IsShow_No).
  591. Update("is_show = ?", pasturePb.IsShow_Ok).Error; err != nil {
  592. zaplog.Error("UpdateChangeAdJust-2", zap.Any("error", err), zap.Any("xToday", xToday))
  593. }
  594. return nil
  595. }
  596. func (e *Entry) UpdateNeckRingOriginalIsShow(neckRingList *model.NeckActiveHabit) error {
  597. if err := e.DB.Model(new(model.NeckRingOriginal)).
  598. Where("neck_ring_number = ?", neckRingList.NeckRingNumber).
  599. Where("active_date = ?", neckRingList.HeatDate).
  600. Where("frameid IN (?)", util.FrameIds(neckRingList.Frameid)).
  601. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  602. return xerr.WithStack(err)
  603. }
  604. return nil
  605. }
  606. // computeIfPositiveElse 辅助函数来计算过滤值
  607. func computeIfPositiveElse(newValue, prevFilterValue float64, weightPrev, weightNew float64) float64 {
  608. return math.Ceil((prevFilterValue * weightPrev) + (weightNew * newValue))
  609. }
  610. // 计算 score 的逻辑
  611. func calculateScore(habit *model.NeckActiveHabit) int {
  612. // 第一部分逻辑
  613. var part1 float64
  614. switch {
  615. case (habit.CalvingAge <= 1 && habit.Lact >= 1) ||
  616. (habit.CalvingAge >= 2 && habit.CalvingAge <= 13 && (habit.SumRumina+habit.SumIntake) == 0) ||
  617. ((habit.Lact == 0 || habit.CalvingAge >= 14) && habit.ChangeFilter == -99):
  618. part1 = -199
  619. case habit.CalvingAge >= 2 && habit.CalvingAge <= 13:
  620. part1 = math.Min((float64(habit.SumRumina+habit.SumIntake)-(100+math.Min(7, float64(habit.CalvingAge))*60))/10*2, 0)
  621. case habit.ChangeFilter > -99:
  622. part1 = math.Min(0, math.Min(getValueOrDefault(float64(habit.ChangeFilter), 0), getValueOrDefault(float64(habit.SumMinHigh), 0)))*0.2 +
  623. math.Min(0, math.Min(getValueOrDefault(float64(habit.ChangeFilter), 0), getValueOrDefault(float64(habit.SumMinChew), 0)))*0.2 +
  624. getRuminaSumIntakeSumScore(float64(habit.SumRumina+habit.SumIntake)) + getAdditionalScore(habit)
  625. default:
  626. part1 = -299
  627. }
  628. // 第二部分逻辑
  629. var part2 float64
  630. switch {
  631. case habit.FirmwareVersion%100 >= 52:
  632. part2 = 1
  633. case habit.FirmwareVersion%100 >= 30 && habit.FirmwareVersion%100 <= 43:
  634. part2 = 0.8
  635. default:
  636. part2 = 0.6
  637. }
  638. // 最终 score
  639. return DefaultScore + int(math.Floor(part1*part2))
  640. }
  641. // 获取值或默认值
  642. func getValueOrDefault(value, defaultValue float64) float64 {
  643. if value > -99 {
  644. return value
  645. }
  646. return defaultValue
  647. }
  648. // 计算累计反刍得分
  649. func getRuminaSumIntakeSumScore(sum float64) float64 {
  650. switch {
  651. case sum < 80:
  652. return -30
  653. case sum < 180:
  654. return -20
  655. case sum < 280:
  656. return -10
  657. default:
  658. return 0
  659. }
  660. }
  661. // 计算额外得分
  662. func getAdditionalScore(habit *model.NeckActiveHabit) float64 {
  663. var score float64
  664. if (habit.SumRumina+habit.SumIntake < 280 || habit.SumMinHigh+habit.SumMinChew < -50) && habit.SumMaxHigh > 50 {
  665. score += 10
  666. }
  667. if habit.ChangeFilter < -30 && habit.ChangeFilter <= habit.SumMinHigh && habit.ChewFilter < -30 && habit.ChewFilter <= habit.SumMinChew {
  668. score -= 5
  669. }
  670. return score
  671. }