using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Fuel.Payment.Service.AllInPayProcessor.AllInPay.Util
{
    public class AppUtil
    {
        /// <summary>
        /// 将参数排序组装
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static String BuildParamStr(Dictionary<String, String> param)
        {
            if (param == null || param.Count == 0)
            {
                return "";
            }
            Dictionary<String, String> ascDic = param.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
            StringBuilder sb = new StringBuilder();
            foreach (var item in ascDic)
            {
                if (!string.IsNullOrEmpty(item.Value))
                {
                    sb.Append(item.Key).Append("=").Append(item.Value).Append("&");
                }

            }

            return sb.ToString().Substring(0, sb.ToString().Length - 1);
        }

        public static String BuildParamStr(Dictionary<String, object> param)
        {
            if (param == null || param.Count == 0)
            {
                return "";
            }
            Dictionary<String, object> ascDic = param.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
            StringBuilder sb = new StringBuilder();
            foreach (var item in ascDic)
            {
                if (item.Value != null)
                {
                    if (item.Value is string)
                    {
                        sb.Append(item.Key).Append("=").Append(item.Value).Append("&");
                    }
                    else if (item.Value is List<ConsumeType>)
                    {
                        sb.Append(item.Key).Append("=").Append(JsonConvert.SerializeObject(item.Value)).Append("&");
                    }
                    else if (item.Value is OilStation)
                    {
                        sb.Append(item.Key).Append("=").Append(JsonConvert.SerializeObject(item.Value)).Append("&");
                    }    
                    else
                    {
                        sb.Append(item.Key).Append("=").Append(JsonConvert.SerializeObject(item.Value)).Append("&");
                        // unexpected type
                    }
                }
                
            }

            return sb.ToString().Substring(0, sb.ToString().Length - 1);
        }

        public static String signParam(Dictionary<String, String> param, String appkey)
        {
            if (param == null || param.Count == 0)
            {
                return "";
            }
            param.Add("key", appkey);
            String blankStr = BuildParamStr(param);
            return MD5Encrypt(blankStr);

        }

        public static String signParam(Dictionary<String, object> param, String appkey, bool lowerCase = false)
        {
            if (param == null || param.Count == 0)
            {
                return "";
            }
            param.Add("key", appkey);
            string blankStr = BuildParamStr(param);
            return lowerCase ? MD5Encrypt(blankStr).ToLower() : MD5Encrypt(blankStr);
        }

        public static bool validSign(Dictionary<String, String> param, String appkey)
        {
            String signRsp = param["sign"];
            param.Remove("sign");
            String sign = signParam(param, AppConstants.APPKEY);
            return sign.ToLower().Equals(signRsp.ToLower());

        }

        /// <summary>
        /// 将实体转化为json
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ObjectToJson(object o)
        {
            string json = JsonConvert.SerializeObject(o);
            return json;
        }

        /// <summary>
        /// md5加签
        /// </summary>
        /// <param name="strText"></param>
        /// <returns></returns>
        public static string MD5Encrypt(string strText)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            //var str1 = "appId=test&bizContent={\"amount\":1,\"backUrl\":\"http://www.baidu.com\",\"bizOrderNo\":\"1607592344575\",\"consumeTypes\":[{\"amount\":1,\"type\":\"C0001\"}],\"limitPay\":\"no_credit\",\"oilStation\":{\"oilGunNo\":\"1\",\"oilStationNo\":\"S0012\",\"oilStationPersonNo\":\"\"},\"payType\":\"SCAN_WEIXIN\",\"remark\":\"\",\"shiftsMask\":\"S0012001\",\"shiftsTime\":\"20201210\",\"sysId\":\"1902271423530473681\"}&charset=utf-8&key=123456&service=oil.pay.apply&signType=MD5&timestamp=20201210172545&version=1.0";
            //byte[] result1 = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str1));
            //var s = BitConverter.ToString(result1).Replace("-", "");

            byte[] result = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strText));
            var resultStr = BitConverter.ToString(result).Replace("-", "");
            return resultStr;
        }
    }
}
