package services

import (
	"sparrow/pkg/generator"
	"sparrow/pkg/models"
	"sparrow/pkg/utils"
	"sparrow/services/knowoapi/model"
)

// UserService 用户业务接口
type UserService interface {
	// 登陆
	Login(*models.LoginRequest) (bool, *models.User, error)
	// 注册
	Register(*models.Reqrequest) (*models.User, error)
	// 修改密码
	ModifyPassword(int, string, string) (bool, error)
	// check name exsits
	CheckUserName(string) (bool, error)
	// check phone number exsits
	CheckPhone(string) (bool, error)
	// check email exsits
	CheckEmail(string) (bool, error)
}

type userservice struct {
	model  *model.All
	keyGen *generator.KeyGenerator
}

// NewUserService ``
func NewUserService(all *model.All, keyGen *generator.KeyGenerator) UserService {
	return userservice{
		model:  all,
		keyGen: keyGen,
	}
}

func (a userservice) Login(user *models.LoginRequest) (bool, *models.User, error) {
	user.Password = utils.Md5(user.Password + model.SignedString)
	return a.model.User.LoginCheck(user.UserName, user.Password)
}

func (a userservice) Register(user *models.Reqrequest) (*models.User, error) {
	_u := &models.User{}
	_u.UserKey, _ = a.keyGen.GenRandomKey(_u.ID)
	_u.UserPass = utils.Md5(user.PassWord + model.SignedString)
	_u.UserName = user.UserName
	_u.Phone = user.Phone
	_u.Email = user.Email
	vedor := &models.Vendor{
		VendorName: user.VendorName,
	}
	vedor.VendorKey, _ = a.keyGen.GenRandomKey(vedor.ID)
	err := a.model.Vendor.Create(vedor)
	if err != nil {
		return nil, err
	}
	_u.VendorID = vedor.ID
	return _u, a.model.User.Create(_u)
}
func (a userservice) ModifyPassword(userid int, new, old string) (bool, error) {
	old = utils.Md5(old + model.SignedString)
	new = utils.Md5(new + model.SignedString)
	return a.model.User.UpdatePassword(userid, new, old)
}

func (a userservice) CheckUserName(name string) (bool, error) {
	return a.model.User.CheckUserName(name)
}
func (a userservice) CheckPhone(name string) (bool, error) {
	return a.model.User.CheckPhone(name)
}
func (a userservice) CheckEmail(name string) (bool, error) {
	return a.model.User.CheckEmail(name)
}
