package manager

import (
	"Wine-Server/utils"
	"Wine-Server/utils/tables"
	"errors"
	"github.com/gorilla/websocket"
)

func keepAlive(conn *websocket.Conn) {
	_ = conn.WriteJSON(utils.WsEvent("pon", nil))
}

func getSecrets(conn *websocket.Conn) {
	_ = conn.WriteJSON(utils.WsEvent("secrets", utils.JsonType{
		"public": utils.ClientPub, "private": utils.ClientPri,
	}))
}

func userLogin(conn *websocket.Conn, data any) (string, error) {
	var param loginParam
	err := utils.AnyTrans(data, &param)
	if err != nil {
		_ = conn.WriteJSON(utils.WsError("param error"))
		return "", err
	}
	password, err := utils.Decrypt(param.Password)
	manager := tables.ManagerTable{Account: param.Account}
	err = manager.GetByAcc()
	if err != nil {
		_ = conn.WriteJSON(utils.WsEvent("loginResult", utils.JsonType{"status": false, "msg": "用户不存在"}))
		utils.Logger.Println(err)
		return "", err
	}
	if utils.IsPasswordMatch(manager.Password, password) {
		var token string
		utils.ManagerLock.Lock()
		if _, exist := utils.ManagerWss[manager.Id]; exist {
			utils.ManagerLock.Unlock()
			_ = conn.WriteJSON(utils.WsEvent("loginResult", utils.JsonType{"status": false, "msg": "账户已在别处登录"}))
			return "", errors.New("login other where")
		}
		for {
			token = utils.Format("ManagerToken_%s", utils.RandomString(19, utils.AlphaNumPatten))
			exist, _ := utils.Redis.Exists(utils.WxPayCli, token).Result()
			if exist != 1 {
				_ = utils.Redis.Set(utils.WxPayCli, token, manager.Id, utils.Duration(7*24*60*60)).Err()
				break
			}
		}
		utils.ManagerLock.Unlock()
		_ = conn.WriteJSON(utils.WsEvent("loginResult", utils.Success(utils.JsonType{"token": token, "super": manager.Super})))
		return manager.Id, nil
	} else {
		utils.Logger.Println(utils.HashPassword(password))
		_ = conn.WriteJSON(utils.WsEvent("loginResult", utils.Fail("密码错误")))
		return "", errors.New("password error")
	}
}

func getUserInfo(conn *websocket.Conn, manager *tables.ManagerTable) {
	_ = conn.WriteJSON(utils.WsEvent("userInfo", utils.JsonType{
		"id": manager.Id, "super": manager.Super, "name": manager.Name,
		"order": manager.Order, "income": manager.Income,
	}))
}

func userLogout(conn *websocket.Conn, data any) {
	utils.Redis.Del(utils.WxPayCli, data.(string))
	_ = conn.WriteJSON(utils.WsEvent("logoutResult", nil))
}
