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"></param>
        /// <param name="touser"></param>
        /// <param name="pushUrlList"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static bool SendCustomerMessage(string access_token, string touser, List<string> pushUrlList,out string message)
        {
            message = "";
            bool flag = false;
            string responseStr = "";
            try
            {
                if (string.IsNullOrEmpty(access_token))
                {
                    flag = false;
                    return flag;
                }
                string content = string.Format("您有{0}个新订单未支付，请点击链接地址进行支付! ", pushUrlList.Count);
                int index = 1;
                foreach (var item in pushUrlList)
                {
                    content += string.Format("订单{0}：" + item + "  \n", index);
                    index++;
                }
                //请求路径
                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 = content
                    },
                    //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;
        }
    }
}
