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;
using Senparc.Weixin.MP.AdvancedAPIs;
using MadRunFabric.Model;
using Api.SignToken;
using Microsoft.Extensions.Logging;
using NLog;
using Microsoft.AspNetCore.Cors;
using Senparc.Weixin.MP.Containers;
using Microsoft.Net.Http.Headers;
using Microsoft.Extensions.Caching.Distributed;

namespace WechatApi.Controllers
{
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class LoginController : BaseController
    {
        private readonly string AppId;
        private readonly string AppSecret;
        private readonly string FocusUrl;
        private readonly string QRCodeTimeOut;
        private readonly IDistributedCache _cache;
        private readonly ISignTokenService _signTokenService;
        static Logger Logger = LogManager.GetCurrentClassLogger();
        public LoginController(IConfiguration configuration, IDistributedCache cache, ISignTokenService signTokenService)
        {
            AppId = configuration["WechatStatic:AppId"];
            AppSecret = configuration["WechatStatic:AppSecret"];
            FocusUrl = configuration["WechatStatic:FocusUrl"];
            QRCodeTimeOut = configuration["WechatStatic:QRCodeTimeOut"];
            _signTokenService = signTokenService;
            _cache = cache;
        }

        /// <summary>
        /// 获取UserInfo 和 Token
        /// </summary>
        /// <param name="wxLoginDto"></param>
        /// <returns></returns>
        [HttpPost("getuserinfotoken")]
        public async Task<IActionResult> GetUserInfoTokenAsync(string code)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                var refurl = Request.Headers[HeaderNames.Referer].ToString();
                var url = OAuthApi.GetAuthorizeUrl(AppId, refurl, "qwertyuidfghjkl", OAuthScope.snsapi_userinfo);
                return Redirect("跳转", url);
            }
            var access = await OAuthApi.GetAccessTokenAsync(AppId, AppSecret, code);
            var userinfo = await OAuthApi.GetUserInfoAsync(access.access_token, access.openid);

            #region 发送请求获取系统内验证Token
            var res = await _signTokenService.Wechat_LoginAsync(userinfo.openid, userinfo.nickname, userinfo.headimgurl);
            #endregion

            return Content(res);
        }

        /// <summary>
        /// 获取UserInfo
        /// </summary>
        /// <param name="wxLoginDto"></param>
        /// <returns></returns>
        [HttpGet("getuserinfo")]
        public IActionResult GetUserInfoAsync(string openid)
        {
            var accessToken = AccessTokenContainer.GetAccessToken(AppId);
            Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson userInfos = UserApi.Info(accessToken, openid);

            return Success("成功", userInfos);
        }

        /// <summary>
        /// 获取二维码图片
        /// </summary>
        /// <param name="wxLoginDto"></param>
        /// <returns></returns>
        [HttpGet("getqrcode")]
        public async Task<IActionResult> GetQRCodeAsync(string usercode)
        {
            string url= await _cache.GetStringAsync($"qrcode{usercode}");
            if (string.IsNullOrEmpty(url))
            {
                int timeout = int.Parse(QRCodeTimeOut);
                var ExpirationTime = DateTime.Now.AddSeconds(timeout);
                var accessToken = AccessTokenContainer.GetAccessToken(AppId);
                var cre = await QrCodeApi.CreateAsync(accessToken, timeout, 1, QrCode_ActionName.QR_STR_SCENE, usercode);
                url = QrCodeApi.GetShowQrCodeUrl(cre.ticket);

                DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();
                options.AbsoluteExpiration = ExpirationTime;

                await _cache.SetStringAsync($"qrcode{usercode}", url, options);
            }

            return Success("成功", url);
        }
    }
}
