using CommonHelper;
using GasolineBlend.DAL;
using GasolineBlend.Entity;
using Microsoft.Office.Interop.Word;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static GasolineBlend.Entity.SubsidyDataPage;
using RegexMatch = System.Text.RegularExpressions.Match;
using NPOIMatch = NPOI.SS.Formula.Functions.Match;
using static GasolineBlend.Entity.CozePage;
namespace GasolineBlend.BLL
{
public class SubsidyDataBLL
{
private SubsidyDataDAL _sub = new SubsidyDataDAL();
private SubsidyInquiryRecordDAL _sir = new SubsidyInquiryRecordDAL();
private OrderDataDAL _acc = new OrderDataDAL();
///
/// 获取用益信托网记录数据
///
///
public PaginatedResult GetSubsidyDataList(int PageNumber, int PageSize, string Keyword, string CompanyName)
{
// 设置API的URL
string apiUrl = "http://open.api.tianyancha.com/services/open/ic/baseinfoV3/2.0";
// 设置授权令牌
string authToken = "5d4c3939-53bb-422f-8ab6-91865b958e3a";
// 设置请求的JSON内容
string Region = "";
string City = "";
// 创建HttpClient实例
using (var client = new HttpClient())
{
// 添加Authorization头部
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authToken);
// 添加keyword参数到查询字符串
var queryString = $"?keyword={Uri.EscapeDataString(CompanyName)}";
// 构建完整的URL
string fullUrl = apiUrl + queryString;
try
{
// 发送GET请求
HttpResponseMessage response = client.GetAsync(fullUrl).Result;
// 确保响应状态为成功
response.EnsureSuccessStatusCode();
// 读取响应内容
string responseBody = response.Content.ReadAsStringAsync().Result;
// 将JSON字符串反序列化为JObject
JObject jsonData = JObject.Parse(responseBody);
if ((int)jsonData["error_code"] != 0) {
return null;
}
// 访问嵌套的JSON属性
City = (string)jsonData["result"]["city"];
Region = (string)jsonData["result"]["district"];
}
catch (HttpRequestException e)
{
LogHelper.Write(Level.Error, "获取政策列表数据 GetSubsidyDataListAPi查询", e, OperatorProvider.Instance.Current == null ? "GuestEx" : OperatorProvider.Instance.Current.LoginName);
}
}
string Province = _sub.GetProvince(City, Region);
int totalCount = _sub.GetSubsidyDataCount(Keyword, City, Region, Province);
int totalPage = (int)Math.Ceiling((double)totalCount / PageSize);
List totalData = _sub.GetSubsidyDataList(PageNumber, PageSize, Keyword, City, Region, Province);
return new PaginatedResult(totalData, totalCount, totalPage);
}
public List GetSubsidyDataFilter(string Keyword, string CompanyName)
{
// 设置API的URL
string apiUrl = "http://open.api.tianyancha.com/services/open/ic/baseinfoV3/2.0";
// 设置授权令牌
string authToken = "5d4c3939-53bb-422f-8ab6-91865b958e3a";
// 设置请求的JSON内容
string Region = "";
string City = "";
// 创建HttpClient实例
using (var client = new HttpClient())
{
// 添加Authorization头部
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authToken);
// 添加keyword参数到查询字符串
var queryString = $"?keyword={Uri.EscapeDataString(CompanyName)}";
// 构建完整的URL
string fullUrl = apiUrl + queryString;
try
{
// 发送GET请求
HttpResponseMessage response = client.GetAsync(fullUrl).Result;
// 确保响应状态为成功
response.EnsureSuccessStatusCode();
// 读取响应内容
string responseBody = response.Content.ReadAsStringAsync().Result;
// 将JSON字符串反序列化为JObject
JObject jsonData = JObject.Parse(responseBody);
if ((int)jsonData["error_code"] != 0)
{
return null;
}
// 访问嵌套的JSON属性
City = (string)jsonData["result"]["city"];
Region = (string)jsonData["result"]["district"];
}
catch (HttpRequestException e)
{
LogHelper.Write(Level.Error, "获取政策列表数据 GetSubsidyDataListAPi查询", e, OperatorProvider.Instance.Current == null ? "GuestEx" : OperatorProvider.Instance.Current.LoginName);
}
}
string Province = _sub.GetProvince(City, Region);
List totalData = _sub.GetSubsidyDataFilter( Keyword, City, Region, Province);
return totalData;
}
//public string GetMoonshot(string CompanyName)
//{
// string _apiKey = "sk-Lec41LGc7aV8KdFzOCiJQIM9A8bsbBk5KumvqBSyfeW9EXec"; // 替换为你的API密钥
// string _baseUrl = "https://api.moonshot.cn/v1"; // 确保URL是正确的
// string model = "moonshot-v1-32k";
// string systemMessage = "你是 Kimi,由 Moonshot AI 提供的人工智能助手,你更擅长中文和英文的对话。你会为用户提供安全,有帮助,准确的回答。同时,你会拒绝一切涉及恐怖主义,种族歧视,黄色暴力等问题的回答。Moonshot AI 为专有名词,不可翻译成其他语言。";
// string userMessage = $"{CompanyName}获得了哪些荣誉与资质?请列举一下,以Json格式输出。";
// double temperature = 0.3;
// var messages = new[]
// {
// new { role = "system", content = systemMessage },
// new { role = "user", content = userMessage }
//};
// var requestContent = new
// {
// model = model,
// messages = messages,
// temperature = temperature
// };
// var json = JsonConvert.SerializeObject(requestContent);
// var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
// using (var client = new HttpClient())
// {
// try
// {
// // 添加API密钥到请求头
// client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
// // 发送POST请求
// HttpResponseMessage response = client.PostAsync(_baseUrl + "/chat/completions", httpContent).Result;
// if (response.IsSuccessStatusCode)
// {
// string responseContent = response.Content.ReadAsStringAsync().Result;
// var completion = JsonConvert.DeserializeObject(responseContent);
// return completion.choices[0].message.content.ToString();
// }
// else
// {
// return $"Error: {response.StatusCode}";
// }
// }
// catch (Exception e)
// {
// return $"Exception caught: {e.Message}";
// }
// }
//}
public CozeResult GetPolicyApplied(string CompanyName)
{
try
{
// 设置API的URL
string apiUrl = "https://api.coze.cn/v1/workflow/run";
// 设置授权令牌
string bearerToken = "pat_58jGFdi1EjYOZnLCJRe162Mq3E9Xary8gyXzTDKEvUn3wqXNi9WzGktFgHPK1oUa";
// 设置请求的JSON内容
string jsonContent = $@"{{
""workflow_id"": ""7427036924374892570"",
""parameters"": {{
""BOT_USER_INPUT"": """",
""keyword"": ""{CompanyName}获得了哪些荣誉与资质与公司成立日期""
}}
}}";
using (HttpClient client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, apiUrl)
{
Content = new StringContent(jsonContent, Encoding.UTF8, "application/json")
};
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearerToken);
// 使用Task.Run来运行异步操作,并使用.Result获取结果
HttpResponseMessage response = System.Threading.Tasks.Task.Run(() => client.SendAsync(request)).Result;
if (response.IsSuccessStatusCode)
{
// 读取响应内容
string responseContent = System.Threading.Tasks.Task.Run(() => response.Content.ReadAsStringAsync()).Result;
// 解析JSON字符串
var rootObject = JObject.Parse(responseContent);
var codeToken = rootObject["code"].ToString();
int codeValue = int.Parse(codeToken);
if (codeValue != 0 )
{
var Serror = "[{ \"id\": -2, \"name\": -2, \"date\": -2}]";
var Jerror = JArray.Parse(Serror);
var Terror = Jerror.ToObject>();
var Error = new CozeResult(Terror);
return Error;
}
var data = rootObject["data"].ToString();
// 解析data字段中的JSON字符串
var dataObject = JObject.Parse(data);
// 提取output字段
var output = dataObject["output"];
// 修正JSON字符串中的属性分隔符
var outputJson = output.ToString().Replace(":", ":");
// 修正JSON字符串中的属性分隔符
outputJson = outputJson.ToString().Replace(",", ",");
if (outputJson == "-1")
{
return null;
}
// 解析output字段中的JSON数组字符串
var outputArray = JArray.Parse(outputJson);
// 将JArray转换为CozePage对象列表
var cozePages = outputArray.ToObject>();
// 创建CozeResult实例
var cozeResult = new CozeResult(cozePages);
return cozeResult;
}
else
{
Console.WriteLine("请求失败,状态码:" + response.StatusCode);
return null;
}
}
}
catch (Exception ex)
{
Console.WriteLine("请求过程中发生错误:" + ex.Message);
return null;
}
}
public string GetPolicyAnswer(int UserId, string CompanyName)
{
try
{
int IsVIP = _acc.GetIsPolicyVIPList(UserId);
int Count = _sir.GetSubsidyInquiryRecordToDayCount(UserId);
if (Count>= IsVIP) {
Console.WriteLine("今日政策洞察额度已经用完,如有需要请联系管理员!");
return "-1";
}
//coze
// // 设置API的URL
// string apiUrl = "https://api.coze.cn/v1/workflow/run";
// // 设置授权令牌
// string bearerToken = "pat_58jGFdi1EjYOZnLCJRe162Mq3E9Xary8gyXzTDKEvUn3wqXNi9WzGktFgHPK1oUa";
// // 设置请求的JSON内容
// string jsonContent = $@"{{
// ""workflow_id"": ""7427048743201832975"",
// ""parameters"": {{
// ""BOT_USER_INPUT"": """",
// ""keyword"": ""{CompanyName}能申请哪些政策""
// }}
//}}";
//dify
// 设置API的URL
string apiUrl = "http://14.103.174.44/v1/workflows/run";
// 设置授权令牌
string bearerToken = "app-KTUm354NyhAylEhQGk7I7W2l";
// 设置请求的JSON内容
string jsonContent = $@"{{
""user"": ""rensofter"",
""response_mode"": ""blocking"",
""inputs"": {{
""company"": ""{CompanyName}""
}}
}}";
using (HttpClient client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, apiUrl)
{
Content = new StringContent(jsonContent, Encoding.UTF8, "application/json")
};
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearerToken);
// 使用Task.Run来运行异步操作,并使用.Result获取结果
HttpResponseMessage response = System.Threading.Tasks.Task.Run(() => client.SendAsync(request)).Result;
if (response.IsSuccessStatusCode)
{
string responseContent = System.Threading.Tasks.Task.Run(() => response.Content.ReadAsStringAsync()).Result;
// 解析JSON字符串
var rootObject = JObject.Parse(responseContent);
// 提取data字段
var data = rootObject["data"].ToString();
// 解析data字段中的JSON字符串
var dataObject = JObject.Parse(data);
// 提取output字段
string outputs = dataObject["outputs"].ToString();
// 解析data字段中的JSON字符串
var datatxt = JObject.Parse(outputs);
// 提取output字段
string text = datatxt["data"].ToString();
bool isInsert = _sir.AddSubsidyInquiryRecordData(UserId, CompanyName, text);
if (!isInsert&& data == null)
{
Console.WriteLine("请求失败");
return null;
}
return text;
}
else
{
Console.WriteLine("请求失败,状态码:" + response.StatusCode);
return null;
}
}
}
catch (Exception ex)
{
Console.WriteLine("请求过程中发生错误:" + ex.Message);
return null;
}
}
}
}