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
using DTO;
using IServices;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using zhengcaioa.IService;
using zhengcaioa.Models;
 
namespace zhengcaioa.Timer
{
    public class TimerGetShopUsersService : BackgroundService
    {
        private readonly ILogger _logger;
        private readonly IConfiguration _configuration;
        private readonly ILiaotianService _liaotianService;
        private readonly IHttpClientFactory _clientFactory;
        private readonly ICooperatecustomCustomerService _cooperatecustomCustomerService;
 
 
        public TimerGetShopUsersService(ILogger<TimerGetShopUsersService> logger, IServiceScopeFactory factory)
        {
            _logger = logger;
            _configuration = factory.CreateScope().ServiceProvider.GetRequiredService<IConfiguration>();
            _liaotianService = factory.CreateScope().ServiceProvider.GetRequiredService<ILiaotianService>();
            _clientFactory = factory.CreateScope().ServiceProvider.GetRequiredService<IHttpClientFactory>();
            _cooperatecustomCustomerService = factory.CreateScope().ServiceProvider.GetRequiredService<ICooperatecustomCustomerService>();
 
 
        }
 
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("TimerGetShopUsersService is starting.");
 
            //stoppingToken.Register(() => File.Create($"E:\\dotnetCore\\Practice\\Practice\\{DateTime.Now.Millisecond}.txt"));
 
            DateTime datenow = DateTime.Now;
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("TimerGetShopUsersService 开始执行");
                _logger.LogInformation(datenow.ToString("yyyy-MM-dd HH:mm:ss"));
                //每个小时计算一次
                if (datenow.Hour == DateTime.Now.Hour)
                //if (true)
                {
 
                    try
                    {
                        
                        await this.huoquhuiyuanAsync();
 
                    }
                    catch (Exception ex)
                    {
                        _logger.LogInformation(ex.ToString());
                    }
 
                    datenow = DateTime.Now.AddHours(1);
                }
 
 
                await Task.Delay(TimeSpan.FromMinutes(10), stoppingToken);
 
                _logger.LogInformation("TimerGetShopUsersService 继续执行");
            }
 
