up_income_stat.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package income
  2. import (
  3. "bytes"
  4. "context"
  5. "strconv"
  6. incomeD "go-common/app/job/main/growup/dao/income"
  7. model "go-common/app/job/main/growup/model/income"
  8. )
  9. // UpIncomeStatSvr up_income_stat svr
  10. type UpIncomeStatSvr struct {
  11. batchSize int
  12. dao *incomeD.Dao
  13. }
  14. // NewUpIncomeStatSvr new server
  15. func NewUpIncomeStatSvr(dao *incomeD.Dao, batchSize int) (svr *UpIncomeStatSvr) {
  16. return &UpIncomeStatSvr{
  17. batchSize: batchSize,
  18. dao: dao,
  19. }
  20. }
  21. // UpIncomeStat return stats, key: mid, value: total_income
  22. func (p *UpIncomeStatSvr) UpIncomeStat(c context.Context, limit int64) (m map[int64]*model.UpIncomeStat, err error) {
  23. var id int64
  24. m = make(map[int64]*model.UpIncomeStat)
  25. for {
  26. var um map[int64]*model.UpIncomeStat
  27. um, id, err = p.dao.UpIncomeStat(c, id, limit)
  28. if err != nil {
  29. return
  30. }
  31. if len(um) == 0 {
  32. break
  33. }
  34. for mid, u := range um {
  35. if u.IsDeleted == 0 {
  36. m[mid] = u
  37. }
  38. }
  39. }
  40. return
  41. }
  42. // BatchInsertUpIncomeStat insert up_income_statis batch
  43. func (p *UpIncomeStatSvr) BatchInsertUpIncomeStat(c context.Context, us map[int64]*model.UpIncomeStat) (err error) {
  44. var (
  45. buff = make([]*model.UpIncomeStat, batchSize)
  46. buffEnd = 0
  47. )
  48. for _, u := range us {
  49. if u.DataState == 0 {
  50. continue
  51. }
  52. buff[buffEnd] = u
  53. buffEnd++
  54. if buffEnd >= p.batchSize {
  55. values := upIncomeStatValues(buff[:buffEnd])
  56. buffEnd = 0
  57. _, err = p.dao.InsertUpIncomeStat(c, values)
  58. if err != nil {
  59. return
  60. }
  61. }
  62. }
  63. if buffEnd > 0 {
  64. values := upIncomeStatValues(buff[:buffEnd])
  65. buffEnd = 0
  66. _, err = p.dao.InsertUpIncomeStat(c, values)
  67. }
  68. return
  69. }
  70. func upIncomeStatValues(us []*model.UpIncomeStat) (values string) {
  71. var buf bytes.Buffer
  72. for _, u := range us {
  73. buf.WriteString("(")
  74. buf.WriteString(strconv.FormatInt(u.MID, 10))
  75. buf.WriteByte(',')
  76. buf.WriteString(strconv.FormatInt(u.TotalIncome, 10))
  77. buf.WriteByte(',')
  78. buf.WriteString(strconv.FormatInt(u.AvTotalIncome, 10))
  79. buf.WriteByte(',')
  80. buf.WriteString(strconv.FormatInt(u.ColumnTotalIncome, 10))
  81. buf.WriteByte(',')
  82. buf.WriteString(strconv.FormatInt(u.BgmTotalIncome, 10))
  83. buf.WriteString(")")
  84. buf.WriteByte(',')
  85. }
  86. if buf.Len() > 0 {
  87. buf.Truncate(buf.Len() - 1)
  88. }
  89. values = buf.String()
  90. buf.Reset()
  91. return
  92. }