using BLL;
using BLL.Common;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FineUIPro.Web
{
    public partial class ssocallback : System.Web.UI.Page
    {
        private string code = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            
            this.code = Request.Params["code"];
            BLL.ErrLogInfo.WriteLog($"获取code={this.code}");
            if (string.IsNullOrEmpty(this.code))
            {
                Response.Redirect("~/login.aspx");
                return;
            }
            var token =  GetAccessToken(this.code);
            var userInfo = getUserInfo(token);
            if (userInfo == null)
            {
                Response.Redirect("~/login.aspx");
                return;
            }
            
            Response.Redirect("~/index.aspx");
        }

        private AccessTokenModel GetAccessToken(string _code)
        {
            string clientId = "9379ad91-eef9-4956-a1ee-8b04bb3d42c8";
            string clientSecret = "iLu8Q~4DRYAn~sMjvO1j.tgRERFWhILvLYRPNc9S";
            string grant_type = "authorization_code";
            string redirect_url = "https://fcl-test.basf-ypc.net.cn/ssocallback.aspx";
            string scope = "profile openid";
            string baseUrl = $"https://login.microsoftonline.com/ecaa386b-c8df-4ce0-ad01-740cbdb5ba55/oauth2/v2.0/token";

            try
            {
                string postData = $"code={code}&client_id={clientId}&client_secret={clientSecret}&grant_type={grant_type}&redirect_uri={redirect_url}&scope={scope}";
                BLL.ErrLogInfo.WriteLog($"请求参数postData={postData}");
                string result = BLL.Common.HttpHelper.HttpPost(baseUrl, postData);
                BLL.ErrLogInfo.WriteLog($"请求API Result={result}");
                var Data = JsonConvert.DeserializeObject<AccessTokenModel>(result);

                return Data;

            }
            catch (Exception ex)
            {
                ErrLogInfo.WriteLog(ex.Message);
            }
            return null;

        }


        private Model.Sys_User getUserInfo(AccessTokenModel token)
        {
            try
            {
                string username = string.Empty;
                string[] toke_split= token.id_token.Split('.');
                var header = Encoding.UTF8.GetString(Base64UrlEncoder.DecodeBytes(toke_split[0]));
                var clamis= Encoding.UTF8.GetString(Base64UrlEncoder.DecodeBytes(toke_split[1]));
                BLL.ErrLogInfo.WriteLog("clamis=" + clamis);
                JObject jo = JObject.Parse(clamis);
                if (jo["cn"] != null)
                {
                    username = jo["cn"].ToString();
                }
                else
                {
                    if (jo["preferred_username"] != null)
                    {
                        string preferred_username = jo["preferred_username"].ToString();
                        username = preferred_username.Split('@')[0];
                    }   
                }
                var info = Funs.DB.Sys_User.Where(t => t.Account == username && t.IsPost == true).FirstOrDefault();
                if (info != null)
                {
                    FormsAuthentication.SetAuthCookie(username, false);
                    Session[SessionName.CurrUser] = info;
                }
              
                return info;
            }
            catch (Exception ex)
            {
                //这里报错了,写入日志
                BLL.ErrLogInfo.WriteLog(ex.Message);    
            }
            return null;
        }

    }

}