package models

import (
	"bwallet/pkg/setting"
	"github.com/jinzhu/gorm"
	"time"
)

type User struct {
	Uid           int32  `gorm:"type:int(11);primary key"`
	UserName      string `gorm:"type:varchar(64);unique;not null"`
	NickName      string `gorm:"type:varchar(128)"`
	Password      string `gorm:"type:varchar(32);not null"`
	RegTime       int64  `gorm:"type:datetime"`
	LastLoginTime int64  `gorm:"type:datetime"`
	RegIp         uint32 `gorm:"type:int(10)"`
	LastLoginIp   uint32 `gorm:"type:int(10)"`
	Status        uint8  `gorm:"not null;default:0"`
	PlatformId    int64  `gorm:"not null;default:0"`
}

func (u User) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_user"
}

func GetUser(id int32) (*User, error) {
	var user User
	err := db.Where("id = ?", id).First(&user).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	err = db.Model(&user).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return &user, nil
}

func ExistUserById(id int32) (bool, error) {
	var user User
	err := db.Select("uid").Where("uid = ?", id).First(&user).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

	if user.Uid > 0 {
		return true, nil
	}

	return false, nil
}

func GetUserTotal(maps interface{}) (int, error) {
	var count int

	if err := db.Model(&User{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

func GetUsers(pageNum, pageSize int, maps interface{}) ([]*User, error) {
	var user []*User

	err := db.Where(maps).Preload("Category").Order("sort desc").Order("create_time desc").Offset(pageNum).Limit(pageSize).Find(&user).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return user, nil
}

func AddUser(data map[string]interface{}) (error) {
	user := User{
		UserName:      data["username"].(string),
		NickName:      data["nickname"].(string),
		Password:      data["password"].(string),
		RegTime:       time.Now().Unix(),
		LastLoginTime: time.Now().Unix(),
		RegIp:         data["reg_ip"].(uint32),
		LastLoginIp:   data["last_login_ip"].(uint32),
		Status:        data["status"].(uint8),
		PlatformId:    data["platform_id"].(int64),
	}

	if err := db.Create(&user).Error; err != nil {
		return err
	}

	return nil
}

func EditUser(id int32, data interface{}) error {
	if err := db.Model(&User{}).Where("uid = ?", id).Updates(data).Error; err != nil {
		return err
	}

	return nil
}

func DeleteUser(id int32) error {
	if err := db.Where("id = ?", id).Delete(User{}).Error; err != nil {
		return err
	}

	return nil
}
