package service

import (
	"blazing/cool"
	"blazing/modules/blazing/model"
	"context"
	"encoding/json"
	"strings"
	"time"

	"github.com/gogf/gf/v2/os/glog"
)

// 是否注册,如果注册过,那么就会产生用户player信息
func (s *UserService) IsReg() bool {

	m := cool.DBM(s.info.Model).Where("player_id", s.userid)

	record, err := m.One()
	if err != nil {
		return false
	}
	if record != nil {
		return true
	}
	return false
}

// 实现注册,id+昵称+颜色
func (s *UserService) Reg(nick string, color uint32) {

	nick = strings.Trim(nick, "\x00")

	t := model.NewPlayer()
	t.PlayerID = uint64(s.userid)
	//设置用户信息
	t1 := model.NewPlayerInfo()
	t1.Nick = nick

	t1.Color = color
	t1.RegisterTime = uint32(time.Now().Unix()) //写入注册时间
	t22, err := json.Marshal(t1)
	if err != nil {
		return
	}

	t.Data = string(t22)
	_, err = cool.DBM(s.info.Model).Data(t).FieldsEx("id").Insert()
	if err != nil {
		glog.Error(context.Background(), err)
		return
	}
	//go s.InitTask()
}

func (s *UserService) Person() (ret *model.PlayerInfo) {

	m := cool.DBM(s.info.Model).Where("player_id", s.userid)
	var tt model.Player
	m.Scan(&tt)
	json.Unmarshal([]byte(tt.Data), &ret)

	return

}
func (s *UserService) PersonOther(userid uint32) (ret *model.PlayerInfo) {

	m := cool.DBM(s.info.Model).Where("player_id", userid)
	var tt model.Player
	m.Scan(&tt)
	json.Unmarshal([]byte(tt.Data), &ret)

	return

}
func (s *UserService) Save(data *model.PlayerInfo) {

	m := cool.DBM(s.info.Model).Where("player_id", data.UserID)
	var tt model.Player
	m.Scan(&tt)
	//todo 待测试

	temp, _ := json.Marshal(data)
	tt.Data = string(temp)
	_, err := m.Update(tt)
	if err != nil {
		panic(err)
	}

	return

}

func (s *UserService) RegExec(processFunc func(*model.PlayerInfo) bool) bool {
	//todo待测试
	var player model.Player
	m1 := cool.DBM(s.info.Model).Where("player_id", s.userid)
	m1.Scan(&player)
	var tt model.PlayerInfo
	json.Unmarshal([]byte(player.Data), &tt)
	processFunc(&tt)
	tmep, _ := json.Marshal(tt)
	player.Data = string(tmep)
	m1.Save(player)
	return false
}
