package jobs

import (
	"fmt"
	"gadmin/config"
	"gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"github.com/jinzhu/now"
	"github.com/sirupsen/logrus"
	"gorm.io/gen"
	"sync"
	"time"
)

var (
	Logins = new(jLogins)
)

type jLogins struct {
	sync.RWMutex
}

func (j *jLogins) Run() {
	logrus.Info("jLogins Run.....")
	j.handle()
}

// handle
// 用法，通过一下脚本过滤出满足时间段内的用户，和达到指定累计登录次数的次数统计，再通过sql于广告表关联计算出近一段时间登陆超过N天的用户，看有多少人没有一次广告展示

// 查询连续登录超过3天的用户
// SELECT `playerid` FROM `player_logins` where times >= 5

// 查询 连续登录超过3天的用户观看过广告的次数
// SELECT COUNT(DISTINCT user_id) FROM `advertisement_logs` where user_id IN(SELECT `playerid` FROM `player_logins` where times >= 3)
func (j *jLogins) handle() {
	j.RLock()
	defer j.RUnlock()

	var (
		results []*model.LoginLog
		u             = query.Use(config.DB).LoginLog
		l             = query.Use(config.DB).PlayerLogin
		startAt int32 = 1676908800
		endAt   int32 = 1677427200
		logins  []*model.PlayerLogin
		batches []*model.PlayerLogin
	)
	err := u.Select(u.UserID.Distinct()).
		Where(u.EventAt.Between(startAt, endAt)).
		Order(u.ID).
		FindInBatches(&results, 10000000, func(tx gen.Dao, batch int) error {
			for _, result := range results {
				if result.UserID == 0 {
					continue
				}
				letter := &model.PlayerLogin{
					Playerid: result.UserID,
				}

				batches = append(batches, letter)
				if len(batches) >= 1000 {
					if err := l.Create(batches...); err != nil {
						logrus.Warningf("addLetter Create err :%+v, batches:%+v", err, batches)
						return err
					}
					batches = []*model.PlayerLogin{}
				}

			}
			return nil
		})

	if err != nil {
		logrus.WithField("form", "Logins").Errorf("FindInBatches err:%+v", err)
	}

	if len(batches) > 0 {
		if err = l.Create(batches...); err != nil {
			logrus.Warningf("addLetter Create err2 :%+v, batches:%+v", err, batches)
		}
	}

	for i := 0; i <= 6; i++ {
		at := now.With(time.Unix(int64(startAt), 0).AddDate(0, 0, i))
		begin, end := at.BeginningOfDay().Unix(), at.EndOfDay().Unix()
		logrus.Warnf("at:%v", at)
		logrus.Warnf("begin:%v,end:%v", begin, end)

		err = l.Select(l.ID, l.Playerid, l.Times).
			Where(l.Times.Lt(3)).
			Order(l.ID).
			FindInBatches(&logins, 1000, func(tx gen.Dao, batch int) error {
				for _, login := range logins {
					first, _ := u.Select(u.UserID.Distinct()).
						Where(u.EventAt.Between(int32(begin), int32(end))).
						Where(u.UserID.Eq(int64(login.Playerid))).First()
					if first != nil {
						if _, err := l.Where(l.ID.Eq(login.ID)).Updates(&model.PlayerLogin{
							Times: login.Times + 1,
						}); err != nil {
							fmt.Printf("Updates err: %+v", err)
							logrus.WithField("form", "Logins").Warnf("Updates err: %+v", err)
							return err
						}
					}
				}
				return nil
			})

		if err != nil {
			logrus.WithField("form", "Logins").Errorf("FindInBatches2 err:%+v", err)
		}

	}

	logrus.Infof("jLogins ok!!")
}
