package controller

import (
	"encoding/base64"
	"fmt"
	"github.com/gin-gonic/gin"
	"iot_manager_service/app/user/model"
	"iot_manager_service/app/user/service"
	"iot_manager_service/util/cache"
	"iot_manager_service/util/common"
	"iot_manager_service/util/rsa"
	"iot_manager_service/util/token"
	"iot_manager_service/util/websocket"
	"net/http"
	"strconv"
)

var SysUserController = new(user)

type user struct{}

func (u *user) Login(c *gin.Context) {
	loginSysUser := model.LoginSysUser{}
	if err := c.ShouldBindJSON(&loginSysUser); err != nil {
		c.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	info := service.SysUserService.Login(loginSysUser.UserName, loginSysUser.PassWord)
	c.JSON(http.StatusOK, info)
}

func (u *user) GetPublicKey(c *gin.Context) {
	key := service.SysUserService.GetPublicKey()

	r := rsa.RSA{}
	publicKey := r.ReturnPublicKey()
	fmt.Print("key", publicKey)
	encryption := r.Encryption([]byte("123456"))

	toString := base64.StdEncoding.EncodeToString(encryption)

	fmt.Print("?????+++", toString)
	c.JSON(http.StatusOK, key)
}

func (u *user) GetDeptSysUsers(c *gin.Context) {
	header := c.GetHeader("Authorization")
	claims, _ := token.JwtClaims.ParseJwtToken(header)
	uid, _ := strconv.Atoi(claims.ID)
	users := service.SysUserService.GetDeptSysUsers(uid)
	c.JSON(http.StatusOK, users)
}

func (u *user) GetDepts(c *gin.Context) {
	depts := service.SysUserService.GetDepts()
	c.JSON(http.StatusOK, depts)
}

func (u *user) GetNewTokens(c *gin.Context) {
	header := c.GetHeader("Authorization")
	claims, _ := token.JwtClaims.ParseJwtToken(header)
	nowSysUser, _ := cache.GetNowSysUser(claims.ID)

	accessToken, _ := token.JwtClaims.CreateJwtToken(claims.ID, nowSysUser.Username, nowSysUser.UUID, 1)
	refreshToken, _ := token.JwtClaims.CreateJwtToken(claims.ID, nowSysUser.Username, nowSysUser.UUID, 24*7)
	tokens := make(map[string]interface{})

	tokens["accessToken"] = accessToken
	tokens["refreshToken"] = refreshToken

	c.JSON(http.StatusOK, common.SuccessResponse("获取成功", tokens))
}

func (u *user) Logout(c *gin.Context) {
	header := c.GetHeader("Authorization")
	claims, _ := token.JwtClaims.ParseJwtToken(header)
	err := cache.DeleteToken(claims.ID)
	if err != nil {
		c.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	//关闭websocket连接
	websocket.CloseConn(claims.ID)
	c.JSON(http.StatusOK, common.SuccessResponse("退出成功", nil))
}

func (u *user) GetSysUserInfo(c *gin.Context) {
	header := c.GetHeader("Authorization")
	claims, _ := token.JwtClaims.ParseJwtToken(header)
	uid, _ := strconv.Atoi(claims.ID)
	info := service.SysUserService.GetSysUserInfo(uid)
	c.JSON(http.StatusOK, info)

}

func (u *user) GetSysUser(c *gin.Context) {
	fmt.Println("demo。。。")
}
