using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using Library;
using LitJson;
using MySystem.Models;
using System.Net;

namespace MySystem.Areas.Api.Controllers
{
    [Area("Api")]
    [Route("Api/[controller]/[action]")]
    public class UserAuthController : BaseController
    {
        public UserAuthController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }
        
        #region 小程序-获取secret

        public JsonResult GetSecret(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string AppId = data["appId"].ToString(); //小程序AppId
            string AuthCode = data["authCode"].ToString(); //小程序授权码
            Projects pro = db.Projects.FirstOrDefault(m => m.AppId == AppId);
            if(pro == null)
            {
                return Json(new AppResultJson() { Status = "-1", Info = "appid不存在" });
            }
            pro = db.Projects.FirstOrDefault(m => m.AppId == AppId && m.AuthCode == AuthCode);
            if(pro == null)
            {
                return Json(new AppResultJson() { Status = "-1", Info = "授权码不正确" });
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Obj.Add("appSecret", pro.AppSecret); //小程序密钥
            Obj.Add("appSalt", pro.AppIv); //小程序IV
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }

        #endregion

        #region 小程序-授权

        public JsonResult Auth(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string AppId = data["appId"].ToString(); //小程序AppId
            string Code = data["code"].ToString(); //加密Code
            Projects pro = db.Projects.FirstOrDefault(m => m.AppId == AppId);
            if(pro == null)
            {
                return Json(new AppResultJson() { Status = "-1", Info = "appid不存在" });
            }
            string Data = AppDesDecrypt(Code, pro.AppSecret, pro.AppIv);
            if(string.IsNullOrEmpty(Data))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "授权失败" });
            }
            string CheckAppId = Data.Substring(0, 16);
            if(CheckAppId != AppId)
            {
                return Json(new AppResultJson() { Status = "-1", Info = "授权失败" });
            }
            string UserId = Data.Substring(16);
            int PlateformUserId = int.Parse(UserId);
            string OpenId = "kxsmp_" + function.MD5_16(UserId + AppId);
            string Token = function.MD532(Guid.NewGuid().ToString() + "948576");
            UserForProject userFor = db.UserForProject.FirstOrDefault(m => m.PlateformUserId == PlateformUserId && m.AppId == AppId);
            if(userFor == null)
            {
                userFor = db.UserForProject.Add(new UserForProject()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now.AddHours(1),
                    PlateformUserId = PlateformUserId,
                    AppId = AppId,
                    OpenId = OpenId,
                    Token = Token,
                }).Entity;
            }
            else
            {
                userFor.UpdateDate = DateTime.Now.AddHours(1);
                userFor.OpenId = OpenId;
                userFor.Token = Token;
            }
            db.SaveChanges();
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Obj.Add("appToken", Token); //小程序获取用户信息的Token
            Obj.Add("openId", OpenId); //小程序openId
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }

        #endregion

        #region 小程序-获取用户信息

        public JsonResult GetUserInfo(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string AppToken = data["appToken"].ToString(); //小程序获取用户信息的Token
            string OpenId = data["openId"].ToString(); //小程序openId
            DateTime now = DateTime.Now;
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            UserForProject userFor = db.UserForProject.FirstOrDefault(m => m.Token == AppToken && m.OpenId == OpenId && m.UpdateDate > now);
            if(userFor == null)
            {
                return Json(new AppResultJson() { Status = "-1", Info = "获取用户信息失败" });
            }
            PlateformModels.Users user = pdb.Users.FirstOrDefault(m => m.Id == userFor.PlateformUserId) ?? new PlateformModels.Users();
            Obj.Add("mobile", user.Mobile);
            Obj.Add("nickName", user.RealName); //昵称
            Obj.Add("headPhoto", SourceHost + user.HeadPhoto);  //头像
            Obj.Add("makerCode", user.MakerCode);
            string province = "";
            string city = "";
            string district = "";
            if(!string.IsNullOrEmpty(user.Areas))
            {
                string[] AreaList = user.Areas.Split(',');
                if(AreaList.Length > 0) province = AreaList[0];
                if(AreaList.Length > 1) province = AreaList[1];
                if(AreaList.Length > 2) province = AreaList[2];
            }
            Obj.Add("province", province); //省
            Obj.Add("city", city); //市
            Obj.Add("district", district); //区
            Dictionary<string, string> tokens = GetToken(user.Id);
            Obj.Add("accessToken", tokens["access_token"]);
            Obj.Add("refreshToken", tokens["refresh_token"]);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, string> GetToken(int UserId)
        {
            Dictionary<string, string> obj = new Dictionary<string, string>();
            string access_token = "";
            string refresh_token = "";

            PlateformModels.WebCMSEntities db = new PlateformModels.WebCMSEntities();
            PlateformModels.Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new PlateformModels.Users();
            PlateformModels.UserMoveInfo userMove = db.UserMoveInfo.FirstOrDefault(m => m.UserId == UserId) ?? new PlateformModels.UserMoveInfo();

            string basic = "kxs_app:MxYh7A9Gkngp5YxWwKkuKlBGUaAIvpTn";
            basic = Convert.ToBase64String(Encoding.UTF8.GetBytes(basic));
            Dictionary<string, string> header = new Dictionary<string, string>();
            header.Add("Authorization", "Basic " + basic);
            string url = "https://apigateway.kexiaoshuang.com/v1/kxs/userServer/oauth2/token?scope=server&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer";
            Dictionary<string, string> req = new Dictionary<string, string>();
            req.Add("username", user.Mobile);
            req.Add("password", userMove.LoginPwd);
            string reqJson = Newtonsoft.Json.JsonConvert.SerializeObject(req);
            function.WriteLog("reqJson:" + reqJson, "拦截器日志");
            string jsonData = AesEncrypt(reqJson);
            function.WriteLog(str: "jsonData:" + jsonData, "拦截器日志");
            jsonData = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonData));
            string result = PostWebRequest(url, jsonData, header);
            function.WriteLog(str: "result:" + result, "拦截器日志");
            JsonData jsonObj = JsonMapper.ToObject(result);
            if(jsonObj["status"].ToString() == "1")
            {
                access_token = jsonObj["data"]["access_token"].ToString();
                refresh_token = jsonObj["data"]["refresh_token"].ToString();
            }
            obj.Add("access_token", access_token);
            obj.Add("refresh_token", refresh_token);
            return obj;
        }
        public string PostWebRequest(string postUrl, string paramData, Dictionary<string, string> headers)
        {
            string ret = string.Empty;
            try
            {
                function.WriteLog(DateTime.Now.ToString(), "请求开店宝API日志");
                function.WriteLog(postUrl, "请求开店宝API日志");
                function.WriteLog(paramData, "请求开店宝API日志");
                byte[] postData = System.Text.Encoding.UTF8.GetBytes(paramData);
                // 设置提交的相关参数 
                HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
                System.Text.Encoding myEncoding = System.Text.Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = "application/json";
                foreach (string key in headers.Keys)
                {
                    request.Headers.Add(key, headers[key]);
                }
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";

                request.ContentLength = postData.Length;

                // 提交请求数据 
                Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();
                HttpWebResponse response;
                Stream responseStream;
                StreamReader reader;
                string srcString;
                response = request.GetResponse() as HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
                srcString = reader.ReadToEnd();
                ret = srcString;   //返回值赋值
                reader.Close();
                function.WriteLog(srcString, "请求开店宝API日志");
            }
            catch (WebException ex)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                Stream myResponseStream = response.GetResponseStream();
                //获取响应内容
                StreamReader myStreamReader = new StreamReader(myResponseStream);
                ret = myStreamReader.ReadToEnd();
                myResponseStream.Close();
            }
            catch (Exception ex)
            {
                ret = "fail";
                function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "请求开店宝API异常");
            }
            return ret;
        }
        public string AesEncrypt(string str)
        {
            if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            string key = "CBTU1dD4Kd5pyiGWTsI10jRQ3SvKusSV";
            string iv = "DYgjCEIMVrj2W9xN";

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                IV = Encoding.UTF8.GetBytes(iv),
                Mode = System.Security.Cryptography.CipherMode.CBC,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };
            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        #endregion




        #region 3DES解密

        private string AppDesDecrypt(string encryptedText, string key, string iv)
        {
            string decryptedText = "";
            try
            {
                byte[] keyArray;
                byte[] ivArray;
                byte[] encryptedTextArray;
                byte[] decryptedTextArray;
                TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();

                keyArray = UTF8Encoding.UTF8.GetBytes(key.Substring(0, 24));
                ivArray = UTF8Encoding.UTF8.GetBytes(iv);
                encryptedTextArray = Convert.FromBase64String(encryptedText);

                tripleDES.Key = keyArray;
                tripleDES.IV = ivArray;

                ICryptoTransform decryptor = tripleDES.CreateDecryptor(tripleDES.Key, tripleDES.IV);

                using (MemoryStream ms = new MemoryStream(encryptedTextArray))
                {
                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader(cs))
                        {
                            decryptedTextArray = Encoding.UTF8.GetBytes(sr.ReadToEnd());
                        }
                    }
                }
                decryptedText = Encoding.UTF8.GetString(decryptedTextArray);
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "3DES解密异常");
            }
            return decryptedText;
        }

        #endregion
    }
}