using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Pivotal.Discovery.Client;
using System.Collections.Generic;
using System.Linq.Expressions;
using System;

namespace Api.SignToken
{
    public class WechatService : IWechatService
    {
        DiscoveryHttpClientHandler _handler;
        ILogger<WechatService> _logger;

        /// <summary>
        /// URL
        /// </summary>
        private const string URL = "http://wechatapi/api/";


        public WechatService(IDiscoveryClient client, ILoggerFactory logFactory)
        {
            _handler = new DiscoveryHttpClientHandler(client, logFactory.CreateLogger<DiscoveryHttpClientHandler>());
            _logger = logFactory.CreateLogger<WechatService>();
        }

        private HttpClient GetClient()
        {
            var client = new HttpClient(_handler, false);
            return client;
        }

        /// <summary>
        /// 发送连接消息
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task<string> SendNewsMsg(string openid, string title, string content, string url)
        {
            var client = GetClient();
            HttpContent postContent = new FormUrlEncodedContent(new Dictionary<string, string>()
            {
               {"openid", openid},
               {"title", title},
               {"content", content},
               {"url", url}
            });
            var response = await client.PostAsync(URL + "sendmessage/sendmessage", postContent);
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="url"></param>
        /// <param name="jsondata"></param>
        /// <param name="templateid"></param>
        /// <returns></returns>
        public async Task<string> SendTemplateMsg(string openid, string url, string jsondata, string templateid)
        {
            var client = GetClient();
            HttpContent postContent = new FormUrlEncodedContent(new Dictionary<string, string>()
            {
               {"openid", openid},
               {"url", url},
               {"jsondata", jsondata},
               {"templateid", templateid}
            });
            var response = await client.PostAsync(URL + "templatemessage/sendtemplatemessage", postContent);
            return await response.Content.ReadAsStringAsync();
        }

        public async Task<string> GetUserInfo(string openid)
        {
            var client = GetClient();
            var result = await client.GetStringAsync(URL + "login/getuserinfo");
            return result;
        }
    }
}
