namespace RG3.BO.DB.Services
{
    /// <summary>
    /// 聚合数据请求
    /// </summary>
    public partial class DbExecuteService : IService
    {

        /// <summary>
        /// 获取多 源 数据
        /// </summary>
        /// <param name="pf"></param>
        /// <param name="sqlConfig"></param>
        /// <param name="mkey"></param>
        /// <param name="resField"></param>
        /// <param name="dictionaryUrl"></param>
        /// <returns></returns>
        public async Task<ResultObject<JToken>> QueryMergeData(PFGlobalParameter pf, SqlConfig sqlConfig, string mkey, string resField, Dictionary<string, object> dictionaryUrl, HttpContext httpContext)
        {
            if (sqlConfig.ResponseFieldTemp.Source == null || !sqlConfig.ResponseFieldTemp.Source.Any() || sqlConfig.ResponseFieldTemp.Source.Count() == 0)
            {
                throw new BizException(ErrorCodeConst.FILE_17010.ErrorCode, $"【responseField:source[]未配置");
            }

            List<Task<ResultDetail<JToken>>> lstJtoken = new List<Task<ResultDetail<JToken>>>();
            TaskFactory factory = new TaskFactory();

            foreach (var source in sqlConfig.ResponseFieldTemp.Source)
            {

                Dictionary<string, object> dictionaryP = DictionaryUtil.ConvertDictionaryRemoveJObject(dictionaryUrl);
                if (source.Query != null)
                {
                    DictionaryUtil.SetConvertDictionary(dictionaryP, source.Query);
                }

                lstJtoken.Add(factory.StartNew<ResultDetail<JToken>>(() =>
                {
                    JToken jToken = new JObject();

                    switch (source.DataFromType)
                    {
                        case DataFromType.Api:
                            try
                            {

                                //HttpClient httpClient = _httpClientFactory.CreateClient(HttpClientEnum.Unknown.ToString());
                                //自定义HttpClientHandler实例
                                HttpClientHandler httpClientHandler = source.ClientHandler;
                                if (httpClientHandler == null)
                                {
                                    httpClientHandler = new HttpClientHandler();
                                }

                                //new HttpClientHandler
                                //{
                                //    MaxRequestContentBufferSize = source.MaxRequestContentBufferSize == 0 ? 102400 : source.MaxRequestContentBufferSize,
                                //    Proxy = source.Proxy,
                                //    UseProxy = source.UseProxy

                                //};
                                if (source.ServerCertificateCustomValidationCallback == true)
                                {
                                    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;
                                }
                                //httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;
                                //if (source.AutomaticDecompression != DecompressionMethods.None)
                                //{
                                //    httpClientHandler.AutomaticDecompression = source.AutomaticDecompression;
                                //}
                                //var httpClientHandler = new HttpClientHandler()
                                //{
                                //    MaxRequestContentBufferSize = item.Value.MaxRequestContentBufferSize == 0 ? 102400 : item.Value.MaxRequestContentBufferSize,
                                //    Proxy = item.Value.Proxy,
                                //    UseProxy = item.Value.UseProxy
                                //};
                                //temp.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;
                                //return temp;

                                string result = null;
                                using (HttpClient httpClient = new HttpClient(httpClientHandler))
                                {

                                    Dictionary<string, string> headers = source.Header;
                                    if (headers != null)
                                    {
                                        foreach (KeyValuePair<string, string> header in headers)
                                        {
                                            httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                                        }
                                    }
                                    //设置头部信息 end
                                    StringBuilder sbUrl = new StringBuilder();
                                    sbUrl.Append(source.Url);
                                    //替换地址参数
                                    foreach (var item in dictionaryP)
                                    {
                                        sbUrl.Replace("{" + item.Key + "}", (item.Value ?? "").ToString());
                                    }
                                    //source.Query

                                    switch (source.Method)
                                    {
                                        case "post":
                                            // "{\\"where\\":\\"\\"}";
                                            string postData = JsonUtil.Serialize(source.Body, false, false, false);
                                            StringBuilder sbUrlBody = new StringBuilder();
                                            foreach (var item in dictionaryP)
                                            {
                                                sbUrlBody.Replace("{" + item.Key + "}", (item.Value ?? "").ToString());
                                            }
                                            postData = sbUrlBody.ToString();
                                            Encoding encoding = encoding = EncodeUtil.ConvertEnCoding(source.ContentType ?? "utf8");
                                            //EncodeUtil.ConvertEnCoding() Unicode UTF32 UTF8 UTF7 ASCII ANSI ANSI
                                            string contentType = source.ContentType ?? "application/json";
                                            List<Dictionary<string, object>> datas = new List<Dictionary<string, object>>();
                                            using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
                                            {
                                                if (contentType != null)
                                                {
                                                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
                                                }
                                                using (HttpResponseMessage responseMessage = httpClient.PostAsync(sbUrl.ToString(), content).Result)
                                                {
                                                    Byte[] resultBytes = responseMessage.Content.ReadAsByteArrayAsync().Result;
                                                    result = Encoding.UTF8.GetString(resultBytes);
                                                }
                                            }
                                            break;
                                        case "get":
                                            //.Replace("\\"error_code\\":\\"00\\"", "\\"success\\":true,\\"code\\":0").Replace("defaultValue", "default_value")

                                            if (source.RegisterEncoding == true)
                                            {
                                                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                                            }

                                            if (!string.IsNullOrEmpty(source.ResponseEncoding))
                                            {
                                                result = Encoding.GetEncoding(source.ResponseEncoding).GetString(httpClient.GetByteArrayAsync(sbUrl.ToString()).Result);
                                            }
                                            else
                                            {
                                                result = Encoding.UTF8.GetString(httpClient.GetByteArrayAsync(sbUrl.ToString()).Result);
                                            }
                                            break;
                                        case "form":

                                            break;
                                    }
                                };

                                if (!string.IsNullOrEmpty(result))
                                {
                                    jToken = JsonUtil.Deserialize<JToken>(result);
                                }
                            }
                            catch (Exception ex)
                            {
                                FileUtil.CreateFileAndContent($"~/App_Logs/{pf.OwnerId}/merge/{mkey}-{resField}-api-{DateTime.Now.ToFileTime()}.json", JsonUtil.Serialize(new { dataFromType = "Api", data = jToken, source = source, query = dictionaryUrl, ex = ex }, false, false, false));
                            }

                            break;
                        case DataFromType.ConfigFile:
                            try
                            {
                                JToken resultCache = new JObject();
                                resultCache["success"] = false;
                                StringBuilder sb = new StringBuilder();
                                string detailPath = source.Path;
                                if (!string.IsNullOrEmpty(detailPath))
                                {
                                    sb.Append(detailPath);
                                    foreach (string key in dictionaryUrl.Keys)
                                    {
                                        if (detailPath.Contains($"{key}"))
                                        {
                                            sb.Replace($"@{key}", dictionaryP[key]?.ToString());
                                        }
                                    }
                                }
                                var str = FileUtil.ReadFileAndContentByVirUrl(sb.ToString());
                                resultCache = JsonUtil.Deserialize<JToken>(str);
                                if (resultCache != null && resultCache["data"] != null)
                                {

                                    jToken = resultCache["data"];

                                }
                                else
                                {
                                    jToken = resultCache;
                                }

                            }
                            catch (Exception ex)
                            {
                                FileUtil.CreateFileAndContent($"~/App_Logs/{pf.OwnerId}/merge/{mkey}-{resField}-configfile-{DateTime.Now.ToFileTime()}.json", JsonUtil.Serialize(new { dataFromType = "ConfigFile", data = jToken, source = source, query = dictionaryUrl, ex = ex }, false, false, false));
                            }
                            break;
                        case DataFromType.Json:
                            jToken = source.Data;
                            break;

                        default:

                            try
                            {
                                //dictionaryUrl = NodeJsUtil.SetRequestParams(pf, _configurationBuilderService, _nodeServices, dictionaryUrl, httpContext, mkey, resField, RequestModuleType.List, sqlConfig.ResponseFieldTemp.NjcArgs).Result;


                                jToken = JsonUtil.Deserialize<JArray>(JsonUtil.Serialize(_db.QueryDictionary(pf, source.ConnName, source.SqlV, dictionaryP, ColumnNameCase.Lower), false, false, false));
                            }
                            catch (Exception ex)
                            {
                                FileUtil.CreateFileAndContent($"~/App_Logs/{pf.OwnerId}/merge/{mkey}-{resField}-database-{DateTime.Now.ToFileTime()}.json", JsonUtil.Serialize(new { dataFromType = "DataBase", data = jToken, source = source, query = dictionaryUrl, ex = ex }, false, false, false));
                            }
                            break;

                    }

                    return new ResultDetail<JToken> { Data = jToken, Field = source.Field };
                }));

            }

            ResultObject<JToken> jtokenR = new ResultObject<JToken>();
            jtokenR.Data = new JObject();
            lstJtoken.ForEach(t =>
            {
                jtokenR.Data[t.Result.Field] = t.Result.Data;

            });

            return jtokenR;
        }


    }
}

文档更新时间: 2021-07-04 08:00   作者:admin