using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.MP.Entities;

namespace WechatApi.Controllers
{
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class SendMessageController : BaseController
    {
        private readonly string AppId;
        private readonly string AppSecret;
        private readonly string MessageUrl;
        public SendMessageController(IConfiguration configuration)
        {
            AppId = configuration["WechatStatic:AppId"];
            AppSecret = configuration["WechatStatic:AppSecret"];
            MessageUrl = configuration["WechatStatic:MessageUrl"];
        }

        /// <summary>
        /// 发送模板消息【需要安全验证】
        /// </summary>
        /// <returns></returns>
        [HttpGet("testsend")]
        public async Task<IActionResult> TestSendAsync(string openid)
        {
            List<Article> articles = new List<Article>();
            Article ae = new Article();
            ae.Title = "标题";
            ae.Url = "http://www.baidu.com";
            ae.Description = "内容";
            articles.Add(ae);

            var accessToken = AccessTokenContainer.GetAccessToken(AppId);
            var result = await CustomApi.SendNewsAsync(accessToken, openid, articles);
            return Success("OK", result);
        }

        /// <summary>
        /// 发送模板消息【需要安全验证】
        /// </summary>
        /// <returns></returns>
        [HttpPost("sendmessage")]
        public async Task<IActionResult> SendMessageAsync(string openid,  string title, string content,string url)
        {
            if (MessageUrl.IndexOf("?") != -1)
            {
                url = MessageUrl + "&" + url;
            }
            else
            {
                url = MessageUrl + "?" + url;
            }

            List<Article> articles = new List<Article>();
            Article ae = new Article();
            ae.Title = title;
            ae.Url = url;
            ae.Description = content;
            articles.Add(ae);

            var accessToken = AccessTokenContainer.GetAccessToken(AppId);
            var result = await CustomApi.SendNewsAsync(accessToken, openid, articles);

            return Success("OK", result);
        }
    }
}