You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

782 lines
34 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. using Shentun.WebPeis.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Volo.Abp.Application.Services;
  8. using Volo.Abp.Domain.Entities;
  9. using Volo.Abp.Domain.Repositories;
  10. using Volo.Abp.Users;
  11. using Shentun.WebPeis.Wechats;
  12. using Microsoft.Extensions.Configuration;
  13. using System.Net.Http;
  14. using System.Net;
  15. using System.Text.Json;
  16. using Volo.Abp.Identity;
  17. using Volo.Abp;
  18. using Shentun.WebPeis.Enums;
  19. using System.Net.Http.Headers;
  20. using Microsoft.AspNetCore.Mvc;
  21. using OpenIddict.Abstractions;
  22. using Microsoft.AspNetCore.Identity;
  23. using Volo.Abp.ObjectMapping;
  24. using Microsoft.AspNetCore.Authorization;
  25. using Volo.Abp.Caching;
  26. using NPOI.SS.Formula.Functions;
  27. using System.Linq.Dynamic.Core.Tokenizer;
  28. using Microsoft.Extensions.Caching.Distributed;
  29. using Volo.Abp.Uow;
  30. using Scriban.Parsing;
  31. using System.IdentityModel.Tokens.Jwt;
  32. using Shentun.WebPeis.PatientRegisters;
  33. using Microsoft.AspNetCore.Http;
  34. using System.IO;
  35. using Shentun.WebPeis.CustomerOrgs;
  36. using Shentun.Utilities.Enums;
  37. using Shentun.Sms.Client;
  38. using Shentun.Utilities;
  39. namespace Shentun.WebPeis.Persons
  40. {
  41. /// <summary>
  42. /// 微信人员
  43. /// </summary>
  44. [ApiExplorerSettings(GroupName = "Work")]
  45. [Authorize]
  46. public class PersonAppService : ApplicationService
  47. {
  48. private readonly IRepository<QuestionRegister> _questionRegisterRepository;
  49. private readonly IConfiguration _configuration;
  50. private readonly IRepository<IdentityUser, Guid> _identityUserRepository;
  51. private readonly IdentityUserManager _userManager;
  52. private readonly IRepository<Person> _repository;
  53. private readonly PersonManager _personManager;
  54. private readonly IDistributedCache<string, string> _cache;
  55. private readonly IUnitOfWorkManager _unitOfWorkManager;
  56. private readonly IRepository<PersonKinship> _personKinshipRepository;
  57. private readonly IRepository<PatientRegister> _patientRegisterRepository;
  58. private readonly IRepository<Patient> _patientRepository;
  59. private readonly CacheService _cacheService;
  60. private readonly IHttpContextAccessor _httpContextAccessor;
  61. private readonly IRepository<CustomerOrg> _customerOrgRepository;
  62. public PersonAppService(IRepository<Person> repository,
  63. IConfiguration configuration,
  64. IRepository<Volo.Abp.Identity.IdentityUser, Guid> identityUserRepository,
  65. IdentityUserManager userManager,
  66. PersonManager personManager,
  67. IUnitOfWorkManager unitOfWorkManager,
  68. IDistributedCache<string, string> cache,
  69. IRepository<PersonKinship> personKinshipRepository,
  70. IRepository<PatientRegister> patientRegisterRepository,
  71. IRepository<Patient> patientRepository,
  72. CacheService cacheService,
  73. IHttpContextAccessor httpContextAccessor,
  74. IRepository<CustomerOrg> customerOrgRepository,
  75. IRepository<QuestionRegister> questionRegisterRepository)
  76. {
  77. _repository = repository;
  78. _configuration = configuration;
  79. _identityUserRepository = identityUserRepository;
  80. _userManager = userManager;
  81. _personManager = personManager;
  82. _unitOfWorkManager = unitOfWorkManager;
  83. _cache = cache;
  84. _personKinshipRepository = personKinshipRepository;
  85. _patientRegisterRepository = patientRegisterRepository;
  86. _patientRepository = patientRepository;
  87. _cacheService = cacheService;
  88. _httpContextAccessor = httpContextAccessor;
  89. _customerOrgRepository = customerOrgRepository;
  90. _questionRegisterRepository = questionRegisterRepository;
  91. }
  92. public async Task<PersonDto> GetByIdAsync(PersonIdInputDto input)
  93. {
  94. var entity = await _repository.GetAsync(o => o.PersonId == input.PersonId);
  95. var entityDto = ObjectMapper.Map<Person, PersonDto>(entity);
  96. return entityDto;
  97. }
  98. /// <summary>
  99. /// 微信用户登录
  100. /// </summary>
  101. /// <param name="input"></param>
  102. /// <returns></returns>
  103. [AllowAnonymous]
  104. [HttpPost("api/app/Person/WeChatUserLogin")]
  105. public async Task<UserTokenDto> WeChatUserLoginAsync(WechatUserJsCodeInputDto input)
  106. {
  107. var weChatClientId = _configuration.GetSection("AuthServer").GetSection("WeChatClientId").Value;
  108. var secret = _configuration.GetSection("AuthServer").GetSection("WeChatClientSecret").Value;
  109. var commonScopes = new List<string> {
  110. OpenIddictConstants.Permissions.Scopes.Address,
  111. OpenIddictConstants.Permissions.Scopes.Email,
  112. OpenIddictConstants.Permissions.Scopes.Phone,
  113. OpenIddictConstants.Permissions.Scopes.Profile,
  114. OpenIddictConstants.Permissions.Scopes.Roles,
  115. "WebPeis"
  116. };
  117. var dic = new Dictionary<string, object>
  118. {
  119. {"jsCode",input.JsCode},
  120. {"client_id",weChatClientId},
  121. {"client_secret",secret},
  122. {"grant_type",WeChatGrant.GrantType},
  123. {"scope","WeChat offline_access"}
  124. };
  125. var dicStr = dic.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n);
  126. var token = await GetTokenAsync(dicStr);
  127. var options = new DistributedCacheEntryOptions()
  128. .SetAbsoluteExpiration(TimeSpan.FromDays(3));
  129. var sessionKey = CacheKeys.SessionKey + Guid.NewGuid().ToString();
  130. var sessionKeyValue = Guid.NewGuid().ToString();
  131. _cache.Set(sessionKey, sessionKeyValue, options);
  132. token.SessionKey = sessionKey;
  133. token.SessionKeyValue = sessionKeyValue;
  134. return token;
  135. }
  136. [AllowAnonymous]
  137. [HttpPost("api/app/Person/Create")]
  138. [UnitOfWork(IsDisabled = false)]
  139. public async Task<UserTokenDto> CreateAsync(CreatePersonDto input)
  140. {
  141. if(input == null) throw new UserFriendlyException("input参数不能为空");
  142. using (var unitOfWork = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true))
  143. {
  144. var entity = ObjectMapper.Map<CreatePersonDto, Person>(input);
  145. if (string.IsNullOrWhiteSpace(input.JsCode))
  146. {
  147. throw new UserFriendlyException("jsCode不能为空");
  148. }
  149. if (string.IsNullOrWhiteSpace(input.WechatOpenId))
  150. {
  151. throw new UserFriendlyException("WechatOpenId不能为空");
  152. }
  153. if (_cache.Get(CacheKeys.OpenIdKey + input.WechatOpenId) != input.WechatOpenId)
  154. {
  155. throw new UserFriendlyException("无效的WechatOpenId");
  156. }
  157. if (string.IsNullOrWhiteSpace(input.MobileTelephone))
  158. {
  159. throw new UserFriendlyException("手机号码不能为空");
  160. }
  161. if (input.MobileTelephone.Length != 11)
  162. {
  163. throw new UserFriendlyException("手机号码必须为11位");
  164. }
  165. if (string.IsNullOrWhiteSpace(input.SmsVerifyCodeKey))
  166. {
  167. throw new UserFriendlyException("短信校验码键不能为空");
  168. }
  169. if (_cache.Get(input.SmsVerifyCodeKey) != input.SmsVerifyCode)
  170. {
  171. throw new UserFriendlyException("无效的短信校验码或已过期");
  172. }
  173. var person = await _repository.FindAsync(o => o.IdNo == input.IdNo);
  174. if (person != null)
  175. {
  176. var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId &&
  177. o.PhoneNumber == input.MobileTelephone).FirstOrDefault();
  178. if (user == null)
  179. {
  180. throw new UserFriendlyException("该身份证号已注册,但手机号码不一致");
  181. }
  182. if (!string.IsNullOrWhiteSpace(person.WechatOpenId))
  183. {
  184. throw new UserFriendlyException("该微信号已注册");
  185. }
  186. person.WechatOpenId = input.WechatOpenId;
  187. await _repository.UpdateAsync(person);
  188. }
  189. else
  190. {
  191. entity.WechatOpenId = input.WechatOpenId;
  192. var userWithPerson = await _personManager.CreateAsync(entity, input.PersonName,
  193. input.Email, input.MobileTelephone);
  194. await _identityUserRepository.InsertAsync(userWithPerson.User);
  195. await _repository.InsertAsync(userWithPerson.Person);
  196. //设置密码
  197. (await _userManager.RemovePasswordAsync(userWithPerson.User)).CheckErrors();
  198. (await _userManager.AddPasswordAsync(userWithPerson.User, Shentun.Utilities.
  199. Encrypt.RandomHelper.CreateRandom(Utilities.Enums.RandomType.NumAndChar, 10) + "0Cz*")).CheckErrors();
  200. }
  201. await unitOfWork.CompleteAsync();
  202. }
  203. using (var unitOfWork = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: false))
  204. {
  205. var weChatClientId = _configuration.GetSection("AuthServer").GetSection("WeChatClientId").Value;
  206. var secret = _configuration.GetSection("AuthServer").GetSection("WeChatClientSecret").Value;
  207. var dic = new Dictionary<string, object>
  208. {
  209. {"jsCode",input.JsCode},
  210. {"client_id",weChatClientId},
  211. {"client_secret",secret},
  212. {"grant_type",WeChatGrant.GrantType},
  213. {"scope","WeChat offline_access"}
  214. };
  215. var dicStr = dic.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n);
  216. var token = await GetTokenAsync(dicStr);
  217. //var entityDto = ObjectMapper.Map<Person, PersonDto>(userWithPerson.Person);
  218. await unitOfWork.CompleteAsync();
  219. return token;
  220. }
  221. }
  222. /// <summary>
  223. /// 更新
  224. /// </summary>
  225. /// <param name="input"></param>
  226. /// <returns></returns>
  227. /// <exception cref="UserFriendlyException"></exception>
  228. [HttpPost("api/app/Person/Update")]
  229. public async Task<PersonDto> UpdateAsync(UpdatePersonDto input)
  230. {
  231. if (input == null) throw new UserFriendlyException("input参数不能为空");
  232. var entity = ObjectMapper.Map<UpdatePersonDto, Person>(input);
  233. if (string.IsNullOrWhiteSpace(input.MobileTelephone))
  234. {
  235. throw new UserFriendlyException("手机号码不能为空");
  236. }
  237. if (input.MobileTelephone.Length != 11)
  238. {
  239. throw new UserFriendlyException("手机号码必须为11位");
  240. }
  241. if (string.IsNullOrWhiteSpace(input.SmsVerifyCodeKey))
  242. {
  243. throw new UserFriendlyException("短信校验码键不能为空");
  244. }
  245. if (_cache.Get(input.SmsVerifyCodeKey) != input.SmsVerifyCode)
  246. {
  247. throw new UserFriendlyException("无效的短信校验码或已过期");
  248. }
  249. //更新人员信息
  250. var person = await _repository.GetAsync(o =>o.PersonId == input.PersonId);
  251. await _personManager.UpdateAsync(entity, person);
  252. await _repository.UpdateAsync(person);
  253. //更新用户信息
  254. var user = await _identityUserRepository.GetAsync(person.PersonId);
  255. user.Name = input.PersonName;
  256. user.SetPhoneNumber(input.MobileTelephone,false);
  257. await _identityUserRepository.UpdateAsync(user);
  258. return ObjectMapper.Map<Person, PersonDto>(person);
  259. }
  260. /// <summary>
  261. /// 创建亲属
  262. /// </summary>
  263. /// <param name="input"></param>
  264. /// <returns></returns>
  265. /// <exception cref="UserFriendlyException"></exception>
  266. [HttpPost("api/app/Person/CreatePersonKinship")]
  267. public async Task CreatePersonKinshipAsync(CreatePersonKinshipDto input)
  268. {
  269. if (input == null) throw new UserFriendlyException("input参数不能为空");
  270. var entity = ObjectMapper.Map<CreatePersonKinshipDto, Person>(input);
  271. if (string.IsNullOrWhiteSpace(input.KinshipId))
  272. {
  273. throw new UserFriendlyException("亲属关系不能为空");
  274. }
  275. if (string.IsNullOrWhiteSpace(input.SmsVerifyCodeKey))
  276. {
  277. throw new UserFriendlyException("短信校验码键不能为空");
  278. }
  279. if (_cache.Get(input.SmsVerifyCodeKey) != input.SmsVerifyCode)
  280. {
  281. throw new UserFriendlyException("无效的短信校验码或已过期");
  282. }
  283. var person = await _repository.FindAsync(o => o.IdNo == input.IdNo);
  284. if (person != null)
  285. {
  286. var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId &&
  287. o.PhoneNumber == input.MobileTelephone).FirstOrDefault();
  288. if (user == null)
  289. {
  290. throw new UserFriendlyException("该身份证号已注册,但手机号码不一致");
  291. }
  292. var personKinshipExist = new PersonKinship()
  293. {
  294. PersonId = person.PersonId,
  295. ParentPersonId = (Guid)CurrentUser.Id,
  296. KinshipId = input.KinshipId,
  297. };
  298. await _personKinshipRepository.InsertAsync(personKinshipExist);
  299. return;
  300. }
  301. var userWithPerson = await _personManager.CreateAsync(entity, input.PersonName,
  302. input.Email, input.MobileTelephone);
  303. var personKinship = new PersonKinship()
  304. {
  305. PersonId = userWithPerson.Person.PersonId,
  306. ParentPersonId = (Guid)CurrentUser.Id,
  307. KinshipId = input.KinshipId,
  308. };
  309. await _identityUserRepository.InsertAsync(userWithPerson.User);
  310. await _repository.InsertAsync(userWithPerson.Person);
  311. await _personKinshipRepository.InsertAsync(personKinship);
  312. //设置密码
  313. (await _userManager.RemovePasswordAsync(userWithPerson.User)).CheckErrors();
  314. (await _userManager.AddPasswordAsync(userWithPerson.User, Shentun.Utilities.
  315. Encrypt.RandomHelper.CreateRandom(Utilities.Enums.RandomType.NumAndChar, 10) + "0Cz*")).CheckErrors();
  316. }
  317. /// <summary>
  318. /// 取消人员绑定
  319. /// </summary>
  320. /// <param name="input"></param>
  321. /// <returns></returns>
  322. [HttpPost("api/app/Person/CancelPersonKinship")]
  323. public async Task CancelPersonKinshipAsync(PersonIdInputDto input)
  324. {
  325. var personKinship = await _personKinshipRepository.GetAsync(o => o.ParentPersonId == (Guid)CurrentUser.Id && o.PersonId == input.PersonId);
  326. await _personKinshipRepository.DeleteAsync(personKinship);
  327. }
  328. /// <summary>
  329. /// 获取体检次数列表
  330. /// </summary>
  331. /// <param name="input"></param>
  332. /// <returns></returns>
  333. [HttpPost("api/app/Person/GetMedicalTimesListByPersonId")]
  334. public async Task<List<PersonMedicalTimesDto>> GetMedicalTimesListByPersonIdAsync(PersonIdInputDto input)
  335. {
  336. var entityList = (from user in await _identityUserRepository.GetQueryableAsync()
  337. join person in await _repository.GetQueryableAsync()
  338. on user.Id equals person.PersonId
  339. join patient in await _patientRepository.GetQueryableAsync()
  340. on new { idNo = person.IdNo, phone = user.PhoneNumber } equals new { idNo = patient.IdNo, phone = patient.MobileTelephone }
  341. join patientRegister in await _patientRegisterRepository.GetQueryableAsync()
  342. on patient.PatientId equals patientRegister.PatientId
  343. where user.Id == input.PersonId &&
  344. (patientRegister.CompleteFlag == PatientRegisterCompleteFlag.SumCheck)
  345. orderby patientRegister.MedicalStartDate
  346. select new PersonMedicalTimesDto()
  347. {
  348. PatientRegisterId = patientRegister.PatientRegisterId,
  349. PersonName = patient.PatientName,
  350. MedicalStartDate = patientRegister.MedicalStartDate,
  351. }).ToList();
  352. return entityList;
  353. }
  354. /// <summary>
  355. /// 获取本人和亲属列表
  356. /// </summary>
  357. /// <returns></returns>
  358. [HttpPost("api/app/Person/GetPersonKinshipList")]
  359. public async Task<List<PersonDto>> GetPersonKinshipList()
  360. {
  361. var personKinshipIds = (await _personKinshipRepository.GetQueryableAsync())
  362. .Where(o => o.ParentPersonId == CurrentUser.Id)
  363. .Select(o => o.PersonId).ToList();
  364. personKinshipIds.Add((Guid)CurrentUser.Id);
  365. var personList = (from user in await _identityUserRepository.GetQueryableAsync()
  366. join person in await _repository.GetQueryableAsync()
  367. on user.Id equals person.PersonId
  368. join questionRegister in await _questionRegisterRepository.GetQueryableAsync()
  369. on person.PersonId equals questionRegister.PersonId into emptyQuestionRegister
  370. from haveQuestionRegister in emptyQuestionRegister.DefaultIfEmpty()
  371. where personKinshipIds.Contains(user.Id)
  372. orderby user.CreationTime
  373. select new PersonDto
  374. {
  375. PersonId = user.Id,
  376. PersonNo = person.PersonNo,
  377. MedicalCenterId = person.MedicalCenterId,
  378. PersonName = user.Name,
  379. SexId = person.SexId,
  380. SexName = _cacheService.GetSexNameAsync(person.SexId).Result,
  381. MaritalStatusId = person.MaritalStatusId,
  382. MaritalStatusName = _cacheService.GetMaritalStatusNameAsync(person.MaritalStatusId).Result,
  383. BirthDate = person.BirthDate,
  384. NationId = person.NationId,
  385. NationName = _cacheService.GetNationNameAsync(person.NationId).Result,
  386. BirthPlaceId = person.BirthPlaceId,
  387. IdNo = person.IdNo,
  388. PostalCode = person.PostalCode,
  389. Email = user.Email,
  390. MobileTelephone = user.PhoneNumber,
  391. Address = person.Address,
  392. IdTypeId = person.IdTypeId,
  393. CountryCode = person.CountryCode,
  394. IsAllowBind = person.IsAllowBind,
  395. IsHaveQuestionRegister = haveQuestionRegister == null ? 'N' : 'Y',
  396. Height = person.Height,
  397. Weight = person.Weight
  398. }).Distinct().ToList();
  399. for (var i = 0; i < personList.Count; i++)
  400. {
  401. personList[i].DisplayOrder = i + 1;
  402. if (personList[i].PersonId == CurrentUser.Id)
  403. {
  404. personList[i].DisplayOrder = 0; //本人强行排第一个
  405. }
  406. }
  407. personList = personList.OrderBy(o => o.DisplayOrder).ToList();
  408. return personList;
  409. }
  410. /// <summary>
  411. /// 获取PDF体检报告
  412. /// </summary>
  413. /// <param name="input"></param>
  414. /// <returns></returns>
  415. /// <exception cref="UserFriendlyException"></exception>
  416. [HttpPost("api/app/Person/GetMedicalReportByPatientRegisterId")]
  417. public async Task<MedicalReportDto> GetMedicalReportByPatientRegisterIdAsync(PatientRegisterIdInputDto input)
  418. {
  419. var entity = await _patientRegisterRepository.GetAsync(o => o.PatientRegisterId == input.PatientRegisterId);
  420. if (string.IsNullOrWhiteSpace(entity.ReportFile))
  421. {
  422. throw new UserFriendlyException("没有报告单");
  423. }
  424. var Host = $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host.Host}:{_httpContextAccessor.HttpContext.Request.Host.Port}";
  425. var returnValue = new MedicalReportDto()
  426. {
  427. FilePath = entity.ReportFile,
  428. FileBase64 = Shentun.Utilities.FileHelper.ToBase64(Host + entity.ReportFile)
  429. };
  430. return returnValue;
  431. }
  432. /// <summary>
  433. /// 获取健康评估报告
  434. /// </summary>
  435. /// <param name="input"></param>
  436. /// <returns></returns>
  437. /// <exception cref="UserFriendlyException"></exception>
  438. [HttpPost("api/app/Person/GetMedicalHealthReportByPatientRegisterId")]
  439. public async Task<MedicalReportDto> GetMedicalHealthReportByPatientRegisterIdAsync(PatientRegisterIdInputDto input)
  440. {
  441. var entity = await _patientRegisterRepository.GetAsync(o => o.PatientRegisterId == input.PatientRegisterId);
  442. string baseAddress = _configuration.GetSection("MedicalHealthReport").GetSection("BaseAddress").Value;
  443. string reportListApiUrl = _configuration.GetSection("MedicalHealthReport").GetSection("ReportListApiUrl").Value;
  444. string reportApiUrl = _configuration.GetSection("MedicalHealthReport").GetSection("ReportApiUrl").Value;
  445. var medicalHealthReportListInputDto = new MedicalHealthReportListInputDto
  446. {
  447. Page = 1,
  448. Size = 10,
  449. RecordNo = entity.PatientRegisterNo
  450. };
  451. var medicalHealthReportListResult = await CallAppServiceAsync<MedicalHealthReportListInputDto, MedicalHealthReportListDto>(baseAddress, reportListApiUrl, medicalHealthReportListInputDto, "post");
  452. if (medicalHealthReportListResult.Code != 200
  453. || medicalHealthReportListResult.Data.FirstOrDefault() == null
  454. || medicalHealthReportListResult.Data.FirstOrDefault().ReportStatus != "1")
  455. {
  456. throw new UserFriendlyException("没有健康评估报告");
  457. }
  458. //报告单ID
  459. var resultId = medicalHealthReportListResult.Data.FirstOrDefault().ResultId;
  460. reportApiUrl = reportApiUrl + $"?resultId={resultId}"; //获取报告apiurl
  461. var medicalHealthReportResult = await CallAppServiceAsync<MedicalHealthReportDto, MedicalHealthReportDto>(baseAddress, reportApiUrl, null, "get");
  462. if (medicalHealthReportResult.Code != 200
  463. || string.IsNullOrWhiteSpace(medicalHealthReportResult.Data)
  464. )
  465. {
  466. throw new UserFriendlyException("没有健康评估报告");
  467. }
  468. string reportUrl = medicalHealthReportResult.Data;
  469. if (reportUrl.IndexOf(baseAddress) == -1)
  470. {
  471. //替换路径为代理地址
  472. reportUrl = reportUrl.Replace("http://", "").Replace("https://", "");
  473. reportUrl = baseAddress + reportUrl.Substring(reportUrl.IndexOf('/'));
  474. }
  475. var returnValue = new MedicalReportDto()
  476. {
  477. FilePath = reportUrl,
  478. FileBase64 = Shentun.Utilities.FileHelper.ToBase64(reportUrl)
  479. };
  480. return returnValue;
  481. }
  482. /// <summary>
  483. /// 获取校验码
  484. /// </summary>
  485. /// <param name="input"></param>
  486. /// <returns></returns>
  487. /// <exception cref="UserFriendlyException"></exception>
  488. [AllowAnonymous]
  489. [HttpPost("api/app/Person/GetSmsVerifyCode")]
  490. public async Task<SmsVerifyCodeDto> GetSmsVerifyCodeAsync(SmsVerifyCodeInputDto input)
  491. {
  492. if (input == null)
  493. {
  494. throw new UserFriendlyException("input不能为空");
  495. }
  496. //if (string.IsNullOrWhiteSpace(input.WechatOpenId))
  497. //{
  498. // throw new UserFriendlyException("WechatOpenId不能为空");
  499. //}
  500. //if (_cache.Get(CacheKeys.OpenIdKey + input.WechatOpenId) != input.WechatOpenId)
  501. //{
  502. // throw new UserFriendlyException("无效的WechatOpenId");
  503. //}
  504. if (string.IsNullOrWhiteSpace(input.SessionKey))
  505. {
  506. throw new UserFriendlyException("SessionKey不能为空");
  507. }
  508. if (_cache.Get(input.SessionKey) != input.SessionKeyValue)
  509. {
  510. throw new UserFriendlyException("无效的SessionKeyValue");
  511. }
  512. if (string.IsNullOrWhiteSpace(input.PersonName))
  513. {
  514. throw new UserFriendlyException("姓名不能为空");
  515. }
  516. if (string.IsNullOrWhiteSpace(input.MobileTelephone))
  517. {
  518. throw new UserFriendlyException("手机号码不能为空");
  519. }
  520. if (input.MobileTelephone.Length != 11)
  521. {
  522. throw new UserFriendlyException("手机号码必须为11位");
  523. }
  524. if (string.IsNullOrWhiteSpace(input.IdNo))
  525. {
  526. throw new UserFriendlyException("身份证号码不能为空");
  527. }
  528. input.IdNo = input.IdNo.Trim();
  529. if (input.IdNo.Length != 18)
  530. {
  531. throw new UserFriendlyException("身份证长度必须为18位");
  532. }
  533. //var sexByIdNo = ConvertExtr.ToSexByIdNo(idNo).ToCharArray();
  534. if (input.PersonId == null || input.PersonId == default(Guid))
  535. {
  536. var person = await _repository.FindAsync(o => o.IdNo == input.IdNo);
  537. if (person != null)
  538. {
  539. var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId &&
  540. o.PhoneNumber == input.MobileTelephone).FirstOrDefault();
  541. if (user == null)
  542. {
  543. throw new UserFriendlyException("该身份证号已注册,但手机号码不一致");
  544. }
  545. //if (!string.IsNullOrWhiteSpace(person.WechatOpenId))
  546. //{
  547. // throw new UserFriendlyException("该微信号已注册");
  548. //}
  549. }
  550. }
  551. var createSmsTaskDto = new CreateSmsTaskDto()
  552. {
  553. PersonId = "0001",
  554. PersonName = input.PersonName,
  555. MobileTelephone = input.MobileTelephone,
  556. CountryCode = "86",
  557. };
  558. var smsVerifyCodeKey = await SendVerifySms(createSmsTaskDto);
  559. var SmsVerifyCodeDto = new SmsVerifyCodeDto()
  560. {
  561. SmsVerifyCodeKey = smsVerifyCodeKey
  562. };
  563. return SmsVerifyCodeDto;
  564. }
  565. private async Task<UserTokenDto> GetTokenAsync(string request)
  566. {
  567. using var client = new HttpClient();
  568. HttpContent httpContent = new StringContent(request);
  569. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
  570. var url = _configuration.GetSection("AuthServer").
  571. GetSection("Authority").Value + "/connect/token";
  572. var tokenResult = await client.PostAsync(url
  573. , httpContent);
  574. var tokenResultStr = await tokenResult.Content.ReadAsStringAsync();
  575. if (tokenResult.IsSuccessStatusCode)
  576. {
  577. if (!string.IsNullOrEmpty(tokenResultStr))
  578. {
  579. if (tokenResultStr.ToLower().Contains("openid"))
  580. {
  581. var wechatUserDto = JsonSerializer.Deserialize<WechatUserDto>(tokenResultStr,
  582. new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
  583. var userTokenDto = new UserTokenDto
  584. {
  585. IsNewUser = "Y",
  586. OpenId = wechatUserDto.OpenId
  587. };
  588. var options = new DistributedCacheEntryOptions()
  589. .SetAbsoluteExpiration(TimeSpan.FromDays(3));
  590. _cache.Set(CacheKeys.OpenIdKey + wechatUserDto.OpenId,
  591. wechatUserDto.OpenId, options);
  592. return userTokenDto;
  593. }
  594. else
  595. {
  596. var signResult = JsonSerializer.Deserialize<SignInResultDto>(tokenResultStr,
  597. new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
  598. var userTokenDto = new UserTokenDto
  599. {
  600. IsNewUser = "N",
  601. AccessToken = signResult.access_token,
  602. RefreshToken = signResult.refresh_token
  603. };
  604. return userTokenDto;
  605. }
  606. }
  607. else
  608. {
  609. throw new UserFriendlyException("token值为空");
  610. }
  611. }
  612. else
  613. {
  614. //tokenResultStr = tokenResultStr.Replace("<", "").Replace(">", "");
  615. //var grantErrorDto = JsonSerializer.Deserialize<GrantErrorDto>(tokenResultStr,
  616. // new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
  617. throw new UserFriendlyException("获取token失败:" + tokenResultStr);
  618. }
  619. }
  620. public async Task<string> SendVerifySms(CreateSmsTaskDto createSmsTaskDto)
  621. {
  622. if (createSmsTaskDto == null)
  623. {
  624. throw new UserFriendlyException("createSmsTaskDto参数不能为空");
  625. }
  626. var message = Shentun.Utilities.Encrypt.RandomHelper.CreateRandom(Utilities.Enums.RandomType.Num, 6);
  627. var verifySmsValidTimeStr = _configuration.GetSection("Sms")
  628. .GetSection("VerifySmsValidTime").Value;
  629. if (!int.TryParse(verifySmsValidTimeStr, out var verifySmsValidTime))
  630. {
  631. throw new Exception("解析校验短信有效时间错误");
  632. }
  633. createSmsTaskDto.Content = message + "|" + verifySmsValidTime.ToString();
  634. //发送短信
  635. createSmsTaskDto.TaskCycleType = '0';
  636. await SmsClientHelper.CreateVerifySmsTask(createSmsTaskDto);
  637. //存储短信校验码
  638. var options = new DistributedCacheEntryOptions()
  639. .SetAbsoluteExpiration(TimeSpan.FromMinutes(verifySmsValidTime));
  640. var smsVerifyCodeKey = CacheKeys.SmsKey + createSmsTaskDto.MobileTelephone + Guid.NewGuid().ToString();
  641. _cache.Set(smsVerifyCodeKey, message, options);
  642. return smsVerifyCodeKey;
  643. }
  644. private async static Task<TOut> CallAppServiceAsync<TInput, TOut>(string baseAddress, string url, TInput? data, string method = "post")
  645. {
  646. using (var httpClientHandler = new HttpClientHandler())
  647. {
  648. using (var httpClient = new HttpClient(httpClientHandler))
  649. {
  650. httpClient.BaseAddress = new Uri(baseAddress);
  651. httpClient.DefaultRequestHeaders.Accept.Add(
  652. new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
  653. var jsonOptions = new JsonSerializerOptions
  654. {
  655. WriteIndented = true, // 设置为true以便于可读性更好的JSON输出
  656. PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
  657. // 如果你想要对日期进行格式化,可以使用JsonConverter
  658. Converters = { new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss") }
  659. };
  660. var sendData = System.Text.Json.JsonSerializer.Serialize(data, jsonOptions);
  661. using (HttpContent httpContent = new StringContent(sendData))
  662. {
  663. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  664. HttpResponseMessage response = null;
  665. if (method == "post")
  666. {
  667. response = await httpClient.PostAsync(url, httpContent);
  668. }
  669. else
  670. {
  671. response = await httpClient.GetAsync(url);
  672. }
  673. string result;
  674. if (!response.IsSuccessStatusCode)
  675. {
  676. result = response.Content.ReadAsStringAsync().Result;
  677. throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
  678. }
  679. result = await response.Content.ReadAsStringAsync();
  680. var resultDto = System.Text.Json.JsonSerializer.Deserialize<TOut>(result, jsonOptions);
  681. return resultDto;
  682. }
  683. }
  684. }
  685. }
  686. }
  687. }