package user_service

import (
	"bwallet/models"
)

type User struct {
	Uid           int32
	UserName      string
	NickName      string
	Password      string
	RegTime       int64
	LastLoginTime int64
	RegIp         uint32
	LastLoginIp   uint32
	Status        uint8
	PlatformId    int64

	PageNum  int
	PageSize int
}

func (u *User) GetUser() (*models.User, error) {
	user, err := models.GetUser(u.Uid)
	if err != nil {
		return nil, err
	}

	return user, nil
}

func (u *User) GetAll() ([]*models.User, error) {
	var user []*models.User

	user, err := models.GetUsers(u.PageNum, u.PageSize, u.getMaps())
	if err != nil {
		return nil, err
	}

	return user, nil
}

func (u *User) Add() error {
	user := map[string]interface{}{
		"username":      u.UserName,
		"nickname":      u.NickName,
		"password":      u.Password,
		"reg_ip":        u.RegIp,
		"last_login_ip": u.LastLoginIp,
		"status":        u.Status,
		"platform_id":   u.PlatformId,
	}

	if err := models.AddUser(user); err != nil {
		return err
	}

	return nil
}

func (u *User) Edit() error {
	return models.EditUser(u.Uid, map[string]interface{}{
		"username":      u.UserName,
		"nickname":      u.NickName,
		"password":      u.Password,
		"reg_ip":        u.RegIp,
		"last_login_ip": u.LastLoginIp,
		"status":        u.Status,
		"platform_id":   u.PlatformId,
	})
}

func (u *User) ExistById() (bool, error) {
	return models.ExistUserById(u.Uid)
}

func (u *User) Count() (int, error) {
	return models.GetUserTotal(u.getMaps())
}

func (u *User) Delete() error {
	return models.DeleteUser(u.Uid)
}

func (u *User) getMaps() (map[string]interface{}) {
	maps := make(map[string]interface{})

	if u.Uid != 0 {
		maps["id"] = u.Uid
	}

	if u.PlatformId != 0 {
		maps["platform_id"] = u.PlatformId
	}

	maps["status"] = u.Status

	return maps
}
