package jobs

import (
	"encoding/json"
	"gadmin/config"
	model2 "gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"github.com/sirupsen/logrus"
	"gorm.io/gen"
	"log"
)

var MaxTalents = new(jMaxTalents)

type jMaxTalents struct {
	Stat map[int]int
}

func (j *jMaxTalents) Run() {
	logrus.Info("jMaxTalents Run.....")
	j.Stat = make(map[int]int)
	j.stat()
}

func (j *jMaxTalents) stat() {
	var (
		results []*model2.PlayerMaterial
		m       = query.Use(config.GDB1).PlayerMaterial
	)
	err := m.Select(m.ID, m.Talents).
		FindInBatches(&results, 10000, func(tx gen.Dao, batch int) error {
			for _, result := range results {
				if result.Talents == "" {
					logrus.Warningf("无Talents，跳过..")
					continue
				}

				var talents = make(map[int]int)
				if err := json.Unmarshal([]byte(result.Talents), &talents); err != nil {
					logrus.Warningf("Unmarshal talents err:%+v", err)
					panic(err)
				}

				if len(talents) > 0 {
					for id, level := range talents {
						lv, ok := j.Stat[id]
						if !ok {
							j.Stat[id] = level
							continue
						}

						if lv < level {
							j.Stat[id] = level
							continue
						}
					}
				}
			}
			return nil
		})

	if err != nil {
		panic(err)
	} else {
		logrus.Warningf("stat:%+v", j.Stat)
		log.Println("stat MaxTalents finished")
	}
}
