chenzx
2025-01-20 f914946689e613f1dfeb4dfe91f5797764245332
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
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();
        /// <summary>
        /// 获取用益信托网记录数据
        /// </summary>
        /// <returns></returns>
        public PaginatedResult<SubsidyDataPage> 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<SubsidyDataPage> totalData = _sub.GetSubsidyDataList(PageNumber, PageSize, Keyword, City, Region, Province);
            return new PaginatedResult<SubsidyDataPage>(totalData, totalCount, totalPage);
        }
 
 
 
        public List<SubsidyDataPage> 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<SubsidyDataPage> 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<dynamic>(responseContent);
        //                return completion.choices[0].message.content.ToString();
        //            }
        //            else
        //            {
        //                return $"Error: {response.StatusCode}";
        //            }
        //        }
        //        catch (Exception e)
        //        {
        //            return $"Exception caught: {e.Message}";
        //        }
        //    }
        //}
 
        public CozeResult<CozePage> 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<List<CozePage>>();
                            var Error = new CozeResult<CozePage>(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<List<CozePage>>();
 
                        // 创建CozeResult<CozePage>实例
                        var cozeResult = new CozeResult<CozePage>(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;
                }
        
        }
    }
}