package service

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"iot_manager_service/app/user/dao"
	"iot_manager_service/util/cache"
	"iot_manager_service/util/common"
	"iot_manager_service/util/md5"
	"iot_manager_service/util/rsa"
	"iot_manager_service/util/token"
	"strconv"
)

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

type userService struct{}

func (s *userService) Login(username string, pwd string) *common.Errors {
	userdao := &dao.SysUser{}
	USER, err := userdao.LoginFindUserName(username)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return common.ParamsInvalidResponse("登录失败，账号不存在", nil)
		}
		return common.FailResponse(err.Error(), nil)
	}
	if USER.Enable != 1 {
		return common.ParamsInvalidResponse("登录失败，用户被禁止登录", nil)
	}
	//解密前端密文
	r := rsa.RSA{}
	decrypt := r.Decrypt(pwd)
	//解密数据库密文
	ok := md5.BcryptCheck(decrypt, USER.Password)
	if !ok {
		return common.ParamsInvalidResponse("密码错误", nil)
	}
	//登录成功则生成token
	USERID := strconv.Itoa(USER.ID)
	accessToken, _ := token.JwtClaims.CreateJwtToken(USERID, USER.Username, USER.UUID, 1)
	refreshToken, _ := token.JwtClaims.CreateJwtToken(USERID, USER.Username, USER.UUID, 24*7)
	cache.SetNowSysUser(USERID, USER)

	tokens := make(map[string]interface{})
	tokens["accessToken"] = accessToken
	tokens["refreshToken"] = refreshToken

	//TODO:到时候记得修改服务器域名
	urlWebSocket := "ws://106.52.134.22:8890/notice/websocket?userID=" + USERID
	return common.SuccessResponse("登录成功", gin.H{"token": tokens, "websocket": urlWebSocket})
}

func (s *userService) GetPublicKey() *common.Errors {
	r := rsa.RSA{}
	publicKey := r.ReturnPublicKey()
	return common.SuccessResponse("获取公钥成功", gin.H{"publicKey": publicKey})
}

func (s *userService) GetDeptSysUsers(id int) *common.Errors {
	deptdao := &dao.Dept{}
	depts, _ := deptdao.GetDepts(id)

	userdao := &dao.SysUser{}
	users, _ := userdao.GetSysUsers()

	deptSysUsersMap := make(map[int][]dao.SysUser)
	for _, user := range users {
		deptSysUsersMap[user.DeptId] = append(deptSysUsersMap[user.DeptId], user)
	}

	var deptSysUsers []dao.Dept
	for _, dept := range depts {
		users := deptSysUsersMap[dept.ID]
		deptSysUsers = append(deptSysUsers, dao.Dept{
			ID:       dept.ID,
			DeptName: dept.DeptName,
			ParentId: dept.ParentId,
			SysUsers: users,
		})
	}
	return common.SuccessResponse("获取成功", gin.H{"deptSysUsers": deptSysUsers})
}

func (s *userService) GetDepts() *common.Errors {
	deptdao := &dao.Dept{}
	depts, _ := deptdao.GetChildDepts()

	userdao := &dao.SysUser{}
	users, _ := userdao.GetSysUsers()

	deptSysUsersMap := make(map[int][]dao.SysUser)
	for _, user := range users {
		deptSysUsersMap[user.DeptId] = append(deptSysUsersMap[user.DeptId], user)
	}

	var deptSysUsers []dao.Dept
	for _, dept := range depts {
		users := deptSysUsersMap[dept.ID]
		if users != nil {
			deptSysUsers = append(deptSysUsers, dao.Dept{
				ID:       dept.ID,
				DeptName: dept.DeptName,
				ParentId: dept.ParentId,
			})
		}
	}
	return common.SuccessResponse("获取成功", gin.H{"depts": deptSysUsers})
}

func (s *userService) GetSysUserInfo(id int) *common.Errors {
	userdao := &dao.SysUser{}
	user, _ := userdao.GetSysUserInfo(id)
	return common.SuccessResponse("获取成功", gin.H{"sysUser": user})
}
