package service

import (
	"exam_system/dao"
	"exam_system/entity"
	"exam_system/middleware/claims"
	"exam_system/result"
	"exam_system/vo"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"strings"
)

func Login(u *vo.UserVo) *result.Result {
	// 1、查询
	res := dao.FindUserbySid(u.Sid)
	if res.Data == nil {
		return res
	}

	// 2、查询角色
	userVo := res.Data.(vo.UserVo)
	roleNames := strings.Split(*userVo.RoleName, ",")

	// 3、解密
	err := bcrypt.CompareHashAndPassword([]byte(userVo.Password), []byte(u.Password))
	if err != nil {
		return result.PASSWORD_ERROR
	}

	// 4、判断角色是否存在
	roleExist := false
	for _, roleName := range roleNames {
		if roleName == *u.RoleName {
			roleExist = true
			break
		}
	}
	if !roleExist {
		return result.USER_IS_NOT_EXISTED
	}

	if *userVo.Status != entity.NORMAL {
		return result.USER_PENDING_REVIEW
	}

	// 4、生产token
	token, err := claims.GenToken(userVo.ID, userVo.Username, userVo.Sid, roleNames)
	if err != nil {
		return result.UNKNOW_ERROR
	}
	userVo.Password = ""

	return result.SUCCESS.SetData(gin.H{
		"token": token,
		"user":  userVo,
	})
}

// AddUser 管理员,用户公用
func AddUser(u *entity.User, userTypes string) *result.Result {
	// 1、加密
	hash, _ := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
	u.Password = string(hash)

	// 2、插入用户表
	res := dao.InsertUser(u, userTypes)
	if res != result.SUCCESS {
		return res
	}

	return res
}
