HttpService.cs 18.3 KB
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 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text;
using HHECS.BllModel;
using HHECS.WorkHourStatistics.Dtos;
using Microsoft.Extensions.Caching.Distributed;
using HHECS.WorkHourStatistics.Models;

namespace HHECS.WorkHourStatistics.Service
{
    public class HttpService
    {
        private readonly HttpClient _httpClient;
        private readonly IDistributedCache _cache;

        private readonly JsonSerializerOptions jsonSerializeOptions = new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            PropertyNameCaseInsensitive = true
        };

        private readonly JsonSerializerOptions jsonDeserializeOptions = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };

        public HttpService(HttpClient httpClient, IDistributedCache cache)
        {
            _httpClient = httpClient;
            _cache = cache;
        }

        /// <summary>
        /// 获取DevToken
        /// </summary>
        /// <remarks>接口文档:https://www.yuque.com/x-dhr/pg5f7g/qtd7byfi0wz5n02n</remarks>
        /// <returns></returns>
        public BllResult<string> GetDevToken()
        {
            try
            {
                var key = nameof(GetDevToken);
                var value = _cache.GetString(key);
                if (!string.IsNullOrWhiteSpace(value))
                {
                    return BllResultFactory.Success(value, string.Empty);
                }

                //开发者ApiKey
                const string apiKey = "81deffe3f6aa7e4a";
                var data = new
                {
                    apiKey,
                };
                var json = JsonSerializer.Serialize(data, jsonSerializeOptions);
                var content = new StringContent(json);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                content.Headers.Add(nameof(apiKey), apiKey);
                var result = _httpClient.PostAsync("open-api/token/getDevToken", content).Result;
                var resultContent = result.Content.ReadAsStringAsync().Result;
                if (result.IsSuccessStatusCode)
                {
                    var dataResult = JsonSerializer.Deserialize<OAResult<DevTokenDto>>(resultContent, jsonDeserializeOptions)!;
                    if (dataResult.Code == 0)
                    {
                        var devToken = dataResult.Data.DevToken;
                        var cacheEntryOptions = new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(10));
                        _cache.Set(key, Encoding.Default.GetBytes(devToken), cacheEntryOptions);
                        return BllResultFactory.Success(dataResult.Data.DevToken, string.Empty);
                    }
                    return BllResultFactory.Error<string>(dataResult.Message);
                }

                if (string.IsNullOrEmpty(resultContent))
                {
                    resultContent = result.ReasonPhrase;
                }

                return BllResultFactory.Error<string>(resultContent ?? string.Empty);
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<string>(ex.Message);
            }
        }

        public BllResult<List<UserAttendanceRecords>> GetWorkRecod(int pageIndex, int pageSize, DateTime startTime, DateTime endTime, out int total, string? personId, List<string>? deptNames = null)
        {
            total = 0;
            try
            {
                var personsResult = GetPersons();
                if (!personsResult.Success)
                {
                    return BllResultFactory.Error<List<UserAttendanceRecords>>(personsResult.Msg);
                }

                var key = $"{startTime}_{endTime}_{personId}";
                var cacheDataBytes = _cache.Get(key);
                var data = new List<UserAttendanceRecords>();
                if (cacheDataBytes != null)
                {
                    data = JsonSerializer.Deserialize<List<UserAttendanceRecords>>(cacheDataBytes);
                }
                else
                {
                    var result = GetWorkRecodByApi(pageIndex, int.MaxValue, startTime, endTime, out _, personId);
                    if (!result.Success)
                    {
                        //失败
                        return result;
                    }
                    data = result.Data;
                    var cacheEntryOptions = new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
                    cacheDataBytes = Encoding.Default.GetBytes(JsonSerializer.Serialize(result.Data));
                    _cache.Set(key, cacheDataBytes, cacheEntryOptions);
                }
                var persons = personsResult.Data;
                var personNumbers = personsResult.Data.Select(x => x.Number).ToList();
                var temp = data?.Where(x =>
                {
                    //指定用户
                    if (!string.IsNullOrWhiteSpace(personId))
                    {
                        var person = persons.Where(x => x.Id == personId).FirstOrDefault();
                        if (person == null)
                        {
                            return false;
                        }
                        if (deptNames == null || deptNames.Count == 0)
                        {
                            return x.WorkNo == person.Number;
                        }
                        return x.WorkNo == person.Number && deptNames.Contains(x.SysOrgCode);
                    }

                    //所有用户
                    if (deptNames == null || deptNames.Count == 0)
                    {
                        return personNumbers.Contains(x.WorkNo);
                    }
                    return personNumbers.Contains(x.WorkNo) && deptNames.Contains(x.SysOrgCode);
                }).OrderBy(x => x.SysOrgCode).ThenBy(x => x.WorkNo).ThenBy(x => x.CreateTime).ToList() ?? new List<UserAttendanceRecords>();
                total = temp.Count;
                return BllResultFactory.Success(temp.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList());
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<List<UserAttendanceRecords>>(ex.Message);
            }
        }

        /// <summary>
        /// 查询某段时间流程与打卡记录
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <remarks>接口文档:https://www.yuque.com/x-dhr/pg5f7g/kepwxom3xixatwy8</remarks>
        /// <returns></returns>
        private BllResult<List<UserAttendanceRecords>> GetWorkRecodByApi(int pageIndex, int pageSize, DateTime startTime, DateTime endTime, out int total, string? personId = null)
        {
            total = 0;
            try
            {
                var devTokenResult = GetDevToken();
                if (!devTokenResult.Success)
                {
                    return BllResultFactory.Error<List<UserAttendanceRecords>>(devTokenResult.Msg);
                }

                var data = new WorkRecordRequest
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    DataPenetration = new Datapenetration
                    {
                        StartDate = startTime.ToString("yyyy-MM-dd"),
                        EndDate = endTime.ToString("yyyy-MM-dd"),
                        Staff = false,
                        PersonId = personId
                    }
                };

                var json = JsonSerializer.Serialize(data, jsonSerializeOptions);
                var content = new StringContent(json);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                content.Headers.Add("devToken", devTokenResult.Data);
                var result = _httpClient.PostAsync("open-api/attendance/workRecordList4Check", content).Result;
                var resultContent = result.Content.ReadAsStringAsync().Result;
                if (result.IsSuccessStatusCode)
                {
                    var dataResult = JsonSerializer.Deserialize<OAResult<WorkRecordResponse>>(resultContent, jsonDeserializeOptions)!;
                    if (dataResult.Code == 0)
                    {
                        total = dataResult.Data.Total;
                        var records = dataResult.Data.DataList.Select(x =>
                        {
                            var attendanceDataList = x.AttendanceDataList;
                            var temp1 = string.Empty;
                            var temp2 = string.Empty;

                            DateTime? workingHours = null;
                            DateTime? offDutyHours = null;
                            if (attendanceDataList.Count == 1)
                            {
                                temp1 = attendanceDataList[0].CreateTime;
                            }
                            else if (attendanceDataList.Count >= 2)
                            {
                                temp1 = attendanceDataList.Min(x => x.CreateTime);
                                temp2 = attendanceDataList.Max(x => x.CreateTime);
                            }

                            if (!string.IsNullOrWhiteSpace(temp1))
                            {
                                workingHours = DateTime.Parse(temp1);
                            }

                            if (!string.IsNullOrWhiteSpace(temp2))
                            {
                                offDutyHours = DateTime.Parse(temp2);
                            }

                            return new UserAttendanceRecords
                            {
                                Id = x.Id,
                                WorkNo = x.Number,
                                Name = x.PersonName,
                                SysOrgCode = x.DeptName,
                                WorkingHours = workingHours,
                                OffDutyHours = offDutyHours
                            };
                        }).ToList();
                        return BllResultFactory.Success(records);
                    }
                    return BllResultFactory.Error<List<UserAttendanceRecords>>(dataResult.Message);
                }

                if (string.IsNullOrEmpty(resultContent))
                {
                    resultContent = result.ReasonPhrase;
                }

                return BllResultFactory.Error<List<UserAttendanceRecords>>(resultContent ?? string.Empty);
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<List<UserAttendanceRecords>>(ex.Message);
            }
        }

        /// <summary>
        /// 获取部门信息
        /// </summary>
        /// <returns>接口文档:https://www.yuque.com/x-dhr/pg5f7g/gu3xh4ftnzl0cfe8</returns>
        public BllResult<List<Department>> GetDepartment()
        {
            try
            {
                var devTokenResult = GetDevToken();
                if (!devTokenResult.Success)
                {
                    return BllResultFactory.Error<List<Department>>(devTokenResult.Msg);
                }

                const string parentId = "8682240671139790443";
                if (_httpClient.DefaultRequestHeaders.Contains("devToken"))
                {
                    _httpClient.DefaultRequestHeaders.Remove("devToken");
                }
                _httpClient.DefaultRequestHeaders.Add("devToken", devTokenResult.Data);
                var result = _httpClient.GetAsync($"open-api/department/findChildren?parentId={parentId}&includeChildren=true").Result;
                var resultContent = result.Content.ReadAsStringAsync().Result;
                if (result.IsSuccessStatusCode)
                {
                    var dataResult = JsonSerializer.Deserialize<OAResult<List<Department>>>(resultContent, jsonDeserializeOptions)!;
                    if (dataResult.Code == 0)
                    {
                        return BllResultFactory.Success(dataResult.Data);
                    }
                    return BllResultFactory.Error<List<Department>>(dataResult.Message);
                }

                if (string.IsNullOrEmpty(resultContent))
                {
                    resultContent = result.ReasonPhrase;
                }

                return BllResultFactory.Error<List<Department>>(resultContent ?? string.Empty);
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<List<Department>>(ex.Message);
            }
        }

        /// <summary>
        /// 获取人员信息
        /// </summary>
        /// <param name="deptId">部门Id</param>
        /// <returns>接口文档:https://www.yuque.com/x-dhr/pg5f7g/ysn74kzydf7ybu9q</returns>
        /// <returns></returns>
        public BllResult<List<Person>> GetPersons(string deptId= "8682240671139790443")
        {
            try
            {
                var devTokenResult = GetDevToken();
                if (!devTokenResult.Success)
                {
                    return BllResultFactory.Error<List<Person>>(devTokenResult.Msg);
                }
                //const string deptId = "8682240671139790443";

                var key = $"{nameof(GetPersons)}_{deptId}";
                var cacheDataBytes = _cache.Get(key);
                var data = new List<Person>();
                if (cacheDataBytes != null)
                {
                    data = JsonSerializer.Deserialize<List<Person>>(cacheDataBytes) ?? new List<Person>();
                    return BllResultFactory.Success(data);
                }

                if (_httpClient.DefaultRequestHeaders.Contains("devToken"))
                {
                    _httpClient.DefaultRequestHeaders.Remove("devToken");
                }
                _httpClient.DefaultRequestHeaders.Add("devToken", devTokenResult.Data);
                var result = _httpClient.GetAsync($"open-api/person/findDeptPersons?deptId={deptId}&includeChildren=true").Result;
                var resultContent = result.Content.ReadAsStringAsync().Result;
                if (result.IsSuccessStatusCode)
                {
                    var dataResult = JsonSerializer.Deserialize<OAResult<DeptPersons>>(resultContent, jsonDeserializeOptions)!;
                    if (dataResult.Code == 0)
                    {
                        var cacheEntryOptions = new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
                        cacheDataBytes = Encoding.Default.GetBytes(JsonSerializer.Serialize(dataResult.Data.Persons));
                        _cache.Set(key, cacheDataBytes, cacheEntryOptions);
                        return BllResultFactory.Success(dataResult.Data.Persons);
                    }
                    return BllResultFactory.Error<List<Person>>(dataResult.Message);
                }

                if (string.IsNullOrEmpty(resultContent))
                {
                    resultContent = result.ReasonPhrase;
                }
                return BllResultFactory.Error<List<Person>>(resultContent!);
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<List<Person>>(ex.Message);
            }
        }

        /// <summary>
        /// 28.查询指定日期单位下所有人员有效打卡数据
        /// </summary>
        /// <param name="checkDate">考勤日期,格式:2022-03-04</param>
        /// <param name="pageIndex">第几页,从1开始</param>
        /// <remarks>接口文档:https://www.yuque.com/x-dhr/pg5f7g/tr7kl9w6qhimh2g9</remarks>
        /// <returns></returns>
        public BllResult<List<WorkRecordDto>> GetWorkRecod(string checkDate, int pageIndex)
        {
            try
            {
                var devTokenResult = GetDevToken();
                if (!devTokenResult.Success)
                {
                    return BllResultFactory.Error<List<WorkRecordDto>>(devTokenResult.Msg);
                }

                var key = $"{nameof(GetWorkRecod)}_{checkDate}_{pageIndex}";
                var cacheDataBytes = _cache.Get(key);
                var data = new List<WorkRecordDto>();
                if (cacheDataBytes != null)
                {
                    data = JsonSerializer.Deserialize<List<WorkRecordDto>>(cacheDataBytes) ?? new List<WorkRecordDto>();
                    return BllResultFactory.Success(data);
                }

                var request = new
                {
                    checkDate,
                    pageIndex,
                };

                var json = JsonSerializer.Serialize(request, jsonSerializeOptions);
                var content = new StringContent(json);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                content.Headers.Add("devToken", devTokenResult.Data);
                var result = _httpClient.PostAsync("open-api/attendance/findCheckDataList", content).Result;
                var resultContent = result.Content.ReadAsStringAsync().Result;
                if (result.IsSuccessStatusCode)
                {
                    var dataResult = JsonSerializer.Deserialize<OAResult<CheckDataListResponse>>(resultContent, jsonDeserializeOptions)!;
                    if (dataResult.Code == 0)
                    {
                        var cacheEntryOptions = new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(10));
                        cacheDataBytes = Encoding.Default.GetBytes(JsonSerializer.Serialize(dataResult.Data.DataList));
                        _cache.Set(key, cacheDataBytes, cacheEntryOptions);
                        return BllResultFactory.Success(dataResult.Data.DataList);
                    }
                    return BllResultFactory.Error<List<WorkRecordDto>>(dataResult.Message);
                }

                if (string.IsNullOrEmpty(resultContent))
                {
                    resultContent = result.ReasonPhrase;
                }
                return BllResultFactory.Error<List<WorkRecordDto>>(resultContent!);
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error<List<WorkRecordDto>>(ex.Message);
            }
        }
    }
}