            _logger.LogInformation("TimerGetShopUsersService background task is stopping.");
        }
 
        public override void Dispose()
        {
            base.Dispose();
        }
      
 
        public async Task huoquhuiyuanAsync()
        {
            string Shuchengurl = _configuration.GetSection("Shuchengurl").Value;
            string GetShopUsers = _configuration.GetSection("GetShopUsers").Value;
 
 
            string huiyuanurl = _configuration.GetSection("huiyuanurl").Value;
            string GetDateFirstOrderUser = _configuration.GetSection("GetDateFirstOrderUser").Value;
            string GetUserinfoAndRule = _configuration.GetSection("GetUserinfoAndRule").Value;
 
            ResultEntity resultEntity = new ResultEntity();
            resultEntity.Result = false;
 
 
 
 
 
 
 
          
 
 
 
            //using (TransactionScope scope = new TransactionScope())
            //{
                //获取最后更新时间
                DateTime start = DateTime.Now.AddYears(-10);
                DateTime end = DateTime.Now;
 
                var ssss = _liaotianService.GetSysUpdatetime("getCustomers");
 
                if (ssss != null)
                {
                    start = ssss.Updatetime;
                }
                _logger.LogInformation("start:" + start);
                _logger.LogInformation("end:" + end);
 
 
            //获取客户并且保存到合作客户
 
            #region 书城
            string result = string.Empty;
                Uri getUrl = new Uri(Shuchengurl + GetShopUsers + "?start="+ start.ToString("yyyy-MM-dd HH:mm:ss") + "&end="+ end.ToString("yyyy-MM-dd HH:mm:ss"));
 
                var httpClient = _clientFactory.CreateClient();
                httpClient.Timeout = new TimeSpan(0, 0, 60);
                var Result = await httpClient.GetAsync(getUrl);
                result = Result.Content.ReadAsStringAsync().Result;
 
 
                _logger.LogInformation("result:" + result);
            JObject jobjectresult = (JObject)JsonConvert.DeserializeObject(result);
 
            if (jobjectresult["code"] != null && jobjectresult["code"].ToString() == "1")
            {
                if(jobjectresult["returnObj"] != null && jobjectresult["returnObj"].ToString() != "")
                {
 
 
                    JArray hits = (JArray)jobjectresult["returnObj"];
                    foreach (var hit in hits)
                    {
                        string id = hit["id"].ToString().ToLower();
                        CooperatecustomCustomerDTO cooperatecustomCustomerDTO = _cooperatecustomCustomerService.GetList(id).FirstOrDefault();
                        //如果不存在关联客户
                        if (cooperatecustomCustomerDTO == null)
                        {
 
                            string result2 = string.Empty;
                            Uri postUrl2 = new Uri(huiyuanurl + GetUserinfoAndRule);
 
                            JObject questions2 = new JObject();
                            questions2.Add("UserID", id);
 
                            string requestJson2 = questions2.ToString();
 
                            using (HttpContent httpContent = new StringContent(requestJson2))
                            {
                                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
 
                                var httpClient2 = _clientFactory.CreateClient();
                                httpClient2.Timeout = new TimeSpan(0, 0, 60);
                                var Result2 = await httpClient2.PostAsync(postUrl2, httpContent);
                                result2 = Result2.Content.ReadAsStringAsync().Result;
                            }
 
                            _logger.LogInformation("result2:" + result2);
 
                            JObject jobjectresult2 = (JObject)JsonConvert.DeserializeObject(result2);
                            if (jobjectresult2["code"] == null && jobjectresult2["code"].ToString() != "1")
                            {
                                throw new Exception(jobjectresult2["msg"].ToString());
                            }
 
                            JObject jobjectkehu = (JObject)jobjectresult2["data"];
                            if (jobjectkehu["Name"] == null || jobjectkehu["Name"].ToString() == "")
                            {
                                throw new Exception("未找到对应的会员!");
                            }
 
 
                            cooperatecustomCustomerDTO = _cooperatecustomCustomerService.GetList("", jobjectkehu["Name"].ToString()).FirstOrDefault();
                            //如果不存在当前名字的客户
                            if (cooperatecustomCustomerDTO == null)
                            {
                                cooperatecustomCustomerDTO = new CooperatecustomCustomerDTO();
                                cooperatecustomCustomerDTO.Name = jobjectkehu["Name"].ToString();
                                cooperatecustomCustomerDTO.Tel = jobjectkehu["phonecode"].ToString();
                                cooperatecustomCustomerDTO.Phone = jobjectkehu["phonecode"].ToString();
 
                                cooperatecustomCustomerDTO.HuiyuanId = id;
                                //cooperatecustomCustomerDTO.Remark = hit["personal"].ToString() + "下单时间" + hit["Firsttime"].ToString();
                                cooperatecustomCustomerDTO.Khly = "01";
                                cooperatecustomCustomerDTO.Creater = "1";
                                cooperatecustomCustomerDTO.Createtime = DateTime.Now;
                                cooperatecustomCustomerDTO.Modifier = cooperatecustomCustomerDTO.Creater;
                                cooperatecustomCustomerDTO.Modifytime = cooperatecustomCustomerDTO.Createtime;
 
                                cooperatecustomCustomerDTO.ShrName = hit["accept_name"].ToString();
                                cooperatecustomCustomerDTO.ShrTel = hit["mobile"].ToString();
                                cooperatecustomCustomerDTO.ShrAddress = hit["area"].ToString() + hit["address"].ToString();
 
                                resultEntity = _cooperatecustomCustomerService.save(cooperatecustomCustomerDTO);
                                if (!resultEntity.Result)
                                {
                                    throw new Exception("保存合作客户:" + cooperatecustomCustomerDTO.Name + "出错!");
                                }
                            }
                            else
                            {
                                cooperatecustomCustomerDTO.HuiyuanId = id;
                                cooperatecustomCustomerDTO.ShrName = hit["accept_name"].ToString();
                                cooperatecustomCustomerDTO.ShrTel = hit["mobile"].ToString();
                                cooperatecustomCustomerDTO.ShrAddress = hit["area"].ToString() + hit["address"].ToString();
                                resultEntity = _cooperatecustomCustomerService.save(cooperatecustomCustomerDTO);
                                if (!resultEntity.Result)
                                {
                                    throw new Exception("保存合作客户:" + cooperatecustomCustomerDTO.Name + "出错!");
                                }
                            }
                        }
                        else
                        {
                            cooperatecustomCustomerDTO.HuiyuanId = id;
                            cooperatecustomCustomerDTO.ShrName = hit["accept_name"].ToString();
                            cooperatecustomCustomerDTO.ShrTel = hit["mobile"].ToString();
                            cooperatecustomCustomerDTO.ShrAddress = hit["area"].ToString() + hit["address"].ToString();
                            resultEntity = _cooperatecustomCustomerService.save(cooperatecustomCustomerDTO);
                            if (!resultEntity.Result)
                            {
                                throw new Exception("保存合作客户:" + cooperatecustomCustomerDTO.Name + "出错!");
                            }
                        }
 
                    }
 
                }
            }
            else
            {
                throw new Exception(jobjectresult["error"].ToString());
            }
 
 
 
              
 
            #endregion
 
 
            #region 会员
            string result1 = string.Empty;
            Uri postUrl = new Uri(huiyuanurl + GetDateFirstOrderUser);
 
            JObject questions = new JObject();
            questions.Add("start", start.ToString("yyyy-MM-dd HH:mm:ss"));
            questions.Add("end", end.ToString("yyyy-MM-dd HH:mm:ss"));
 
            string requestJson = questions.ToString();
 
            using (HttpContent httpContent = new StringContent(requestJson))
            {
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
 
                var httpClient1 = _clientFactory.CreateClient();
                httpClient1.Timeout = new TimeSpan(0, 0, 60);
                var Result1 = await httpClient1.PostAsync(postUrl, httpContent);
                result1 = Result1.Content.ReadAsStringAsync().Result;
            }
 
            _logger.LogInformation("result1:" + result1);
            JObject jobject = (JObject)JsonConvert.DeserializeObject(result1);
 
            if (jobject["code"] != null && jobject["code"].ToString() == "1")
            {
                if (jobject["data"] != null && jobject["data"].ToString() != "")
                {
                    JArray hits = (JArray)jobject["data"];
                    foreach (var hit in hits)
                    {
                        CooperatecustomCustomerDTO cooperatecustomCustomerDTO = _cooperatecustomCustomerService.GetList(hit["ID"].ToString()).FirstOrDefault();
                        //如果不存在关联客户
                        if (cooperatecustomCustomerDTO == null)
                        {
                            cooperatecustomCustomerDTO = _cooperatecustomCustomerService.GetList("", hit["Name"].ToString()).FirstOrDefault();
                            //如果不存在当前名字的客户
                            if (cooperatecustomCustomerDTO == null)
                            {
                                cooperatecustomCustomerDTO = new CooperatecustomCustomerDTO();
                                cooperatecustomCustomerDTO.Name = hit["Name"].ToString();
                                cooperatecustomCustomerDTO.Tel = hit["PhoneCode"].ToString();
                                cooperatecustomCustomerDTO.Phone = hit["PhoneCode"].ToString();
 
                                cooperatecustomCustomerDTO.HuiyuanId = hit["ID"].ToString();
                                cooperatecustomCustomerDTO.Remark = hit["personal"].ToString() + "下单时间" + hit["Firsttime"].ToString();
                                cooperatecustomCustomerDTO.Khly = "01";
                                cooperatecustomCustomerDTO.Creater = "1";
                                cooperatecustomCustomerDTO.Createtime = DateTime.Now;
                                cooperatecustomCustomerDTO.Modifier = cooperatecustomCustomerDTO.Creater;
                                cooperatecustomCustomerDTO.Modifytime = cooperatecustomCustomerDTO.Createtime;
 
                                resultEntity = _cooperatecustomCustomerService.save(cooperatecustomCustomerDTO);
                                if (!resultEntity.Result)
                                {
                                    throw new Exception("保存合作客户:" + cooperatecustomCustomerDTO.Name + "出错!");
                                }
                            }
                            else
                            {
                                cooperatecustomCustomerDTO.HuiyuanId = hit["ID"].ToString();
                                resultEntity = _cooperatecustomCustomerService.save(cooperatecustomCustomerDTO);
                                if (!resultEntity.Result)
                                {
                                    throw new Exception("保存合作客户:" + cooperatecustomCustomerDTO.Name + "出错!");
                                }
                            }
                        }
 
                    }
                }
                    
            }
            else
            {
                throw new Exception(jobject["msg"].ToString());
            }
 
            #endregion
 
 
            //保存最后更新时间
            if (ssss != null)
                {
                    ssss.Updatetime = end;
                }
                else
                {
                    ssss = new SysUpdatetime();
                    ssss.Updatetime = end;
                    ssss.Updatename = "getCustomers";
                }
                resultEntity = _liaotianService.saveSysUpdatetime(ssss);
                if (!resultEntity.Result)
                {
                    throw new Exception("保存更新时间出错!");
                }
 
            //    scope.Complete();
            //}
 
             
 
         
 
 
 
        }
    }
}