package services

import (
	"encoding/base64"
	"github.com/gogf/gf/util/guid"
	"sparrow/pkg/generator"
	"sparrow/pkg/models"
	"sparrow/pkg/utils"
	"sparrow/services/knowoapi/model"
)

// UserService 用户业务接口
type UserService interface {
	// Login 登陆
	Login(*models.LoginRequest) (bool, *models.User, error)
	// Register 注册
	Register(*models.Reqrequest) (*models.User, error)
	// ModifyPassword 修改密码,其中密码接收的是已经base64过的字符串
	ModifyPassword(uint, string, string) (bool, error)
	// CheckUserName check name exsits
	CheckUserName(string) (bool, error)
	// CheckPhone check phone number exsits
	CheckPhone(string) (bool, error)
	// CheckEmail check email exsits
	CheckEmail(string) (bool, error)
	// GetRole get role info
	GetRole(int) (models.Role, 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.RecordId = guid.S()
	_u.UserKey, _ = a.keyGen.GenRandomKey(_u.RecordId)
	_u.UserPass = utils.Md5(user.PassWord + model.SignedString)
	_u.UserName = user.UserName
	_u.Phone = user.Phone
	_u.Email = user.Email
	_u.UserRoleID = 1 //默认普通用户
	vedor := &models.Vendor{
		VendorName: user.VendorName,
	}
	vedor.RecordId = guid.S()
	vedor.VendorKey, _ = a.keyGen.GenRandomKey(vedor.RecordId)
	err := a.model.Vendor.Create(vedor)
	if err != nil {
		return nil, err
	}
	_u.VendorID = vedor.RecordId
	return _u, a.model.User.Create(_u)
}
func (a userservice) ModifyPassword(userid uint, new, old string) (bool, error) {
	obytes, _ := base64.StdEncoding.DecodeString(old)
	nbytes, _ := base64.StdEncoding.DecodeString(new)
	old = utils.Md5(string(obytes) + model.SignedString)
	new = utils.Md5(string(nbytes) + 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)
}
func (a userservice) GetRole(roleid int) (models.Role, error) {
	return a.model.Role.QueryRole(roleid)
}
