/****************************************************************
*   作者：liuzl
*   版权：PCXBC
*   创建时间：2022/7/23 16:23:30
*   描述说明：
*
*   修改标识：PC-2022
*   修改描述:
*
*****************************************************************/

using Furion;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Nirvana.Common;
using Senparc.Weixin;
using Senparc.Weixin.Open;
using Senparc.Weixin.Open.OAuthAPIs;
using Senparc.Weixin.Open.QRConnect;
using Senparc.Weixin.Open.WxaAPIs.Sns;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using YBDevice.Entity;

namespace YBDevice.Application.ThirdOpen
{
    /// <summary>
    /// 网页登录处理
    /// </summary>
    public class OpenAppService : Controller
    {
        private static string AppId = Senparc.Weixin.Config.SenparcWeixinSetting.Items["ybdeviceweb"].WeixinAppId;
        private static string AppSecret = Senparc.Weixin.Config.SenparcWeixinSetting.Items["ybdeviceweb"].WeixinAppSecret;
        private static string CDNURL = App.Configuration["CustomSetting:CDNURL"];
        private static string BaseState = "ybdevicepage";

        /// <summary>
        /// 网站二维码登录
        /// </summary>
        /// <param name="url">要跳转的地址,Base64加密</param>
        [Route("web/qr/login")]
        public IActionResult WebLogin(string url = "")
        {
            var redirecturl = $"{CDNURL}/web/qr/info?r={url}";
            var scopes = new OAuthScope[] { OAuthScope.snsapi_login };
            var result = QRConnectAPI.GetQRConnectUrl(AppId, redirecturl, BaseState, scopes);
            return Redirect(result);
        }

        /// <summary>
        /// 授权成功之后的授权处理
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <param name="r"></param>
        /// <returns></returns>
        [Route("web/qr/info")]
        public async Task<IActionResult> InfoAsync(string code, string state, string r = "")
        {
            if (string.IsNullOrEmpty(code))
            {
                return Redirect("/error/reject");
            }
            if (state != BaseState)
            {
                //实际上可以存任何想传递的数据，比如用户ID，并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                return Redirect("/error/reject?msg=验证失败！请从正规途径进入");
            }
            //通过，用code换取access_token
            var result = await QRConnectAPI.GetAccessTokenAsync(AppId, AppSecret, code);
            if (result.errcode != ReturnCode.请求成功)
            {
                return Redirect($"/error/reject?msg=错误：{result.errmsg}");
            }
            OAuthUserInfo userInfo = OAuthApi.GetUserInfo(result.access_token, result.openid);
            var data = userInfo.Adapt<UserBaseInfoS2SDto>().ToJson();
            if (string.IsNullOrEmpty(r))
            {
                return Content(data);
            }
            //对地址进行base64解密
            var url = HttpUtility.UrlDecode(Encoding.UTF8.GetString(Convert.FromBase64String(r)));
            //对data进行URL编码
            data = Convert.ToBase64String(Encoding.UTF8.GetBytes(HttpUtility.UrlEncode(data)));
            if (!url.Contains("info="))
            {
                if (url.Contains("?"))
                {
                    url = $"{url}&info={data}";
                }
                else
                {
                    url = $"{url}?info={data}";
                }
            }
            return Redirect(url);
        }
    }
}