using Furion;
using Furion.DataEncryption;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using Senparc.Weixin.Open;
using Senparc.Weixin.Open.QRConnect;
using System;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using YBDevice.Application;
using YBDevice.Application.CommonInfo;
using YBDevice.Entity;

namespace YBDevice.NWeb.Pages.Login
{
    /// <summary>
    /// 登录
    /// </summary>
    public class IndexModel : LoginPageModel
    {
        public string httpstr = "";
        public string RedirectUrl = "";
        public string state = "ybdevicepage";
        public string cssurl = "";
        public string errmsg = "";
        public string openid = "";
        public string AppId = Senparc.Weixin.Config.SenparcWeixinSetting.Items["ybdeviceweb"].WeixinAppId;
        private string AppSecret = Senparc.Weixin.Config.SenparcWeixinSetting.Items["ybdeviceweb"].WeixinAppSecret;
        private readonly IBusinessService _businessService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public string rurl = "/";
        public IndexModel(IBusinessService businessService, IHttpContextAccessor httpContextAccessor)
        {
            _businessService = businessService;
            _httpContextAccessor = httpContextAccessor;
        }
        public void OnGet(string oid = "",string e="", string returnurl = "")
        {
            string cdnurl = App.Configuration["CustomSetting:CDNURL"];
            httpstr = HttpContext.Request.Scheme;
            RedirectUrl = HttpUtility.UrlEncode($"{cdnurl}/login/success");
            cssurl = $"{cdnurl}/css/loginercode.css";
            openid = oid;
            if (!string.IsNullOrEmpty(e))
            {
                errmsg = HttpUtility.UrlDecode(Encoding.UTF8.GetString(Convert.FromBase64String(e)));
            }
            if (!string.IsNullOrEmpty(returnurl))
            {
                rurl = returnurl;
            }
        }

        /// <summary>
        /// 微信登录回调成功
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> OnGetSuccessAsync(string code, string state)
        {
            if (state != "ybdevicepage")
            {
                errmsg = "验证失败!请从正规途径进入";
                errmsg = Convert.ToBase64String(Encoding.UTF8.GetBytes(HttpUtility.UrlEncode(errmsg)));
                return Redirect($"/Login?e={errmsg}");
            }
            //通过，用code换取access_token
            var result = await QRConnectAPI.GetAccessTokenAsync(AppId, AppSecret, code);
            if (result.errcode != Senparc.Weixin.ReturnCode.请求成功)
            {
                errmsg = result.errmsg;
                errmsg = Convert.ToBase64String(Encoding.UTF8.GetBytes(HttpUtility.UrlEncode(errmsg)));
                return RedirectToPage($"/Login?e={errmsg}");
            }
            //检查绑定的账户
            var resultdata = await _businessService.WXLogin(result.openid);
            if (resultdata.code != ResultState.SUCCESS)
            {
                errmsg = resultdata.message;
                errmsg = Convert.ToBase64String(Encoding.UTF8.GetBytes(HttpUtility.UrlEncode(errmsg)));
                return Redirect($"/Login?oid={result.openid}&e={errmsg}");
            }
            //存储token
            var data = resultdata.data as LoginInfoDto;
            //设置响应报文头
            _httpContextAccessor.HttpContext.Response.Headers["access-token"] = data.Token;
            _httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = data.RefreshToken;

            var claims = JWTEncryption.ReadJwtToken(data.Token)?.Claims;
            // 创建身份信息
            var claimIdentity = new ClaimsIdentity("AuthenticationTypes.Federation");
            claimIdentity.AddClaims(claims);
            var claimsPrincipal = new ClaimsPrincipal(claimIdentity);

            // 设置 HttpContext.User 并登录
            _httpContextAccessor.HttpContext.User = claimsPrincipal;
            await _httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
            TempData["t_token"] = data.Token;
            TempData["t_refreshtoken"] = data.RefreshToken;
            return Redirect("/");
        }
    }
}
