package game

import (
	"fmt"
	"reflect"
	"server/GoUtil"
	"server/MergeConst"
	"server/game/internal"
	"strings"
	"time"

	"server/msg"

	"server/pkg/github.com/name5566/leaf/gate"
	"server/pkg/github.com/name5566/leaf/log"

	"google.golang.org/protobuf/proto"

	"server/db"
)

var (
	Module  = new(internal.Module)
	ChanRPC = internal.ChanRPC
)

func handler(m interface{}, h interface{}) {
	Module.Skeleton.RegisterChanRPC(reflect.TypeOf(m), h)
}

func RegisterHandlerRPC(param []interface{}) {
	handler(&msg.ClientReq{}, HandleClientReq)
	handler(&msg.AdminReq{}, HandleAdminReq)
}

func init() {
	db.InitDB()
	db.InitRedis()
	// db.TestGetAllKey()
	GoUtil.RegisterEvent("GameModuleOnInit", RegisterHandlerRPC, nil)
	G_getGameLogic()
}

func HandleAdminReq(args []interface{}) {
	m := args[0].(*msg.AdminReq)
	// 消息的发送者
	a := args[1].(gate.Agent)
	buf := m.GetInfo()
	// log.Debug("admin 消息Func : %s", m.GetFunc())
	AdminProcess(m.GetFunc(), []interface{}{a, buf})
}

