package user

import (
	"ddpf/model/dbm"
	"github.com/tangs-drm/go-tool/util"
	"github.com/tangs-drm/go-tool/log"
)

// ExistUser 判断用户是否存在
func ExistUser(account string) (bool, error) {
	if len(account) < 1 {
		return false, util.Error("uid is empty")
	}
	var sqlString string = "SELECT ID FROM USER WHERE ACCOUNT = ?;"
	rows, err := dbm.Db().Query(sqlString, account)
	if err != nil {
		log.Error("ExistUser find user by account(%v) error ->(%v)", account, err)
		return false, err
	}
	defer rows.Close()

	if !rows.Next() {
		return false, nil
	}
	return true, nil
}

/*
CheckPassword
arg
	account:用户账号
	password:用户密码
desc
	检查用户账号和密码是否匹配
ret
	0：返回用户信息
	1：返回错误信息
*/
func CheckPassword(account, password string) (*User, error) {
	var sqlString string = "SELECT ID FROM USER WHERE ACCOUNT = ? AND PASSWORD = ?;"
	rows, err := dbm.Db().Query(sqlString, account, password)
	if err != nil {
		log.Error("CheckPassword check account(%v) error ->(%v)", account, err)
		return nil, err
	}
	defer rows.Close()

	if !rows.Next() {
		return &User{}, nil
	}
	var user = &User{}
	err = rows.Scan(&user.Id)
	if err != nil {
		log.Error("CheckPassword check account(%v) scan value error ->(%v)", account, err)
		return nil, err
	}
	return user, nil
}

