package model

import (
	"fmt"
	"sparrow/pkg/models"

	"github.com/jinzhu/gorm"
)

// SignedString 签名
const SignedString = "www.yehaoji.com"

const (
	ErrUserNameOrPassCode = 20001
	ErrUserNameExsitCode  = 20002
	ErrPhoneExistCode     = 20003
	ErrEmailExistCode     = 20004
)

type User struct {
	db *gorm.DB
}

// Init 初始化
func (a *User) Init(_db *gorm.DB) *User {
	a.db = _db
	return a
}

// Create create
func (a *User) Create(user *models.User) error {
	return a.db.Save(user).Error
}

// LoginCheck 登陆检测
func (a *User) LoginCheck(loginname, loginpass string) (bool, *models.User, error) {
	user := &models.User{}
	err := a.db.
		Where("(user_name = ? or phone = ? or email = ?) AND user_pass = ?",
			loginname,
			loginname,
			loginname,
			loginpass).First(user).
		Error
	if err != nil {
		return false, nil, err
	}
	if user.ID > 0 {
		vendor := models.Vendor{}
		// check cache
		cache := getCache()
		key := fmt.Sprintf("Vendor:%d", user.VendorID)
		if v, ok := cache.Get(key); ok {
			user.Vendor = v.(models.Vendor)
		} else {
			a.db.Model(user).Related(&vendor)
			cache.Set(key, vendor)
			user.Vendor = vendor
		}

		return true, user, nil
	}

	return false, nil, nil
}

// UpdatePassword 更新密码
func (a *User) UpdatePassword(userid uint, oldpass, newpass string) (bool, error) {
	var count int
	user := &models.User{}
	err := a.db.Model(user).Where(map[string]interface{}{
		"id":        userid,
		"user_pass": oldpass,
	}).Count(&count).Error
	//.Update("user_pass", newpass).Error
	if err != nil {
		return false, err
	}
	if count > 0 {
		err = a.db.Model(user).Where(userid).Update("user_pass", newpass).Error
		if err != nil {
			return false, err
		}
	} else {
		return false, nil
	}
	return true, nil
}

// CheckUserName 检测用户名
func (a *User) CheckUserName(name string) (bool, error) {
	user := models.User{}
	var count int
	err := a.db.First(&user).
		Where("user_name = ?", name).Count(&count).Error
	if err != nil && err == gorm.ErrRecordNotFound  {
		return false, nil
	}
	if count > 0 {
		return true, nil
	}
	return false, nil
}

// CheckPhone 检测手机号
func (a *User) CheckPhone(name string) (bool, error) {
	user := models.User{}
	var count int
	err := a.db.First(&user).
		Where("user_name = ?", name).Count(&count).Error
	if err != nil && err == gorm.ErrRecordNotFound  {
		return false, nil
	}
	if count > 0 {
		return true, nil
	}
	return false, nil
}

// CheckEmail 检测Email
func (a *User) CheckEmail(name string) (bool, error) {
	user := models.User{}
	var count int
	err := a.db.First(&user).
		Where("user_name = ?", name).Count(&count).Error
	if err != nil && err == gorm.ErrRecordNotFound  {
		return false, nil
	}
	if count > 0 {
		return true, nil
	}
	return false, nil
}
