using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using LitJson;
using Library;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;

namespace MySystem.Areas.Api.Controllers
{
    [Area("Api")]
    [Route("Api/[controller]/[action]")]
    public class SystemSetController : BaseController
    {
        public SystemSetController(IHttpContextAccessor accessor) : base(accessor)
        {
        }


        #region 验证获取jwt的token

        public JsonResult AppCheck(string mobile)
        { 
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            //生成jwt令牌
            Obj.Add("Token", AppToken(mobile));
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }

        public JsonResult AppCheckTest(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string uuid = data["uuid"].ToString();
            string salt = data["salt"].ToString();
            string u = function.MD5_16(uuid + salt);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            //生成jwt令牌
            Obj.Add("Token", AppToken(u));
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }

        public string AppToken(string u)
        {
            u = "old_" + u;
            string test = function.get_Random(10);
            var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtConfig.JwtSecret)), SecurityAlgorithms.HmacSha256);
            var claims = new Claim[] {
                new Claim(JwtRegisteredClaimNames.Iss,JwtConfig.JwtIss),
                new Claim(JwtRegisteredClaimNames.Aud,test),
                new Claim("Guid", Guid.NewGuid().ToString("D")),
                new Claim(ClaimTypes.Role, "system"),
                new Claim(ClaimTypes.Role, "admin"),
            };
            SecurityToken securityToken = new JwtSecurityToken(
                signingCredentials: securityKey,
                expires: DateTime.Now.AddDays(10),//过期时间
                claims: claims,
                audience: test,
                issuer: u
            );
            RedisDbconn.Instance.Set("utoken:" + u, test);
            RedisDbconn.Instance.SetExpire("utoken:" + u, 3600 * 24 * 10);
            //生成jwt令牌
            return new JwtSecurityTokenHandler().WriteToken(securityToken);
        }

        public string AppTokenV2(int UserId, string DeviceId, string DeviceType)
        {
            string Token = RedisDbconn.Instance.Get<string>("apptoken:" + DeviceId + ":" + DeviceType + ":" + UserId);
            if(!string.IsNullOrEmpty(Token))
            {
                return Token;
            }
            string issuer = "new_" + UserId + "_" + DeviceId + "_" + DeviceType;
            string test = function.get_Random(10);
            var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtConfig.JwtSecret)), SecurityAlgorithms.HmacSha256);
            var claims = new Claim[] {
                new Claim(JwtRegisteredClaimNames.Iss,JwtConfig.JwtIss),
                new Claim(JwtRegisteredClaimNames.Aud,test),
                new Claim("Guid", Guid.NewGuid().ToString("D")),
                new Claim(ClaimTypes.Role, "system"),
                new Claim(ClaimTypes.Role, "admin"),
            };
            SecurityToken securityToken = new JwtSecurityToken(
                signingCredentials: securityKey,
                expires: DateTime.Now.AddDays(10),//过期时间
                claims: claims,
                audience: test,
                issuer: issuer
            );
            RedisDbconn.Instance.Set("utoken:" + issuer, test);
            RedisDbconn.Instance.SetExpire("utoken:" + issuer, 3600 * 24 * 10);
            //生成jwt令牌
            Token = new JwtSecurityTokenHandler().WriteToken(securityToken);
            RedisDbconn.Instance.Set("apptoken:" + DeviceId + ":" + DeviceType + ":" + UserId, Token);
            RedisDbconn.Instance.SetExpire("apptoken:" + DeviceId + ":" + DeviceType + ":" + UserId, 3600 * 24 * 10 - 60);
            return Token;
        }

        #endregion







        #region 获取OSS参数
        public JsonResult OssParam(string value)
        {
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Obj.Add("AccessId", AppConfig.Oss.key);
            Obj.Add("AccessKey", AppConfig.Oss.secret);
            return Json(new AppResultJson() { Status = "-1", Info = "", Data = Obj });
        }

        #endregion




        #region 检查签名是否合法，合法返回1，不合法返回提示信息

        /// <summary>
        /// 检查签名是否合法，合法返回1，不合法返回提示信息
        /// </summary>
        /// <param name="value">请求的参数(json字符串)</param>
        /// <param name="signField">要签名的字段</param>
        /// <returns></returns>
        private string CheckSign(string value, string[] signField)
        {
            JsonData json = JsonMapper.ToObject(value);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < signField.Length; i++)
            {
                dic.Add(signField[i], json[signField[i]].ToString());
            }
            string sign = json["sign"].ToString(); //客户端签名字符串
            return new Sign().sign(dic, sign);
        }

        #endregion

    }
}
