using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;

namespace Mall.Common.Plugin
{
    /// <summary>
    /// 推送客服消息
    /// </summary>
    public class WeChatMessageHelper
    {
        /// <summary>
        /// 发送客服消息
        /// </summary>
        /// <param name="access_token">token</param>
        /// <param name="touser">用户openId</param>
        /// <param name="msgtype">消息类型。text表示文本消息；image表示图片消息；link表示图文链接；miniprogrampage表示小程序卡片。</param>
        /// <param name="obj"></param>
        public static bool SendCustomerMessage(string access_token, string touser, string targetUrl,out string message)
        {
            message = "";
            bool flag = false;
            string responseStr = "";
            try
            {
                if (string.IsNullOrEmpty(access_token))
                {
                    flag = false;
                    return flag;
                }
                //请求路径
                string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}", access_token);
                var postData = new
                {
                    touser = touser,
                    msgtype = "text",
                    text = new
                    {
                        content = "您有一个新订单未支付，请点击链接地址进行支付 " + targetUrl
                    },
                    //link = new
                    //{
                    //    title = "您有一个新订单代支付",
                    //    description = "请打开浏览器支付",
                    //    url = targetUrl,
                    //    thumb_url = "",
                    //}
                };
                string param = JsonHelper.Serialize(postData);
                responseStr = Common.Plugin.HttpHelper.HttpPost(url, param, contenttype: "");
                if (responseStr != null && !string.IsNullOrEmpty(responseStr))
                {
                    JObject jobj = JObject.Parse(responseStr);
                    int errcode = jobj.GetInt("errcode");
                    if (errcode == 0)
                    {
                        flag = true;
                    }
                    else
                    {
                        message = jobj.GetStringValue("errmsg");
                    }
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SendCustomerMessage:result=" + responseStr);
            }
            return flag;
        }
    }
}
