using DotNetCore.CAP;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Nirvana.Common;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.Helpers;
using System;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using YBDevice.Core;
using YBDevice.Entity;

namespace YBDevice.NApi.Controllers
{
    public class AuthController : WebBaseController
    {
        private readonly ILoggerService _loggerService;
        private readonly ICapPublisher _capBus;
        public AuthController(ILoggerService loggerService, ICapPublisher capPublisher)
        {
            _loggerService = loggerService;
            _capBus = capPublisher;
        }
        /// <summary>
        /// 授权页面，弹出窗口
        /// </summary>
        /// <param name="r">最终要跳转的url,base64加密</param>
        /// <returns></returns>
        [WeChatFilter]
        public IActionResult Index(string r = "")
        {
            var state = "xbpage";//用于识别请求可靠性
            var redirecturl = $"{Configs.GetString("DOMAIN")}/Auth/page?r={r}";
            var url = OAuthApi.GetAuthorizeUrl(appId, redirecturl, state, OAuthScope.snsapi_userinfo);
            return Redirect(url);
        }
        /// <summary>
        /// 授权页面,静默授权,只能拿到openid
        /// </summary>
        /// <param name="r">最终要跳转的url,base64加密</param>
        /// <returns></returns>
        [WeChatFilter]
        public IActionResult BIndex(string r = "")
        {
            var state = "xbpage";//用于识别请求可靠性
            var redirecturl = $"{Configs.GetString("DOMAIN")}/Auth/page?r={r}";
            var url = OAuthApi.GetAuthorizeUrl(appId, redirecturl, state, OAuthScope.snsapi_base);
            return Redirect(url);
        }
        /// <summary>
        /// 授权成功之后的跳转页面
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <param name="r"></param>
        /// <returns></returns>
        [WeChatFilter]
        public async Task<IActionResult> PageAsync(string code, string state, string r)
        {
            if (string.IsNullOrEmpty(code))
            {
                ViewBag.message = "您拒绝了授权";
                return View(nameof(Reject));
            }
            if (state != "xbpage")
            {
                //实际上可以存任何想传递的数据，比如用户ID，并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                return RedirectToAction(nameof(ErrorInfo), new { msg = "验证失败！请从正规途径进入" });
            }
            //通过，用code换取access_token
            var result = OAuthApi.GetAccessToken(appId, appSecret, code);
            if (result.errcode != ReturnCode.请求成功)
            {
                //记录到日志中
                var msg = $"授权成功之后的跳转页面,code={code},state={state},r={r},result={result.ToJson()}";
                _loggerService.AddLogger(msg);
                return RedirectToAction(nameof(ErrorInfo), new { msg = "错误：" + result.errmsg });
            }
            try
            {
                //已关注，可以得到详细信息
                OAuthUserInfo userInfo = OAuthApi.GetUserInfo(result.access_token, result.openid);
                //昵称会做url编码
                //if (!string.IsNullOrEmpty(userInfo.nickname))
                //{
                //    userInfo.nickname = HttpUtility.UrlEncode(userInfo.nickname, Encoding.UTF8);
                //}
                //如果没有传递url参数,则跳转到默认地址上
                var data = userInfo.Adapt<UserBaseInfoS2SDto>().ToJson();
                if (string.IsNullOrEmpty(r))
                {
                    return Content(data);
                }
                //对地址进行base64解密
                var url = Encoding.UTF8.GetString(Convert.FromBase64String(r));
                if (url.Contains("?"))
                {
                    //对data进行URL编码
                    data = Convert.ToBase64String(Encoding.UTF8.GetBytes(HttpUtility.UrlEncode(data)));
                    url = $"{url}&info={data}";
                }
                else
                {
                    url = $"{url}?info={data}";
                }
                //记录粉丝信息
                await _capBus.PublishAsync("fans.service.update", new YB_WXFans { 
                    HeadImgUrl = userInfo.headimgurl.ToStr(),
                    NickName= userInfo.nickname.ToStr(),
                    Sex = 0,
                    City = "",
                    Country = "",
                    Province = "",
                    FansId = userInfo.unionid.ToStr(),
                    OldOpenId = userInfo.openid.ToStr()
                });
                return Redirect(url);
            }
            catch (Exception ex)
            {
                var msg = $"code={code},state={state},r={r}";
                _loggerService.AddErrorLogger(ex, msg, "授权成功之后的跳转页面");
                return RedirectToAction(nameof(ErrorInfo), new { msg = "错误：" + ex.Message });
            }
        }
        /// <summary>
        /// 拒绝授权页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Reject()
        {
            ViewData["message"] = "授权已拒绝";
            return View();
        }

        /// <summary>
        /// 错误页面
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public IActionResult ErrorInfo(string msg = "")
        {
            ViewBag.message = msg;
            return View();
        }
    }
}
