using LQKJ.WebApi.Stub;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace LQKJ.K3.WebsiteAndSignUpSystem.WebApi
{
    public class Utility
    {
        //token过期时间（分）
        private static int OverdueSum=120;
        public static string CreateToken(string FID,string FNumber,string FUserPhone)
        {
            string Str = "LQKJ"+","+FID + "," + FNumber + ","+ FUserPhone+"," + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            return Encrypt(Str);

        }
        public static ApiResult DecryptToken(string TokenStr)
        {
            ApiResult apiResult = new ApiResult();
            try
            {
                if (string.IsNullOrWhiteSpace(TokenStr))
                {
                    apiResult.code = 501; ;//Token错误
                    apiResult.msg = "未登陆，请登陆后操作";
                }
                string TokenDec = Decrypt(TokenStr);
                if (TokenDec.Substring(0, 4) != "LQKJ")
                {
                     apiResult.code = 501; ;//Token错误
                     apiResult.msg = "身份验证失败，请重新登陆";
                }
                string[] Tokenstrs = TokenDec.Split(',');
                if (Tokenstrs.Length != 5)
                {
                    apiResult.code = 501;//Token错误
                    apiResult.msg = "身份验证失败，请重新登陆";
                }
                Token token = new Token { FID = Tokenstrs[1], FNumber = Tokenstrs[2], FUserPhone = Tokenstrs[3], datetime = DateTime.Parse(Tokenstrs[4]) };
                if (token.datetime.AddMinutes(OverdueSum) < DateTime.Now)
                {
                    apiResult.code = 501;
                    apiResult.msg = "登陆身份过期，请重新登陆";
                }
                else
                {
                    apiResult.code = 200;
                    apiResult.msg = "成功";
                    apiResult.data = token;
                }
            }
            catch (Exception)
            {
                apiResult.code = 501; ;//Token错误
                apiResult.msg = "身份验证失败，请重新登陆";
            }
            return apiResult;
        }
        /// <summary>
        /// 查
        /// </summary>
        /// <param name="TokenStr"></param>
        /// <returns></returns>
        public static SQLResult DecryptTokens(string TokenStr)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                if (string.IsNullOrWhiteSpace(TokenStr))
                {
                    sqlResult.code = "501"; ;//Token错误
                    sqlResult.msg = "未登陆，请登陆后操作";
                }
                string TokenDec = Decrypt(TokenStr);
                if (TokenDec.Substring(0, 4) != "LQKJ")
                {
                    sqlResult.code = "501"; ;//Token错误
                    sqlResult.msg = "身份验证失败，请重新登陆";
                }
                string[] Tokenstrs = TokenDec.Split(',');
                if (Tokenstrs.Length != 5)
                {
                    sqlResult.code = "501";//Token错误
                    sqlResult.msg = "身份验证失败，请重新登陆";
                }
                Token token = new Token { FID = Tokenstrs[1], FNumber = Tokenstrs[2], FUserPhone = Tokenstrs[3], datetime = DateTime.Parse(Tokenstrs[4]) };
                if (token.datetime.AddMinutes(OverdueSum) < DateTime.Now)
                {
                    sqlResult.code = "501";
                    sqlResult.msg = "登陆身份过期，请重新登陆";
                }
                else
                {
                    sqlResult.code = "200";
                    sqlResult.msg = "成功";
                    sqlResult.data = token;
                }
            }
            catch (Exception)
            {
                sqlResult.code = "500"; ;//Token错误
                sqlResult.msg = "身份验证失败，请重新登陆";
            }
            return sqlResult;
        }
        // 常量16字节密钥（128位）
        private static readonly byte[] ConstantKey = Encoding.UTF8.GetBytes("lqkj456789A10086");

        // 常量16字节初始化向量（128位）
        private static readonly byte[] ConstantIV = Encoding.UTF8.GetBytes("lqkj456789A10087");
        public static string Encrypt(string plainText)
        {
            using (Aes aes = Aes.Create())
            {
                aes.Key = ConstantKey;
                aes.IV = ConstantIV;

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
                        cryptoStream.Write(plainBytes, 0, plainBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        return Convert.ToBase64String(memoryStream.ToArray());
                    }
                }
            }
        }

        public static string Decrypt(string encryptedText)
        {
            using (Aes aes = Aes.Create())
            {
                aes.Key = ConstantKey;
                aes.IV = ConstantIV;

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
                        cryptoStream.Write(encryptedBytes, 0, encryptedBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        return Encoding.UTF8.GetString(memoryStream.ToArray());
                    }
                }
            }
        }
    }
}
