package push

import (
	"encoding/json"
	"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
	protocol "openapi/pkg/domain"
	"openapi/pkg/infrastructure/push"
	"openapi/pkg/infrastructure/push/getui"
	"openapi/pkg/infrastructure/utils"
)

//推送信息
func Notification(header *protocol.RequestHeader, request *protocol.PushInfoRequest) (rsp *protocol.PushInfoResponse, err error) {
	var (
		sendData  = make(map[string]interface{})
		clientIds []string
		fc        = func(m json.RawMessage) {
			if len(m) == 0 {
				return
			}
			var (
				id  string
				ids []string
			)
			if e := json.Unmarshal(m, &ids); e == nil {
				clientIds = append(clientIds, ids...)
				return
			}
			if e := json.Unmarshal(m, &id); e == nil {
				if len(id) == 0 {
					return
				}
				clientIds = append(clientIds, id)
				return
			}
			return
		}
		options []push.Option = []push.Option{
			push.DebugModule(true),
			push.AppId(request.AppId),
			push.AppKey(request.AppKey),
			push.AppMasterSecret(request.Secret),
			push.MsgType(request.Type),

			push.Title(request.Title),
			push.Content(request.Content),
			//push.TransmissionContent(utils.JsonAssertString(request.Ext)),
		}
	)

	if v, ok := request.Ext["transData"]; ok {
		options = append(options, push.TransmissionContent(utils.JsonAssertString(v)))
	}
	fc(request.ClientId)
	fc(request.DeviceToken)
	switch len(clientIds) {
	case 0:
		err = protocol.NewCustomMessage(2, "clientId/deviceToken 不能同时为空.")
		return
	case 1:
		options = append(options,
			push.PushType(push.PushToSingle),
			push.ClientId(clientIds[0]),
		)
		break
	default:
		options = append(options,
			push.PushType(push.PushToList),
			push.ClientIds(clientIds),
		)
		break
	}

	var pushService push.INotification = &getui.GetuiNotification{}
	err = pushService.Init(options...)
	if err != nil {
		log.Error(err)
		return
	}
	if err = pushService.Send(sendData); err != nil {
		log.Error(err)
		return
	}
	rsp = &protocol.PushInfoResponse{}
	return
}