package main

import (
	"net/http"
	"server/console"
	usercenter "server/datacenter"
	redismgr "server/db/redis"
	"server/msg"
	"server/user"

	"github.com/gin-gonic/gin"
)

func ReqLogin(c *gin.Context) {
	req := c.MustGet("protobuf_data").(*msg.ReqLogin)
	UserId, err := redismgr.GetUserIDFromRedisByAP(req.Account, req.Password)
	if err != nil {
		var user_data *usercenter.User
		user_data, err = usercenter.GetUserByAccountAndPassword(req.Account, req.Password)
		//再从sql查询如果查到了，先写入redis，再返回。否则正常返回错误
		// err = mysqlmgr.QueryRow("  SELECT * FROM users WHERE account = ? AND password = ? LIMIT 1", req.Account, req.Password).Scan(user.Coin, user.Head, user.Name, user.UserID)
		if err != nil {
			console.Log("Query error:", err)
			c.ProtoBuf(http.StatusOK, &msg.ResLogin{
				NikeName: "",
				UserId:   "",
				ErrMsg: &msg.MsgError{
					ErrorCode: 101,
					ErrorMsg:  "Password or Account is error！",
				},
			})
			return
		} else {
			redismgr.SaveUserInfoToRedis(&msg.UserInfo{
				UserId: user_data.UserID,
				MHead:  user_data.Head,
				MCoin:  int32(user_data.Coin),
				Name:   user_data.Name,
			})
		}

	}
	// 获取用户信息 ,如果新用户则创建一个
	userData := user.GetUserInfoById(UserId)
	c.ProtoBuf(http.StatusOK, &msg.ResLogin{
		UserInfo: &msg.UserInfo{
			UserId: userData.UserId,
			MHead:  userData.MHead,
			MCoin:  userData.MCoin,
			Name:   userData.Name,
			RoomId: userData.RoomId,
		},
		ErrMsg: nil,
	})
}
