neck_ring_calculate.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. package crontab
  2. import (
  3. "fmt"
  4. "kpt-pasture/model"
  5. "kpt-pasture/util"
  6. "math"
  7. "strconv"
  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. func (e *Entry) NeckRingCalculate() 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.EntryUpdateActiveHabit(pasture.Id); err != nil {
  21. zaplog.Error("NeckRingCalculate", zap.Any("err", err), zap.Any("pasture", pasture))
  22. }
  23. zaplog.Info(fmt.Sprintf("NeckRingCalculate Success %d", pasture.Id))
  24. }
  25. return nil
  26. }
  27. func (e *Entry) EntryUpdateActiveHabit(pastureId int64) (err error) {
  28. // 获取这段执行数据内最大日期和最小日期
  29. xToday, err := e.XToday(pastureId)
  30. if err != nil {
  31. return xerr.WithStack(err)
  32. }
  33. // 未配置的滤波数据不参与计算
  34. if xToday == nil {
  35. return nil
  36. }
  37. var processIds []int64
  38. // 更新活动滤波
  39. processIds, err = e.FirstFilterUpdate(pastureId, xToday)
  40. if err != nil {
  41. zaplog.Error("NeckRingCalculate", zap.Any("pastureId", pastureId), zap.Any("FirstFilterUpdate", err), zap.Any("xToday", xToday))
  42. }
  43. if len(processIds) <= 0 {
  44. return nil
  45. }
  46. e.WeeklyUpdateActiveHabit(pastureId, processIds, xToday)
  47. // 二次更新滤波
  48. e.SecondUpdateChangeFilter(pastureId, processIds, xToday)
  49. // 活动量校正系数和健康评分
  50. e.FilterCorrectAndScoreUpdate(pastureId, processIds, xToday)
  51. // 更新 ChangeFilter
  52. e.UpdateChangeFilter(pastureId, processIds)
  53. // 更新 FilterCorrect
  54. e.UpdateFilterCorrect(pastureId, processIds)
  55. // 插入群体校正表
  56. e.UpdateChangeAdJust(pastureId, processIds)
  57. // 更新 Cft
  58. e.UpdateCft(pastureId, processIds)
  59. // 更新所有的显示状态为否的记录为是
  60. e.UpdateIsShow(pastureId, processIds)
  61. // 健康预警
  62. e.HealthWarning(pastureId, processIds)
  63. return nil
  64. }
  65. // FirstFilterUpdate 首次更新活动滤波
  66. func (e *Entry) FirstFilterUpdate(pastureId int64, xToDay *XToday) (processIds []int64, err error) {
  67. limit := e.Cfg.NeckRingLimit
  68. if limit <= 0 {
  69. limit = defaultLimit
  70. }
  71. firstHeatDate := time.Now().Local().AddDate(0, 0, int(xToDay.BeforeDayNeckRing)*-1).Format(model.LayoutDate2)
  72. querySql := `SELECT * FROM neck_active_habit WHERE pasture_id = ? AND is_show = ? AND heat_date >= ? AND high >= ?
  73. UNION
  74. SELECT * FROM neck_active_habit WHERE pasture_id = ? AND is_show = ? AND heat_date >= ? AND rumina >= ?
  75. ORDER BY active_time,neck_ring_number,frameid LIMIT ?`
  76. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  77. if err = e.DB.Raw(
  78. querySql,
  79. pastureId, pasturePb.IsShow_No, firstHeatDate, xToDay.High,
  80. pastureId, pasturePb.IsShow_No, firstHeatDate, xToDay.Rumina,
  81. limit,
  82. ).Find(&newNeckActiveHabitList).Error; err != nil {
  83. return nil, xerr.WithStack(err)
  84. }
  85. // 活动量滤波
  86. for _, v := range newNeckActiveHabitList {
  87. // 4小时数据不全的不参与滤波
  88. activeTime, _ := util.TimeParseLocal(model.LayoutTime, v.ActiveTime)
  89. if v.RecordCount != model.DefaultRecordCount && time.Now().Local().Sub(activeTime).Hours() <= 4 {
  90. continue
  91. }
  92. // 过滤牛只未绑定的脖环的数据
  93. cowInfo := e.GetCowInfoByNeckRingNumber(v.PastureId, v.NeckRingNumber)
  94. if cowInfo == nil || cowInfo.Id <= 0 {
  95. v.UpdateIsShowOk()
  96. if err = e.DB.Model(new(model.NeckActiveHabit)).
  97. Select("is_show").
  98. Where("id = ?", v.Id).
  99. Updates(v).Error; err != nil {
  100. zaplog.Error("EntryUpdateActiveHabit", zap.Any("error", err))
  101. }
  102. continue
  103. }
  104. frameId := v.Frameid
  105. heatDate := v.HeatDate
  106. if v.Frameid == 0 {
  107. frameId = 11
  108. heatDateParse, _ := util.TimeParseLocal(model.LayoutDate2, heatDate)
  109. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  110. } else {
  111. frameId -= 1
  112. }
  113. firstFilterData := e.FindFilterData(pastureId, v.NeckRingNumber, heatDate, frameId)
  114. if v.FilterHigh > 0 {
  115. firstFilterData.FilterHigh = v.FilterHigh
  116. } else {
  117. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  118. firstFilterData.FilterHigh = int32(computeIfPositiveElse(float64(v.High), float64(firstFilterData.FilterHigh), 0.23, 0.77))
  119. } else {
  120. firstFilterData.FilterHigh = v.High
  121. }
  122. }
  123. if v.FilterRumina > 0 {
  124. firstFilterData.FilterRumina = v.FilterRumina
  125. } else {
  126. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  127. firstFilterData.FilterRumina = int32(computeIfPositiveElse(float64(v.Rumina), float64(firstFilterData.FilterRumina), 0.33, 0.67))
  128. } else {
  129. firstFilterData.FilterRumina = v.Rumina
  130. }
  131. }
  132. if v.FilterChew > 0 {
  133. firstFilterData.FilterChew = v.FilterChew
  134. } else {
  135. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  136. firstFilterData.FilterChew = int32(computeIfPositiveElse(float64(v.Rumina+v.Intake), float64(firstFilterData.FilterChew), 0.33, 0.67))
  137. } else {
  138. firstFilterData.FilterChew = v.Rumina + v.Intake
  139. }
  140. }
  141. cowWeeklyActive := cowInfo.WeeklyActive
  142. if cowWeeklyActive <= 0 {
  143. cowWeeklyActive = v.WeekHigh
  144. }
  145. processIds = append(processIds, v.Id)
  146. // 更新过滤值
  147. if err = e.DB.Model(new(model.NeckActiveHabit)).
  148. Select("filter_high", "filter_rumina", "filter_chew", "cow_id", "lact", "calving_age", "ear_number", "pen_id", "week_high").
  149. Where("id = ?", v.Id).
  150. Updates(map[string]interface{}{
  151. "filter_high": firstFilterData.FilterHigh,
  152. "filter_rumina": firstFilterData.FilterRumina,
  153. "filter_chew": firstFilterData.FilterChew,
  154. "cow_id": cowInfo.Id,
  155. "lact": cowInfo.Lact,
  156. "calving_age": cowInfo.CalvingAge,
  157. "ear_number": cowInfo.EarNumber,
  158. "pen_id": cowInfo.PenId,
  159. "week_high": cowWeeklyActive,
  160. }).Error; err != nil {
  161. zaplog.Error("FirstFilterUpdate",
  162. zap.Any("error", err),
  163. zap.Any("firstFilterData", firstFilterData),
  164. zap.Any("NeckActiveHabit", v),
  165. zap.Any("cowInfo", cowInfo),
  166. zap.Any("xToday", xToDay),
  167. )
  168. }
  169. }
  170. return processIds, nil
  171. }
  172. // SecondUpdateChangeFilter 第二次更新变化趋势滤波
  173. func (e *Entry) SecondUpdateChangeFilter(pastureId int64, processIds []int64, xToday *XToday) {
  174. newChangeFilterList := make([]*ChangeFilterData, 0)
  175. if err := e.DB.Model(new(model.NeckActiveHabit)).
  176. Select("id", "neck_ring_number", "change_high", "change_filter", "rumina_filter", "change_rumina",
  177. "chew_filter", "change_chew", "heat_date", "frameid", "IF(lact = 0, 0.8, 1) as xlc_dis_count").
  178. Where("pasture_id = ?", pastureId).
  179. Where("id IN (?)", processIds).
  180. Where("change_filter = ?", model.InitChangeFilter).
  181. Where("change_high > ?", MinChangeHigh).
  182. Order("neck_ring_number,heat_date,frameid").
  183. Find(&newChangeFilterList).Error; err != nil {
  184. zaplog.Error("SecondUpdateChangeFilter", zap.Any("error", err))
  185. return
  186. }
  187. for _, v := range newChangeFilterList {
  188. frameId := v.Frameid
  189. heatDate := v.HeatDate
  190. if v.Frameid == 0 {
  191. frameId = 11
  192. heatDateParse, _ := util.TimeParseLocal(model.LayoutDate2, heatDate)
  193. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  194. } else {
  195. frameId -= 1
  196. }
  197. xChangeDiscount := float64(xToday.XChangeDiscount) / 10
  198. xRuminaDisc := float64(xToday.XRuminaDisc) / 10
  199. secondFilterData := e.FindFilterData(pastureId, v.NeckRingNumber, heatDate, frameId)
  200. if secondFilterData.ChangeFilter <= MinChangeFilter {
  201. secondFilterData.ChangeFilter = 0
  202. }
  203. if secondFilterData.RuminaFilter <= MinRuminaFilter {
  204. secondFilterData.RuminaFilter = 0
  205. }
  206. if secondFilterData.ChewFilter <= MinChewFilter {
  207. secondFilterData.ChewFilter = 0
  208. }
  209. changeFilter := float64(v.ChangeFilter)
  210. if v.ChangeFilter <= MinChangeFilter {
  211. changeFilter = float64(secondFilterData.ChangeFilter)*(1-xChangeDiscount*v.XlcDisCount) +
  212. math.Min(float64(v.ChangeHigh), float64(secondFilterData.ChangeFilter)+135)*xChangeDiscount*v.XlcDisCount
  213. }
  214. ruminaFilter := float64(v.RuminaFilter)
  215. discount := xRuminaDisc * v.XlcDisCount
  216. if math.Abs(float64(v.ChangeRumina)) > 60 {
  217. discount *= 0.5
  218. }
  219. ruminaFilter = float64(secondFilterData.RuminaFilter)*(1-discount) + float64(v.ChangeRumina)*discount
  220. if ruminaFilter > 50 {
  221. ruminaFilter = 50
  222. }
  223. chewFilter := float64(v.ChewFilter)
  224. chewFilterDiscount := float64(1)
  225. if math.Abs(float64(v.ChangeChew)) > 60 {
  226. chewFilterDiscount = 0.5
  227. }
  228. chewFilter = float64(secondFilterData.ChewFilter)*(1-xRuminaDisc*chewFilterDiscount) +
  229. float64(v.ChangeChew)*xRuminaDisc*chewFilterDiscount
  230. if chewFilter > 50 {
  231. chewFilter = 50
  232. }
  233. zaplog.Info("SecondUpdateChangeFilter",
  234. zap.Any("NeckActiveHabit", v),
  235. zap.Any("discount", discount),
  236. zap.Any("xChangeDiscount", xChangeDiscount),
  237. zap.Any("xRuminaDisc", xRuminaDisc),
  238. zap.Any("chewFilterDiscount", chewFilterDiscount),
  239. zap.Any("secondFilterData", secondFilterData),
  240. zap.Any("changeFilter", changeFilter),
  241. zap.Any("ruminaFilter", ruminaFilter),
  242. zap.Any("chewFilter", chewFilter),
  243. )
  244. if err := e.DB.Model(new(model.NeckActiveHabit)).
  245. Select("change_filter", "rumina_filter", "chew_filter").
  246. Where("id = ?", v.Id).
  247. Updates(map[string]interface{}{
  248. "change_filter": int32(changeFilter),
  249. "rumina_filter": int32(ruminaFilter),
  250. "chew_filter": int32(chewFilter),
  251. }).Error; err != nil {
  252. zaplog.Error("SecondUpdateChangeFilter", zap.Any("error", err), zap.Any("secondFilterData", secondFilterData))
  253. }
  254. }
  255. }
  256. // FilterCorrectAndScoreUpdate 计算活动量变化趋势校正值(活跃度校正)和健康评分
  257. func (e *Entry) FilterCorrectAndScoreUpdate(pastureId int64, processIds []int64, xToday *XToday) {
  258. beginDayDate := time.Now().Local()
  259. before7DayDate := beginDayDate.AddDate(0, 0, -7).Format(model.LayoutDate2)
  260. before1DayDate := beginDayDate.AddDate(0, 0, -1).Format(model.LayoutDate2)
  261. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  262. if err := e.DB.Model(new(model.NeckActiveHabit)).
  263. Where("id IN (?)", processIds).
  264. Where("pasture_id = ?", pastureId).
  265. Find(&neckActiveHabitList).Error; err != nil {
  266. zaplog.Error("ActivityVolumeChanges-1", zap.Any("error", err), zap.Any("xToday", xToday))
  267. return
  268. }
  269. for _, v := range neckActiveHabitList {
  270. cowScore := calculateScore(v)
  271. if err := e.DB.Model(new(model.NeckActiveHabit)).
  272. Where("id = ?", v.Id).
  273. Update("score", cowScore).Error; err != nil {
  274. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  275. }
  276. activityVolume := &ActivityVolume{}
  277. if err := e.DB.Model(new(model.NeckActiveHabit)).
  278. Select("neck_ring_number", "AVG(IF(change_filter>=60, 60, change_filter)) as avg_filter",
  279. "ROUND(STD(IF(change_filter>=60, 60, change_filter))) as std_filter", "COUNT(1) as nb").
  280. Where("heat_date BETWEEN ? AND ?", before7DayDate, before1DayDate).
  281. Where("pasture_id = ?", pastureId).
  282. Where(e.DB.Where("high > ?", 12).Or("rumina >= ?", xToday.Rumina)).
  283. Where("active_time <= ?", beginDayDate.Add(-12*time.Hour).Format(model.LayoutTime)).
  284. Where("change_filter > ?", MinChangeFilter).
  285. Where("neck_ring_number = ?", v.NeckRingNumber).
  286. Having("nb >= ?", DefaultNb).
  287. First(&activityVolume).Error; err != nil {
  288. zaplog.Error("ActivityVolumeChanges-0", zap.Any("error", err), zap.Any("xToday", xToday), zap.Any("v", v))
  289. continue
  290. }
  291. if activityVolume != nil && activityVolume.NeckRingNumber != "" {
  292. filterCorrect := model.DefaultFilterCorrect - int(math.Round(activityVolume.AvgFilter/3+float64(int(math.Round(activityVolume.StdFilter))/2)))
  293. // 活动量校正系数
  294. if err := e.DB.Model(new(model.NeckActiveHabit)).
  295. Where("id = ?", v.Id).
  296. Update("filter_correct", filterCorrect).Error; err != nil {
  297. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  298. continue
  299. }
  300. }
  301. }
  302. }
  303. func (e *Entry) UpdateChangeFilter(pastureId int64, processIds []int64) {
  304. if err := e.DB.Model(new(model.NeckActiveHabit)).
  305. Where("id IN (?)", processIds).
  306. Where("pasture_id = ?", pastureId).
  307. Where("is_show = ?", pasturePb.IsShow_No).
  308. Where("change_filter = ?", model.InitChangeFilter).
  309. Updates(map[string]interface{}{
  310. "change_filter": model.DefaultChangeFilter,
  311. "rumina_filter": model.DefaultRuminaFilter,
  312. "chew_filter": model.DefaultChewFilter,
  313. }).Error; err != nil {
  314. zaplog.Error("UpdateChangeFilter", zap.Any("change_filter", err))
  315. }
  316. }
  317. func (e *Entry) UpdateFilterCorrect(pastureId int64, processIds []int64) {
  318. if err := e.DB.Model(new(model.NeckActiveHabit)).
  319. Where("id IN (?)", processIds).
  320. Where("pasture_id = ?", pastureId).
  321. Where("change_filter < ?", 0).
  322. Where("filter_correct < ?", model.DefaultFilterCorrect).
  323. Updates(map[string]interface{}{
  324. "filter_correct": model.DefaultFilterCorrect,
  325. }).Error; err != nil {
  326. zaplog.Error("UpdateFilterCorrect", zap.Any("filter_correct", err))
  327. }
  328. }
  329. // UpdateChangeAdJust 更新群体校正数据
  330. func (e *Entry) UpdateChangeAdJust(pastureId int64, processIds []int64) {
  331. neckRingPenChangeList := make([]*model.NeckRingPenChange, 0)
  332. yesterday := time.Now().Local().AddDate(0, 0, -1).Format(model.LayoutDate2)
  333. if err := e.DB.Model(new(model.NeckActiveHabit)).
  334. Select(`heat_date,frameid,pen_id,COUNT(*) AS cow_count,ROUND(AVG(change_high)) AS change_high,ROUND(AVG(change_filter)) AS change_filter`).
  335. Where("pasture_id = ?", pastureId).
  336. Where("heat_date >= ?", yesterday).
  337. Where("cow_id > ?", 0).
  338. Where("pen_id > ?", 0).
  339. Group("heat_date,frameid,pen_id").
  340. Order("heat_date,frameid,pen_id").
  341. Find(&neckRingPenChangeList).Error; err != nil {
  342. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("pastureId", pastureId))
  343. }
  344. for _, v := range neckRingPenChangeList {
  345. var count int64
  346. if err := e.DB.Model(new(model.NeckRingPenChange)).
  347. Where("pasture_id = ?", pastureId).
  348. Where("heat_date = ?", v.HeatDate).
  349. Where("frameid = ?", v.Frameid).
  350. Where("pen_id = ?", v.PenId).
  351. Count(&count).Error; err != nil {
  352. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("v", v), zap.Any("pastureId", pastureId))
  353. }
  354. // 有就更新,没有就新增
  355. if count > 0 {
  356. if err := e.DB.Model(new(model.NeckRingPenChange)).
  357. Where("pasture_id = ?", pastureId).
  358. Where("heat_date = ?", v.HeatDate).
  359. Where("frameid = ?", v.Frameid).
  360. Where("pen_id = ?", v.PenId).
  361. Updates(map[string]interface{}{
  362. "cow_count": v.CowCount,
  363. "change_high": v.ChangeHigh,
  364. "change_filter": v.ChangeFilter,
  365. }).Error; err != nil {
  366. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("v", v), zap.Any("pastureId", pastureId))
  367. }
  368. } else {
  369. neckRingPenChange := model.NewNeckRingPenChange(pastureId, v.HeatDate, v.CowCount, v.Frameid, v.PenId, v.ChangeHigh, v.ChangeFilter)
  370. if err := e.DB.Model(new(model.NeckRingPenChange)).
  371. Create(neckRingPenChange).Error; err != nil {
  372. zaplog.Error("UpdateChangeAdJust",
  373. zap.Any("error", err),
  374. zap.Any("neckRingPenChange", neckRingPenChange),
  375. zap.Any("pastureId", pastureId),
  376. )
  377. }
  378. }
  379. }
  380. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  381. if err := e.DB.Model(new(model.NeckActiveHabit)).
  382. Where("id IN (?)", processIds).
  383. Where("pasture_id = ?", pastureId).
  384. Find(&neckActiveHabitList).Error; err != nil {
  385. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err))
  386. }
  387. if len(neckActiveHabitList) <= 0 {
  388. return
  389. }
  390. for _, v := range neckActiveHabitList {
  391. neckRingPenChange := &model.NeckRingPenChange{}
  392. if err := e.DB.Model(new(model.NeckRingPenChange)).
  393. Where("pasture_id = ?", pastureId).
  394. Where("heat_date = ?", v.HeatDate).
  395. Where("frameid = ?", v.Frameid).
  396. Where("pen_id = ?", v.PenId).
  397. First(&neckRingPenChange).Error; err != nil {
  398. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("v", v), zap.Any("pastureId", pastureId))
  399. continue
  400. }
  401. if neckRingPenChange == nil || neckRingPenChange.Id <= 0 {
  402. continue
  403. }
  404. if neckRingPenChange.ChangeFilter < 10 {
  405. continue
  406. }
  407. if err := e.DB.Model(new(model.NeckActiveHabit)).
  408. Where("id = ?", v.Id).
  409. Update("change_adjust", neckRingPenChange.ChangeFilter).Error; err != nil {
  410. zaplog.Error("UpdateChangeAdJust", zap.Any("error", err), zap.Any("v", v), zap.Any("neckRingPenChange", neckRingPenChange))
  411. }
  412. }
  413. }
  414. func (e *Entry) UpdateCft(pastureId int64, processIds []int64) {
  415. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  416. if err := e.DB.Model(new(model.NeckActiveHabit)).
  417. Where("id IN (?)", processIds).
  418. Where("pasture_id = ?", pastureId).
  419. Where("is_show = ?", pasturePb.IsShow_No).
  420. Find(&neckActiveHabitList).Error; err != nil {
  421. zaplog.Error("UpdateCft-1", zap.Any("error", err))
  422. }
  423. for _, v := range neckActiveHabitList {
  424. cft := CalculateCFT(v)
  425. if err := e.DB.Model(new(model.NeckActiveHabit)).
  426. Where("id = ?", v.Id).
  427. Where("neck_ring_number = ?", v.NeckRingNumber).
  428. Update("cft", strconv.FormatFloat(float64(cft), 'f', 2, 64)).Error; err != nil {
  429. zaplog.Error("UpdateCft-2", zap.Any("error", err))
  430. }
  431. }
  432. }
  433. func (e *Entry) UpdateIsShow(pastureId int64, processIds []int64) {
  434. if err := e.DB.Model(new(model.NeckActiveHabit)).
  435. Where("id IN (?)", processIds).
  436. Where("pasture_id = ?", pastureId).
  437. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  438. zaplog.Error("UpdateChangeAdJust-2", zap.Any("error", err))
  439. }
  440. }
  441. func (e *Entry) XToday(pastureId int64) (*XToday, error) {
  442. xToday := &XToday{}
  443. systemConfigureList, err := e.FindSystemNeckRingConfigure(pastureId)
  444. if err != nil {
  445. return nil, xerr.WithStack(err)
  446. }
  447. if len(systemConfigureList) <= 0 {
  448. return nil, nil
  449. }
  450. for _, v := range systemConfigureList {
  451. switch v.Name {
  452. case model.MaxHabit:
  453. xToday.LastMaxHabitId = v.Value
  454. case model.High:
  455. xToday.High = int32(v.Value)
  456. case model.Rumina:
  457. xToday.Rumina = int32(v.Value)
  458. case model.XRuminaDisc:
  459. xToday.XRuminaDisc = int32(v.Value)
  460. case model.XChangeDiscount:
  461. xToday.XChangeDiscount = int32(v.Value)
  462. case model.WeeklyActive:
  463. xToday.WeeklyActive = int32(v.Value)
  464. case model.BeforeDayNeckRing:
  465. xToday.BeforeDayNeckRing = int32(v.Value)
  466. }
  467. }
  468. return xToday, nil
  469. }
  470. // WeeklyUpdateActiveHabit 时间点周平均值计算
  471. func (e *Entry) WeeklyUpdateActiveHabit(pastureId int64, processIds []int64, xToDay *XToday) {
  472. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  473. if err := e.DB.Model(new(model.NeckActiveHabit)).
  474. Where("id IN (?)", processIds).
  475. Order("heat_date,neck_ring_number,frameid").
  476. Find(&newNeckActiveHabitList).Error; err != nil {
  477. zaplog.Error("WeeklyUpdateActiveHabit", zap.Any("error", err), zap.Any("processIds", processIds))
  478. }
  479. if len(newNeckActiveHabitList) <= 0 {
  480. return
  481. }
  482. e.HabitUpdateActiveHabit(pastureId, newNeckActiveHabitList, xToDay)
  483. e.SumUpdateActiveHabit(pastureId, newNeckActiveHabitList, xToDay)
  484. e.ActiveChange(pastureId, processIds, xToDay)
  485. e.Before3DaysNeckActiveHabit(pastureId, processIds)
  486. }
  487. func (e *Entry) HabitUpdateActiveHabit(pastureId int64, newNeckActiveHabitList []*model.NeckActiveHabit, xToDay *XToday) {
  488. for _, v := range newNeckActiveHabitList {
  489. // 前七天的
  490. weekHabitData := e.FindWeekHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  491. // 更新过滤值
  492. if err := e.DB.Model(new(model.NeckActiveHabit)).
  493. Select("high_habit", "rumina_habit", "chew_habit", "intake_habit", "inactive_habit").
  494. Where("id = ?", v.Id).
  495. Updates(map[string]interface{}{
  496. "high_habit": weekHabitData.HighHabit,
  497. "rumina_habit": weekHabitData.RuminaHabit,
  498. "chew_habit": weekHabitData.ChewHabit,
  499. "intake_habit": weekHabitData.IntakeHabit,
  500. "inactive_habit": weekHabitData.InactiveHabit,
  501. }).Error; err != nil {
  502. zaplog.Error("WeeklyUpdateActiveHabit",
  503. zap.Error(err),
  504. zap.Any("NeckActiveHabit", v),
  505. zap.Any("pastureId", pastureId),
  506. )
  507. }
  508. }
  509. }
  510. // SumUpdateActiveHabit -- 累计24小时数值
  511. func (e *Entry) SumUpdateActiveHabit(pastureId int64, newNeckActiveHabitList []*model.NeckActiveHabit, xToDay *XToday) {
  512. for _, v := range newNeckActiveHabitList {
  513. sumHabitData := e.FindSumHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  514. // 更新过滤值
  515. if err := e.DB.Model(new(model.NeckActiveHabit)).
  516. Select("sum_rumina", "sum_intake", "sum_inactive", "sum_active", "sum_max_high", "sum_min_high", "sum_min_chew").
  517. Where("id = ?", v.Id).
  518. Updates(map[string]interface{}{
  519. "sum_rumina": sumHabitData.SumRumina,
  520. "sum_intake": sumHabitData.SumIntake,
  521. "sum_inactive": sumHabitData.SumInactive,
  522. "sum_active": sumHabitData.SumActive,
  523. "sum_max_high": sumHabitData.SumMaxHigh,
  524. "sum_min_high": sumHabitData.SumMinHigh,
  525. "sum_min_chew": sumHabitData.SumMinChew,
  526. }).Error; err != nil {
  527. zaplog.Error("WeeklyUpdateActiveHabit",
  528. zap.Any("err", err),
  529. zap.Any("NeckActiveHabit", v),
  530. zap.Any("pastureId", pastureId),
  531. )
  532. }
  533. }
  534. }
  535. // ActiveChange -- 变化百分比
  536. func (e *Entry) ActiveChange(pastureId int64, processIds []int64, xToDay *XToday) {
  537. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  538. if err := e.DB.Model(new(model.NeckActiveHabit)).
  539. Where("pasture_id = ?", pastureId).
  540. Where("id IN (?)", processIds).
  541. Where("high_habit > ?", 0).
  542. Where(e.DB.Where("high >= ?", xToDay.High).Or("rumina >= ?", xToDay.Rumina)).
  543. Find(&newNeckActiveHabitList).Error; err != nil {
  544. zaplog.Error("ActiveChange", zap.Any("error", err), zap.Any("processIds", processIds))
  545. }
  546. for _, v := range newNeckActiveHabitList {
  547. changeHigh := calculateChangeHigh(v, xToDay.WeeklyActive)
  548. changeRumina := int32(0)
  549. changeChew := int32(0)
  550. if v.RuminaHabit != 0 {
  551. changeRumina = int32(math.Round(float64(v.FilterRumina-v.RuminaHabit) / float64(v.RuminaHabit) * 100))
  552. }
  553. if v.ChewHabit != 0 {
  554. changeChew = int32(math.Round(float64(v.FilterChew-v.ChewHabit) / float64(v.ChewHabit) * 100))
  555. }
  556. // 更新过滤值
  557. if err := e.DB.Model(new(model.NeckActiveHabit)).
  558. Select("change_high", "change_rumina", "change_chew").
  559. Where("id = ?", v.Id).
  560. Updates(map[string]interface{}{
  561. "change_high": changeHigh,
  562. "change_rumina": changeRumina,
  563. "change_chew": changeChew,
  564. }).Error; err != nil {
  565. zaplog.Error("ActiveChange",
  566. zap.Any("err", err),
  567. zap.Any("NeckActiveHabit", v),
  568. )
  569. }
  570. }
  571. }
  572. func (e *Entry) Before3DaysNeckActiveHabit(pastureId int64, processIds []int64) {
  573. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  574. if err := e.DB.Model(new(model.NeckActiveHabit)).
  575. Where("id IN (?)", processIds).
  576. Order("heat_date,neck_ring_number,frameid").
  577. Find(&newNeckActiveHabitList).Error; err != nil {
  578. zaplog.Error("Before3DaysNeckActiveHabit", zap.Any("error", err), zap.Any("processIds", processIds))
  579. }
  580. for _, v := range newNeckActiveHabitList {
  581. before3DaysNeckActiveHabit := e.FindBefore3DaysNeckActiveHabit(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid)
  582. if before3DaysNeckActiveHabit.SumRumina == 0 && before3DaysNeckActiveHabit.SumIntake == 0 {
  583. continue
  584. }
  585. // 更新过滤值
  586. if err := e.DB.Model(new(model.NeckActiveHabit)).
  587. Select("before_three_sum_rumina", "before_three_sum_intake").
  588. Where("id = ?", v.Id).
  589. Updates(map[string]interface{}{
  590. "before_three_sum_rumina": before3DaysNeckActiveHabit.SumRumina,
  591. "before_three_sum_intake": before3DaysNeckActiveHabit.SumIntake,
  592. }).Error; err != nil {
  593. zaplog.Error("Before3DaysNeckActiveHabit",
  594. zap.Error(err),
  595. zap.Any("NeckActiveHabit", v),
  596. zap.Any("pastureId", pastureId),
  597. )
  598. }
  599. }
  600. }
  601. // calculateChangeHigh 计算活动量变化
  602. func calculateChangeHigh(data *model.NeckActiveHabit, weeklyActive int32) int32 {
  603. highDiff := data.FilterHigh - data.HighHabit
  604. changeHigh := int32(0)
  605. if highDiff > 0 {
  606. denominator := float64(data.WeekHigh)*0.6 + float64(data.HighHabit)*0.2 + float64(weeklyActive)*0.2
  607. changeHigh = int32(math.Round((float64(highDiff) / denominator) * 100))
  608. } else {
  609. changeHigh = int32(math.Round(float64(highDiff) / float64(data.HighHabit) * 100))
  610. }
  611. return changeHigh
  612. }