using System;
using System.Collections.Specialized;
using System.Linq;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Siger.ApiCommon.Filters;
using Siger.Middlelayer.Common.Helpers;

namespace Siger.ApiConfig.Controller
{
    [NoTokenValidateFilter]
    [Route("config/[controller]/[action]")]
    [EnableCors("Cors")]
    public class HwAuthController : ControllerBase
    {
        private const string Key = "0be2d185-acb2-4b47-b4af-13d9f64df91d";

        /// <summary>
        /// 华为认证
        /// </summary>
        public HwAuthController()
        {

        }

        [HttpGet]
        public IActionResult CreateAuth(string timeStamp = "")
        {
            var time = string.IsNullOrWhiteSpace(timeStamp) ? DateTime.Now.ToString("yyyyMMddHHmmssfff") : timeStamp;
            var auth = HMACHelper.Encrypt(Key + time, "timeStamp=" + time);

            return new ObjectResult(auth);
        }

        [HttpGet]
        [NoResultFilter]
        public IActionResult Auth(string activity, string authToken)
        {
            var col = Request.Query.ToList();
            var parameters = new NameValueCollection();
            foreach (var pair in col)
            {
                parameters.Add(pair.Key, pair.Value);
            }
            var verifyRet = HMACHelper.verificateRequestParams(parameters, Key);
            if (verifyRet == false)
            {
                return Ok("false");
            }

            if (activity == "newInstance")
            {
                var mobilePhone = HMACHelper.decryptMobilePhoneOrEMail(Key, col.Find(q => q.Key == "mobilePhone").Value.ToString().Replace(" ", "+"));
                var email = HMACHelper.decryptMobilePhoneOrEMail(Key, col.Find(q => q.Key == "email").Value.ToString().Replace(" ", "+"));
                //return
                var ret = new NewInstanceResponseModel
                {
                    instanceId = col.Find(q => q.Key == "businessId").Value,
                    appInfo = new AppUser
                    {
                        frontEndUrl = "https://huawei.siger-data.com",
                        adminUrl = "https://huawei.siger-data.com"
                    }
                };
                ret.appInfo.EncryptUserName(Key, mobilePhone);
                ret.appInfo.EncryptPassword(Key, email);

                var json = JsonConvert.SerializeObject(ret);
                var result = HMACHelper.generateResponseBodySignature(Key, json);
                var header = $"sign_type=\"HMAC-SHA256\", signature=\"{result}\"";
                //添加响应头信息
                Response.Headers.Add("Body-Sign", header);

                return Ok(ret);
            }
            else
            {
                var ret = new RenewResponseModel();
                var json = JsonConvert.SerializeObject(ret);
                var result = HMACHelper.generateResponseBodySignature(Key, json);
                var header = $"sign_type=\"HMAC-SHA256\", signature=\"{result}\"";
                //添加响应头信息
                Response.Headers.Add("Body-Sign", header);
                return Ok(ret);
            }
        }

        [Serializable]
        public class RenewResponseModel
        {
            public string resultCode { get; set; } = "000000";

            public string resultMsg { get; set; } = "success.";
        }

        [Serializable]
        public class NewInstanceResponseModel
        {
            public string resultCode { get; set; } = "000000";

            public string resultMsg { get; set; } = "success.";

            public string instanceId { get; set; }

            /// <summary>
            ///默认 AES256_CBC_PKCS5Padding 
            /// AES128_CBC_PKCS5Padding
            /// </summary>
            //public string encryptType { get; set; } = "AES256_CBC_PKCS5Padding";

            public string encryptType { get; set; } = "1";

            public AppUser appInfo { get; set; }
        }
        public class AppUser
        {
            public string frontEndUrl { get; set; }

            public string adminUrl { get; set; }

            private string _userName;
            private string _password;

            public string userName
            {
                get
                {
                    return _userName;
                }
            }

            public string password { get { return _password; } }

            /// <summary>
            /// 加密用户名
            /// </summary>
            /// <param name="accessKey"></param>
            /// <param name="userName"></param>
            public string EncryptUserName(string accessKey, string userName)
            {
                if (string.IsNullOrEmpty(userName))
                {
                    _userName = null;
                }
                else
                {
                    _userName = HMACHelper.generateSaaSUsernameOrPwd(accessKey, userName, 256);
                }
                return _userName;
            }

            /// <summary>
            /// 加密密码
            /// </summary>
            /// <param name="accessKey"></param>
            /// <param name="password"></param>
            public string EncryptPassword(string accessKey, string password)
            {
                if (string.IsNullOrEmpty(password))
                {
                    _password = null;
                }
                else
                {
                    _password = HMACHelper.generateSaaSUsernameOrPwd(accessKey, password, 256);
                }
                return _password;
            }

            public string memo { get; set; } = "购买后4小时内通过短信息把账号发送给用户";
        }
    }
}