package msg

import (
	"fmt"
	"git.rosy.net.cn/jx-callback/business/jxutils/enterprise_msg"

	"git.rosy.net.cn/jx-callback/business/jxutils/ddmsg"
	"git.rosy.net.cn/jx-callback/business/jxutils/weixinmsg"
	"git.rosy.net.cn/jx-callback/business/model"

	"git.rosy.net.cn/baseapi/platformapi/dingdingapi"
	"git.rosy.net.cn/jx-callback/business/auth2"
	"git.rosy.net.cn/jx-callback/business/auth2/authprovider/dingding"
	"git.rosy.net.cn/jx-callback/business/auth2/authprovider/weixin"
	"git.rosy.net.cn/jx-callback/globals"
)

// todo msgType不依赖于钉钉
func SendUserMessage(msgType string, user *model.User, title, content string) (err error) {
	userID := user.GetID()
	authList, err := auth2.GetUserBindAuthInfo(userID)
	findOneMethod := false
	if err == nil {
		for _, auth := range authList {
			if auth.Type == dingding.AuthTypeStaff || auth.Type == weixin.AuthTypeMP {
				findOneMethod = true
				if len(content) > dingdingapi.MaxWorkContentLen {
					content = content[:dingdingapi.MaxWorkContentLen-4] + "..."
				}
				if auth.Type == dingding.AuthTypeStaff {
					if title != "" {
						content = title + "\n" + content
					}
					if err2 := ddmsg.SendDDUserMessage(msgType, auth.AuthID, title, content); err2 != nil {
						if msgType == "txt" {
							msgType = "text"
						}
						err = enterprise_msg.SendEnterpriseUserMessage(msgType, auth.AuthID, title, content)
					}
				} else if auth.Type == weixin.AuthTypeMP && msgType != dingdingapi.MsgTypeMarkdown {
					err = weixinmsg.NotifyStoreStatusChanged(auth.AuthID, title, content)
				}
				break
			}
		}
	}
	if !findOneMethod {
		err = fmt.Errorf("用户[%s]找不到至少一个有效的通讯方式", userID)
	}
	if err != nil {
		globals.SugarLogger.Infof("SendUserMessage userID:%s, title:%s, content:%s failed with error:%v", userID, title, content, err)
	}
	return err
}
