package ws

import (
	"encoding/json"
	"errors"
	"fmt"
	"gadmin/config"
	"gadmin/internal/admin/consts"
	"gadmin/internal/admin/gm_rpc/rpc_share"
	"gadmin/internal/gorm/query"
	"gadmin/utility/player"
	"leafstalk/covenant/msg"
	"strconv"
	"time"

	"github.com/gorilla/websocket"
	"github.com/sirupsen/logrus"
)

var (
	errUserNotFound = Msg{
		Type: consts.SocketQueryUser,
		Code: consts.CodePanicErr,
		Msg:  "用户查询失败..",
	}
)

func (client *Client) HandlerReqMsg(reqMsg ReqMsg) {
	if reqMsg.Type != consts.SocketHeartBeat {
		logrus.WithField("from", "HandlerReqMsg").Infof("ws收到消息 sid:%d, admin_id:%v, 请求数据: %+v", client.Id, client.claims.ID, reqMsg)
	}

	switch reqMsg.Type {
	// 心跳
	case consts.SocketHeartBeat:
		client.lastHeart = time.Now().Unix()
		client.WriteResp([]byte(`{"type":1, "pong":1}`))

	// 查询用户
	case consts.SocketQueryUser:
		playerId, _ := strconv.ParseInt(reqMsg.Data, 10, 64)
		if playerId == 0 {
			client.msgChan <- errUserNotFound
		}

		DB, err := player.GetDBByUserId(playerId)
		if err != nil {
			client.msgChan <- Msg{
				Type: consts.SocketQueryUser,
				Code: consts.CodePanicErr,
				Msg:  "用户查询失败 GetDBByUserId:" + err.Error(),
			}
			return
		}

		if DB <= 0 {
			client.msgChan <- Msg{
				Type: consts.SocketQueryUser,
				Code: consts.CodePanicErr,
				Msg:  "玩家服务器信息获取失败",
			}
			return
		}

		data := &msg.GmPlayer{
			MsgId:      fmt.Sprintf("qu:%d:%d", client.Id, playerId),
			PlayerID:   playerId,
			OperatorId: client.claims.ID,
		}

		var resp *msg.ResponseGmPlayer
		res, err := config.GmNats.GmRequest(DB, "GmPlayer", data)
		if err != nil {
			client.msgChan <- Msg{
				Type: consts.SocketQueryUser,
				Code: consts.CodePanicErr,
				Msg:  "用户查询失败 nats查询出错:" + err.Error(),
			}
			return
		}

		if err = json.Unmarshal(res, &resp); err != nil {
			client.msgChan <- Msg{
				Type: consts.SocketQueryUser,
				Code: consts.CodePanicErr,
				Msg:  "用户查询失败 nats Unmarshal出错:" + err.Error(),
			}
			return
		}

		rpc_share.LogChan <- rpc_share.LogMsg{
			MsgID: data.MsgId,
			Data:  resp,
		}

	// 查询开关
	case consts.SocketQuerySwitcher:

		data := &msg.GetGmIosPay{
			MsgId: fmt.Sprintf("qs:%d:%s", client.Id, reqMsg.Data),
		}
		q := query.Use(config.DB).ServerOption
		server, err := q.Order(q.ID.Desc()).First()
		if err != nil {
			logrus.Warnf("SocketQuerySwitcher 查询出错 server err:%+v", err)
			client.msgChan <- Msg{
				Type: consts.SocketQuerySwitcher,
				Code: consts.CodePanicErr,
				Msg:  "查询开关信息失败 获取服务器错误:" + err.Error(),
			}
			return
		}
		var resp *msg.ResponseGetGmIosPay
		res, err := config.GmNats.GmRequest(int(server.ServerID), "GetGmIosPay", data)
		if err != nil {
			client.msgChan <- Msg{
				Type: consts.SocketQuerySwitcher,
				Code: consts.CodePanicErr,
				Msg:  "查询开关信息失败 nats查询出错:" + err.Error(),
			}
			return
		}

		if err = json.Unmarshal(res, &resp); err != nil {
			client.msgChan <- Msg{
				Type: consts.SocketQueryUserGuide,
				Code: consts.CodePanicErr,
				Msg:  "查询开关信息失败 nats Unmarshal出错:" + err.Error(),
			}
			return
		}

		rpc_share.LogChan <- rpc_share.LogMsg{
			MsgID: data.MsgId,
			Data:  resp,
		}
	}

}

func (client *Client) WriteResp(data []byte) (err error) {
	client.Lock.Lock()
	defer client.Lock.Unlock()
	if client.lastHeart < time.Now().Unix()-300 {
		client.c.Close()
		return errors.New("timeout")
	}

	err = client.c.WriteMessage(websocket.TextMessage, data)
	return
}