func HandleClientReq(args []interface{}) {
	if G_GameLogicPtr.SeverInfo.Status == SERVER_STATUS_CLOSE || G_GameLogicPtr.SeverInfo.Status == SERVER_STATUS_MAINTAIN {
		return // 服务器关闭或者维护中，不处理任何消息
	}
	m := args[0].(*msg.ClientReq)
	// 消息的发送者
	a := args[1].(gate.Agent)
	buf := m.GetInfo()
	// log.Debug("消息Func : %s", m.GetFunc())
	switch m.GetFunc() {
	case "ClientTick":
	case "ReqAdminInfo":
		AdminProcess(m.GetFunc(), []interface{}{a, buf})
	case "ReqServerVersion":
		G_GameLogicPtr.SendServerVersion(a)
	case "ReqRegisterAccount":
		detail := &msg.ReqRegisterAccount{}
		proto.Unmarshal(buf, detail)
		gl := G_getGameLogic()
		defer func() {
			if r := recover(); r != nil {
				GoUtil.SendFeishuFatal(0, m.GetFunc(), fmt.Sprintf("username: %s, fatal: %s", detail.UserName, r))
				log.Debug("uid : %d, func : %s, fatal : %s", 0, m.GetFunc(), r)
			}
		}()
		if gl.IsExsitAccount(detail.UserName) {
			ResRegisterAccount := &msg.ResRegisterAccount{}
			ResRegisterAccount.ResultCode = MergeConst.Protocol_Error_Account_Exist
			data, _ := proto.Marshal(ResRegisterAccount)
			gl.PackResInfo(a, "ResRegisterAccount", data)
			break
		}
		if strings.Count(detail.UserName, "")-1 < 6 {
			ResRegisterAccount := &msg.ResRegisterAccount{}
			ResRegisterAccount.ResultCode = MergeConst.Protocol_Error_Account_OR_PWD_Short
			data, _ := proto.Marshal(ResRegisterAccount)
			gl.PackResInfo(a, "ResRegisterAccount", data)
			break
		}
		gl.Db_AccountInfo.UserName = detail.UserName
		gl.Db_AccountInfo.UserPassword = detail.UserPwd
		if !gl.NewAccountInsertDataToDB() {
			ResRegisterAccount := &msg.ResRegisterAccount{}
			ResRegisterAccount.ResultCode = MergeConst.Protocol_Error_Account_Fail
			data, _ := proto.Marshal(ResRegisterAccount)
			gl.PackResInfo(a, "ResRegisterAccount", data)
			break
		}
		ResRegisterAccount := &msg.ResRegisterAccount{}
		ResRegisterAccount.ResultCode = 0
		data, _ := proto.Marshal(ResRegisterAccount)
		gl.PackResInfo(a, "ResRegisterAccount", data)
	case "ReqLogin":
		detail := &msg.ReqLogin{}
		proto.Unmarshal(buf, detail)
		accountInfo := db.GetAccountInfoFromDb(detail.UserName)
		defer func() {
			if r := recover(); r != nil {
				GoUtil.SendFeishuFatal(0, m.GetFunc(), fmt.Sprintf("username: %s, fatal: %s", detail.UserName, r))
				log.Debug("uid : %d, func : %s, fatal : %s", 0, m.GetFunc(), r)
			}
		}()
		ResLogin := &msg.ResLogin{}
		if accountInfo != nil {
			if accountInfo.UserPassword == detail.UserPwd {
				playerbaseinfo := db.GetPlayerBaseInfoFromDbByName(detail.UserName)
				if playerbaseinfo != nil {
					ResLogin.ResultCode = 0
					ResLogin.DwUin = playerbaseinfo.DwUin
					ResLogin.FaceBookId = playerbaseinfo.FaceBookId
					ResLogin.UserName = playerbaseinfo.UserName
				} else {
					ResLogin.ResultCode = MergeConst.Protocol_Error_Account_NoExsit
					ResLogin.DwUin = 0
				}
			} else {
				ResLogin.ResultCode = MergeConst.Protocol_Error_Account_OR_PWD_ERROR
				ResLogin.DwUin = 0
			}
		} else {
			ResLogin.ResultCode = MergeConst.Protocol_Error_Account_OR_PWD_ERROR
			ResLogin.DwUin = 0
			resBuff, _ := proto.Marshal(ResLogin)
			G_GameLogicPtr.PackResInfo(a, "ResLogin", resBuff)
			return
		}
		if ResLogin.DwUin > 0 {
			OldPlayer := G_GameLogicPtr.GetPlayer(ResLogin.DwUin)
			err := G_GameLogicPtr.ReplaceExistPlayerAndAgent(a, OldPlayer)
			if err != nil {
				G_GameLogicPtr.CreateNewPlayer(a, detail.UserName)
			}
		}
		p, _ := internal.Agents.Load(a)
		if p != nil {
			p.(*Player).PushClientRes(ResLogin)
			G_GameLogicPtr.AddLog(&Log{
				Uid:       p.(*Player).M_DwUin,
				EventName: "Login_log",
			})
		}
	case "ReqServerTime": // 获取服务器时间
		detail := &msg.ReqServerTime{}
		proto.Unmarshal(buf, detail)
		res := &msg.ResServerTime{}
		res.ServerTime = (int32)(time.Now().Unix())
		data, _ := proto.Marshal(res)
		G_getGameLogic().PackResInfo(a, "ResServerTime", data)
	case "ReqOfflineReconnect": // 断线重连
		ReqOfflineReconnectFunc(a, buf)
	default:
		p, ok := internal.Agents.Load(a)
		if ok && p != G_GameLogicPtr.NotInitPlayer {
			p.(*Player).lock.Lock()        //加锁
			backup := p.(*Player).BackUp() // 备份当前的 Player 值
			defer func() {
				if r := recover(); r != nil {
					log.Error("uid : %d, func : %s, fatal : %s", p.(*Player).M_DwUin, m.GetFunc(), r)
					GoUtil.SendFeishuFatal(int(p.(*Player).M_DwUin), m.GetFunc(), fmt.Sprintf("fatal : %s", r))
					p.(*Player).Recover(backup) //还原Player的数据
				}
				p.(*Player).lock.Unlock() //解锁
			}()
			p.(*Player).args = make(map[string]interface{})
			p.(*Player).args["func"] = m
			p.(*Player).args["agent"] = a
			err := RunNetProcessByKey(m.GetFunc(), []interface{}{a, buf})
			if err != nil {
				log.Debug("uid : %d, func : %s, err : %s", p.(*Player).M_DwUin, m.GetFunc(), err)
				p.(*Player).Recover(backup) //还原Player的数据
				return
			}
			p.(*Player).ProcessTrigger()
		}
	}
	p, b := internal.Agents.Load(a)
	if b {
		p.(*Player).SendClientRes()
	}

}
