using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
using System.Net;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RestSharp;
using NLog;
using static IronPython.Modules._ast;
using Common;
using BLW_Log.Models;

namespace BLW_Log.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {



        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        public IConfiguration? configuration { get; set; }
        public LoginController(IConfiguration _configuration)
        {
            configuration = _configuration;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [HttpPost]
        public ReturnInfo Login([FromBody] LoginData data)
        {

            ReturnInfo res = new ReturnInfo();

            try
            {
                string? password = data.password;
                string? username = data.username;

                var result = StaticData.scope1.GetVariable("LoginData");

                var str= System.Text.Json.JsonSerializer.Serialize(result);
                var dic= System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string>>(str);

                string TokenString = "";
                if (result != null)
                {
                    if (dic.TryGetValue(username, out string pwd))
                    {
                        if (pwd.Equals(password))
                        {
                            TokenString = GetToken(data);
                            res.isok = true;
                            res.response = TokenString;
                        }
                    }
                    else
                    {
                        res.isok = false;
                        res.message = "密码错误";
                    }
                }
                else
                {
                    res.isok = false;
                    res.message = "用户不存在";
                }
            }
            catch (Exception ex)
            {
                res.message = ex.Message;
                res.isok = false;
            }
            return res;
        }

        private string GetToken(LoginData? entity)
        {
            string TokenString;
            var claims = new Claim[]
            {
                //new Claim(ClaimTypes.NameIdentifier, entity.Id.ToString()),
                //new Claim(ClaimTypes.MobilePhone, entity.Mobile.ToString()),
                //new Claim(ClaimTypes.Name, entity.Username)
            };

            var secretByte = Encoding.UTF8.GetBytes(configuration["JwT:SecretKey"]);
            var signingKey = new SymmetricSecurityKey(secretByte);
            var a = SecurityAlgorithms.HmacSha256;

            var signingCredentials = new SigningCredentials(signingKey, a);

            var token = new JwtSecurityToken(
                issuer: configuration["JwT:Issuer"],
                audience: configuration["JwT:Audience"],//接收
                claims: claims,//存放的用户信息
                notBefore: DateTime.UtcNow,//发布时间
                expires: DateTime.UtcNow.AddHours(12),
                signingCredentials: signingCredentials
           //有效期设置为1天signingCredentials //数字名
           );
            TokenString = new JwtSecurityTokenHandler().WriteToken(token);
            return TokenString;
        }

        [HttpPost()]
        [Authorize()]
        public string Helloooo()
        {
            return "hello";
        }


    }
    public class LoginData
    {
        public string? username { get; set; }
        public string? password { get; set; }
    }

    internal class TblUtsManageUser
    {
        public object Id { get; internal set; }
        public bool IsAdmin { get; internal set; }
        public string? UserName { get; internal set; }
    }
}
