package service

import (
	"bytes"
	"encoding/base64"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"iot_manager_service/util/cache"
	"iot_manager_service/util/rsa"
	"iot_manager_service/util/token"
	"strconv"

	//"github.com/google/uuid"
	"gorm.io/gorm"
	"iot_manager_service/app/user/dao"
	"iot_manager_service/util/common"
	//"iot_manager_service/util/rsa"
	//"iot_manager_service/util/token"
	//"strconv"
)

// 用户管理服务
var UserService = new(userService)

type userService struct{}

func (s *userService) Login(acc string, pwd string) *common.Errors {
	userdao := &dao.User{}
	user, err := userdao.LoginFindAccount(acc)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return common.ParamsInvalidResponse("很抱歉，由于您的账号未完成注册或已被禁用，暂时无法使用。", nil)
		}
		return common.FailResponse(err.Error(), nil)
	}

	//加密
	//encryption := rsa.Encryption([]byte("123456"))
	//base64.StdEncoding.EncodeToString(encryption))
	//解密前端密文
	a, _ := base64.StdEncoding.DecodeString(pwd)
	client := rsa.Decryption(a)

	//解密数据库密文
	b, _ := base64.StdEncoding.DecodeString(user.Password)
	mysql := rsa.Decryption(b)
	if !bytes.Equal(client, mysql) {
		return common.ParamsInvalidResponse("密码错误", err)
	}

	//登录成功则生成token
	UUID := uuid.New().String()
	USERID := strconv.Itoa(user.ID)
	jwtToken, _ := token.JwtClaims.CreateJwtToken(USERID, user.UserName, UUID)
	cache.SetToken(USERID, UUID)
	return common.SuccessResponse("登录成功", gin.H{"token": jwtToken})
}

func (s *userService) GetPublicKey() *common.Errors {
	pub, err := rsa.GetPubKey()
	if err != nil {
		return common.FailResponse(err.Error(), nil)
	}
	return common.SuccessResponse("获取公钥成功", gin.H{"publicKey": pub})
}
