package gm_services

import (
	"encoding/json"
	"fmt"
	"gadmin/internal/admin/consts"
	"gadmin/internal/admin/gm_rpc/rpc_share"
	"gadmin/internal/admin/ws"
	"gadmin/utility"
	"leafstalk/covenant/msg"
	"strings"
	"time"

	"github.com/sirupsen/logrus"
)

type CommonResp struct {
	MsgId   string `json:"msgId"`
	ErrCode int    `json:"errCode"`
}

func ListenRespMsg() {
	for {
		select {
		case logMsg, ok := <-rpc_share.LogChan:
			logrus.Infof("new ListenRespMsg MsgID:%v, Data:%+v", logMsg.MsgID, logMsg.Data)
			if ok {
				if isSingle, prefix, cId := isSinglemsg(logMsg.MsgID); isSingle { //  如果是查詢用戶的，直接發送給指定用戶
					switch prefix {
					case "qu":
						//infos := strings.Split(logMsg.MsgID, ":")
						//var ext map[string]interface{}
						//if user := data.GetUser(cast.ToInt64(infos[2])); user != nil {
						//	ext = map[string]interface{}{"nickName": user.Nickname, "createAt": user.Createtime}
						//}
						resp := logMsg.Data.(*msg.ResponseGmPlayer)
						ws.BoardCast <- ws.Msg{
							Type: getMsgType(logMsg.MsgID),
							Id:   time.Now().Unix(),
							Code: resp.ErrCode,
							Msg:  string(utility.FormatToBytes(resp.Data)),
							CID:  cId,
							//Extra: ext,
						}
					case "qs": // query switcher
						resp := logMsg.Data.(*msg.ResponseGetGmIosPay)
						ws.BoardCast <- ws.Msg{
							Type: getMsgType(logMsg.MsgID),
							Id:   time.Now().Unix(),
							Code: resp.ErrCode,
							Msg:  fmt.Sprintf(`{"iosOpenLevel":%d}`, resp.IosPayOpenLevel),
							CID:  cId,
						}
						/*case "qe": // query endlessRand
							resp := logMsg.Data.(*msg.ResponseGmQueryEndlessRank)
							//if len(resp.Data) == 0 {
							//	getCurrentRankingListKey := func() string {
							//		tm := time.Now()
							//		y, w := tm.ISOWeek()
							//		k := y*100 + w
							//		return fmt.Sprintf("ranking_list:%d", k)
							//	}
							//
							//	key := getCurrentRankingListKey()
							//	logrus.Warnf("无尽排行 getCurrentRankingListKey key:%+v", key)
							//
							//	list, err := config.Redis.ZRevRangeWithScores(key, 0, 99).Result()
							//	if err != nil {
							//		ws.BoardCast <- ws.Msg{
							//			Type: getMsgType(logMsg.MsgID),
							//			Id:   time.Now().Unix(),
							//			Code: resp.ErrCode,
							//			Msg:  string(utility.FormatToBytes(resp.Data)),
							//			CID:  cId,
							//		}
							//		logrus.Warnf("无尽排行 ZRevRangeWithScores err:%+v", err)
							//		return
							//	}
							//
							//	logrus.Warnf("list:%+v", list)
							//
							//	var models []*msg.EndlessUserItem
							//
							//	for k, v := range list {
							//		score := v.Score / 1000000
							//		models = append(models, &msg.EndlessUserItem{
							//			PlayerId: cast.ToInt(v.Member),
							//			Level:    int(score),
							//			Order:    k + 1,
							//		})
							//	}
							//
							//	resp.Data = append(resp.Data, models...)
							//}
							for _, v := range resp.Data {
								user := data.GetUser(cast.ToInt64(v.PlayerId))
								//logrus.Warnf("user:%+v", user)
								if user != nil {
									v.CreateAt = user.CreateTime.Format("2006-01-02 15:04:05")
									v.NickName = user.NickName
								}
							}
							ws.BoardCast <- ws.Msg{
								Type: getMsgType(logMsg.MsgID),
								Id:   time.Now().Unix(),
								Code: resp.ErrCode,
								Msg:  string(utility.FormatToBytes(resp.Data)),
								CID:  cId,
							}
						case "qf": // query endlessRand
							resp := logMsg.Data.(*msg.ResponseGmGetGuide)
							ws.BoardCast <- ws.Msg{
								Type: getMsgType(logMsg.MsgID),
								Id:   time.Now().Unix(),
								Code: resp.ErrCode,
								Msg:  string(utility.FormatToBytes(resp.Data)),
								CID:  cId,
							}*/
					}

				} else { // 其他消息全部客戶都通知
					//typ, ok := IsNoticeMsg(logMsg.MsgID)
					//if ok {
					//	resp := logMsg.Data.(*msg.ResponseGmGetGuide)
					//	ws.BoardCast <- ws.Msg{
					//		Type: getMsgType(logMsg.MsgID),
					//		Id:   time.Now().Unix(),
					//		Code: resp.ErrCode,
					//		Msg:  string(utility.FormatToBytes(resp.Data)),
					//		CID:  cId,
					//	}
					//	return
					//}
					var resp CommonResp
					if tip, ok := rpc_share.MsgMap[logMsg.MsgID]; ok {
						delete(rpc_share.MsgMap, logMsg.MsgID)
						if err := json.Unmarshal(utility.FormatToBytes(logMsg.Data), &resp); err != nil {
							logrus.Warnf("ListenRespMsg CommonResp json.Unmarshal err :%v", err)
							return
						}
						wsMsg := ws.Msg{
							Type: getMsgType(logMsg.MsgID),
							Id:   time.Now().Unix(),
							Code: resp.ErrCode,
							Msg:  tip,
						}
						ws.BoardCast <- wsMsg
					}

				}
			}
		default:
			time.Sleep(1 * time.Second)
		}
	}
}

func isSinglemsg(str string) (bool, string, string) {
	data := strings.Split(str, ":")
	if len(data) != 3 {
		return false, "", ""
	}

	return strings.HasPrefix(data[0], "q"), data[0], data[1]
}

func IsNoticeMsg(str string) (int64, bool) {
	data := strings.Split(str, ":")
	if len(data) != 2 {
		return 0, false
	}
	typ := getMsgType(str)
	if typ != consts.SocketBoardCastMsg {
		return typ, true
	}

	return 0, false
}

// getMsgType 获取消息类型
func getMsgType(id string) int64 {
	if strings.HasPrefix(id, "qu") {
		return consts.SocketQueryUser
	} else if strings.HasPrefix(id, "qs") {
		return consts.SocketQuerySwitcher
	} else if strings.HasPrefix(id, "qe") {
		return consts.SocketQueryEndlessRank
	} else if strings.HasPrefix(id, "qf") {
		return consts.SocketQueryUserGuide
		//} else if strings.HasPrefix(id, "delRank") {
		//	return consts.SocketDelRank
	} else {
		return consts.SocketBoardCastMsg
	}
}
