package nt

import (
	"encoding/json"
	"go.uber.org/zap"
	"time"
)

/// 向消息队列写数据

// 数据格式
type MqJsonMsg struct {
	EventId int32       `json:"id"`
	Guid    uint64      `json:"guid"`
	Orig    uint64      `json:"orig"`
	Ts      int64       `json:"ts"`
	Aux     string      `json:"aux"`
	Params  interface{} `json:"params"`
}

func WriteUserMsg(guid uint64, evId int32, aux string, params interface{}) {
	Wp.Put(func(t *time.Timer) {
		_ = write_user_msg(guid, evId, InstConf.Id, aux, params)
	})
}

func WriteSysMsg(guid uint64, evId int32, aux string, params interface{}) {
	Wp.Put(func(t *time.Timer) {
		_ = write_user_msg(guid, evId, InstConf.Id, aux, params)
	})
}

func WriteMgrMsg(guid uint64, evId int32, aux string, params interface{}) {
	Wp.Put(func(t *time.Timer) {
		_ = write_user_msg(guid, evId, InstConf.Id, aux, params)
	})
}

func WriteDefMsg(guid uint64, evId int32, aux string, params interface{}) {
	Wp.Put(func(t *time.Timer) {
		_ = write_def_msg(guid, evId, InstConf.Id, aux, params)
	})
}

func write_user_msg(guid uint64, evId int32, logicId uint64, aux string, params interface{}) error {
	//TODO 后面可升级为更复杂的 subject 规则
	subject := ZkP.Namespace + ".ev.user"
	msg := &MqJsonMsg{
		EventId: evId,
		Guid:    guid,
		Orig:    logicId,
		Ts:      time.Now().Unix(),
		Aux:     aux,
		Params:  params,
	}
	return writeMsg(subject, msg)
}

func write_sys_msg(guid uint64, evId int32, logicId uint64, aux string, params interface{}) error {
	subject := ZkP.Namespace + ".ev.sys"
	msg := &MqJsonMsg{
		EventId: evId,
		Guid:    guid,
		Orig:    logicId,
		Ts:      time.Now().Unix(),
		Aux:     aux,
		Params:  params,
	}
	return writeMsg(subject, msg)
}

func write_mgr_msg(guid uint64, evId int32, logicId uint64, aux string, params interface{}) error {
	subject := ZkP.Namespace + ".ev.mgr"
	msg := &MqJsonMsg{
		EventId: evId,
		Guid:    guid,
		Orig:    logicId,
		Ts:      time.Now().Unix(),
		Aux:     aux,
		Params:  params,
	}
	return writeMsg(subject, msg)
}

func write_def_msg(guid uint64, evId int32, logicId uint64, aux string, params interface{}) error {
	subject := ZkP.Namespace + ".ev.def"
	msg := &MqJsonMsg{
		EventId: evId,
		Guid:    guid,
		Orig:    logicId,
		Ts:      time.Now().Unix(),
		Aux:     aux,
		Params:  params,
	}
	return writeMsg(subject, msg)
}

func writeMsg(subj string, msg *MqJsonMsg) error {
	bytes, err := json.Marshal(msg)
	if err != nil {
		Log.Error("wirte mq", zap.Uint64("guid", msg.Guid), zap.Int32("evId", msg.EventId), zap.Error(err))
		return err
	}
	err = Mq.Pub(subj, bytes)
	if nil != err {
		Log.Error("wirte mq", zap.Uint64("guid", msg.Guid), zap.Int32("evId", msg.EventId), zap.Error(err))
	}
	return err
}
