package notice

import (
	log "app.yhyue.com/moapp/jylog"
	"bp.jydev.jianyu360.cn/BP/jynsq/gonsq"
	"encoding/json"
)

type NoticeConfig struct {
	IsOpen          bool //是否开启提示
	IsJsonEncode    bool
	Address, TopPic string
	Id, Title, Text string
}
type Notice struct {
	p *gonsq.Producer
	c NoticeConfig
}

func NewNotice(c NoticeConfig) (n *Notice, err error) {
	if c.IsOpen {
		n = &Notice{
			c: c,
		}
		var producer *gonsq.Producer
		producer, err = gonsq.NewProducer(c.Address, c.TopPic, c.IsJsonEncode)
		if err != nil {
			return
		}
		n.p = producer
		return n, err
	}
	return nil, nil
}

// SendWarnMsg 发送异常通知
func (n *Notice) SendWarnMsg(detail map[string]interface{}) error {
	if n.p == nil {
		return nil
	}
	m := &gonsq.Msg{n.c.Id, n.c.Title, n.c.Text, detail}
	bs, err := json.Marshal(m)
	if err != nil {
		return err
	}

	log.Debugf("模拟发送信息----->%s", string(bs))
	if err := n.p.Publish(bs); err != nil {
		log.Errorf("nsq连接失败 %v", err)
	}
	return nil
}
