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.

701 lines
30 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
  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. using (var unitOfWork = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true))
  142. {
  143. var entity = ObjectMapper.Map<CreatePersonDto, Person>(input);
  144. if (string.IsNullOrWhiteSpace(input.JsCode))
  145. {
  146. throw new UserFriendlyException("jsCode不能为空");
  147. }
  148. if (string.IsNullOrWhiteSpace(input.WechatOpenId))
  149. {
  150. throw new UserFriendlyException("WechatOpenId不能为空");
  151. }
  152. if (_cache.Get(CacheKeys.OpenIdKey + input.WechatOpenId) != input.WechatOpenId)
  153. {
  154. throw new UserFriendlyException("无效的WechatOpenId");
  155. }
  156. if (string.IsNullOrWhiteSpace(input.MobileTelephone))
  157. {
  158. throw new UserFriendlyException("手机号码不能为空");
  159. }
  160. if (input.MobileTelephone.Length != 11)
  161. {
  162. throw new UserFriendlyException("手机号码必须为11位");
  163. }
  164. if (string.IsNullOrWhiteSpace(input.SmsVerifyCodeKey))
  165. {
  166. throw new UserFriendlyException("短信校验码键不能为空");
  167. }
  168. if (_cache.Get(input.SmsVerifyCodeKey) != input.SmsVerifyCode)
  169. {
  170. throw new UserFriendlyException("无效的短信校验码或已过期");
  171. }
  172. var person = await _repository.FindAsync(o => o.IdNo == input.IdNo);
  173. if (person != null)
  174. {
  175. var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId &&
  176. o.PhoneNumber == input.MobileTelephone).FirstOrDefault();
  177. if (user == null)
  178. {
  179. throw new UserFriendlyException("该身份证号已注册,但手机号码不一致");
  180. }
  181. if (!string.IsNullOrWhiteSpace(person.WechatOpenId))
  182. {
  183. throw new UserFriendlyException("该微信号已注册");
  184. }
  185. person.WechatOpenId = input.WechatOpenId;
  186. await _repository.UpdateAsync(person);
  187. }
  188. else
  189. {
  190. entity.WechatOpenId = input.WechatOpenId;
  191. var userWithPerson = await _personManager.CreateAsync(entity, input.PersonName,
  192. input.Email, input.MobileTelephone);
  193. await _identityUserRepository.InsertAsync(userWithPerson.User);
  194. await _repository.InsertAsync(userWithPerson.Person);
  195. //设置密码
  196. (await _userManager.RemovePasswordAsync(userWithPerson.User)).CheckErrors();
  197. (await _userManager.AddPasswordAsync(userWithPerson.User, Shentun.Utilities.
  198. Encrypt.RandomHelper.CreateRandom(Utilities.Enums.RandomType.NumAndChar, 10) + "0Cz*")).CheckErrors();
  199. }
  200. await unitOfWork.CompleteAsync();
  201. }
  202. using (var unitOfWork = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: false))
  203. {
  204. var weChatClientId = _configuration.GetSection("AuthServer").GetSection("WeChatClientId").Value;
  205. var secret = _configuration.GetSection("AuthServer").GetSection("WeChatClientSecret").Value;
  206. var dic = new Dictionary<string, object>
  207. {
  208. {"jsCode",input.JsCode},
  209. {"client_id",weChatClientId},
  210. {"client_secret",secret},
  211. {"grant_type",WeChatGrant.GrantType},
  212. {"scope","WeChat offline_access"}
  213. };
  214. var dicStr = dic.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n);
  215. var token = await GetTokenAsync(dicStr);
  216. //var entityDto = ObjectMapper.Map<Person, PersonDto>(userWithPerson.Person);
  217. await unitOfWork.CompleteAsync();
  218. return token;
  219. }
  220. }
  221. /// <summary>
  222. /// 创建亲属
  223. /// </summary>
  224. /// <param name="input"></param>
  225. /// <returns></returns>
  226. /// <exception cref="UserFriendlyException"></exception>
  227. [HttpPost("api/app/Person/CreatePersonKinship")]
  228. public async Task CreatePersonKinshipAsync(CreatePersonKinshipDto input)
  229. {
  230. var entity = ObjectMapper.Map<CreatePersonKinshipDto, Person>(input);
  231. if (string.IsNullOrWhiteSpace(input.KinshipId))
  232. {
  233. throw new UserFriendlyException("亲属关系不能为空");
  234. }
  235. if (string.IsNullOrWhiteSpace(input.SmsVerifyCodeKey))
  236. {
  237. throw new UserFriendlyException("短信校验码键不能为空");
  238. }
  239. if (_cache.Get(input.SmsVerifyCodeKey) != input.SmsVerifyCode)
  240. {
  241. throw new UserFriendlyException("无效的短信校验码或已过期");
  242. }
  243. var person = await _repository.FindAsync(o => o.IdNo == input.IdNo);
  244. if (person != null)
  245. {
  246. var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId &&
  247. o.PhoneNumber == input.MobileTelephone).FirstOrDefault();
  248. if (user == null)
  249. {
  250. throw new UserFriendlyException("该身份证号已注册,但手机号码不一致");
  251. }
  252. var personKinshipExist = new PersonKinship()
  253. {
  254. PersonId = person.PersonId,
  255. ParentPersonId = (Guid)CurrentUser.Id,
  256. KinshipId = input.KinshipId,
  257. };
  258. await _personKinshipRepository.InsertAsync(personKinshipExist);
  259. return;
  260. }
  261. var userWithPerson = await _personManager.CreateAsync(entity, input.PersonName,
  262. input.Email, input.MobileTelephone);
  263. var personKinship = new PersonKinship()
  264. {
  265. PersonId = userWithPerson.Person.PersonId,
  266. ParentPersonId = (Guid)CurrentUser.Id,
  267. KinshipId = input.KinshipId,
  268. };
  269. await _identityUserRepository.InsertAsync(userWithPerson.User);
  270. await _repository.InsertAsync(userWithPerson.Person);
  271. await _personKinshipRepository.InsertAsync(personKinship);
  272. //设置密码
  273. (await _userManager.RemovePasswordAsync(userWithPerson.User)).CheckErrors();
  274. (await _userManager.AddPasswordAsync(userWithPerson.User, Shentun.Utilities.
  275. Encrypt.RandomHelper.CreateRandom(Utilities.Enums.RandomType.NumAndChar, 10) + "0Cz*")).CheckErrors();
  276. }
  277. /// <summary>
  278. /// 获取体检次数列表
  279. /// </summary>
  280. /// <param name="input"></param>
  281. /// <returns></returns>
  282. [HttpPost("api/app/Person/GetMedicalTimesListByPersonId")]
  283. public async Task<List<PersonMedicalTimesDto>> GetMedicalTimesListByPersonIdAsync(PersonIdInputDto input)
  284. {
  285. var entityList = (from user in await _identityUserRepository.GetQueryableAsync()
  286. join person in await _repository.GetQueryableAsync()
  287. on user.Id equals person.PersonId
  288. join patient in await _patientRepository.GetQueryableAsync()
  289. on new { idNo = person.IdNo, phone = user.PhoneNumber } equals new { idNo = patient.IdNo, phone = patient.MobileTelephone }
  290. join patientRegister in await _patientRegisterRepository.GetQueryableAsync()
  291. on patient.PatientId equals patientRegister.PatientId
  292. where user.Id == input.PersonId &&
  293. (patientRegister.CompleteFlag == PatientRegisterCompleteFlag.SumCheck)
  294. orderby patientRegister.MedicalStartDate
  295. select new PersonMedicalTimesDto()
  296. {
  297. PatientRegisterId = patientRegister.PatientRegisterId,
  298. PersonName = patient.PatientName,
  299. MedicalStartDate = patientRegister.MedicalStartDate,
  300. }).ToList();
  301. return entityList;
  302. }
  303. /// <summary>
  304. /// 获取本人和亲属列表
  305. /// </summary>
  306. /// <returns></returns>
  307. [HttpPost("api/app/Person/GetPersonKinshipList")]
  308. public async Task<List<PersonDto>> GetPersonKinshipList()
  309. {
  310. var personKinshipIds = (await _personKinshipRepository.GetQueryableAsync())
  311. .Where(o => o.ParentPersonId == CurrentUser.Id)
  312. .Select(o => o.PersonId).ToList();
  313. personKinshipIds.Add((Guid)CurrentUser.Id);
  314. var personList = (from user in await _identityUserRepository.GetQueryableAsync()
  315. join person in await _repository.GetQueryableAsync()
  316. on user.Id equals person.PersonId
  317. join questionRegister in await _questionRegisterRepository.GetQueryableAsync()
  318. on person.PersonId equals questionRegister.PersonId into emptyQuestionRegister
  319. from haveQuestionRegister in emptyQuestionRegister.DefaultIfEmpty()
  320. where personKinshipIds.Contains(user.Id)
  321. orderby user.CreationTime
  322. select new PersonDto
  323. {
  324. PersonId = user.Id,
  325. PersonName = user.Name,
  326. SexId = person.SexId,
  327. SexName = _cacheService.GetSexNameAsync(person.SexId).Result,
  328. MaritalStatusId = person.MaritalStatusId,
  329. MaritalStatusName = _cacheService.GetMaritalStatusNameAsync(person.MaritalStatusId).Result,
  330. IdNo = person.IdNo,
  331. MobileTelephone = user.PhoneNumber,
  332. IsHaveQuestionRegister = haveQuestionRegister == null ? 'N' : 'Y'
  333. }).Distinct().ToList();
  334. for (var i = 0; i < personList.Count; i++)
  335. {
  336. personList[i].DisplayOrder = i + 1;
  337. if (personList[i].PersonId == CurrentUser.Id)
  338. {
  339. personList[i].DisplayOrder = 0; //本人强行排第一个
  340. }
  341. }
  342. personList = personList.OrderBy(o => o.DisplayOrder).ToList();
  343. return personList;
  344. }
  345. /// <summary>
  346. /// 获取PDF体检报告
  347. /// </summary>
  348. /// <param name="input"></param>
  349. /// <returns></returns>
  350. /// <exception cref="UserFriendlyException"></exception>
  351. [HttpPost("api/app/Person/GetMedicalReportByPatientRegisterId")]
  352. public async Task<MedicalReportDto> GetMedicalReportByPatientRegisterIdAsync(PatientRegisterIdInputDto input)
  353. {
  354. var entity = await _patientRegisterRepository.GetAsync(o => o.PatientRegisterId == input.PatientRegisterId);
  355. if (string.IsNullOrWhiteSpace(entity.ReportFile))
  356. {
  357. throw new UserFriendlyException("没有报告单");
  358. }
  359. var Host = $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host.Host}:{_httpContextAccessor.HttpContext.Request.Host.Port}";
  360. var returnValue = new MedicalReportDto()
  361. {
  362. FilePath = entity.ReportFile,
  363. FileBase64 = Shentun.Utilities.FileHelper.ToBase64(Host + entity.ReportFile)
  364. };
  365. return returnValue;
  366. }
  367. /// <summary>
  368. /// 获取健康评估报告
  369. /// </summary>
  370. /// <param name="input"></param>
  371. /// <returns></returns>
  372. /// <exception cref="UserFriendlyException"></exception>
  373. [HttpPost("api/app/Person/GetMedicalHealthReportByPatientRegisterId")]
  374. public async Task<MedicalReportDto> GetMedicalHealthReportByPatientRegisterIdAsync(PatientRegisterIdInputDto input)
  375. {
  376. var entity = await _patientRegisterRepository.GetAsync(o => o.PatientRegisterId == input.PatientRegisterId);
  377. string baseAddress = _configuration.GetSection("MedicalHealthReport").GetSection("BaseAddress").Value;
  378. string reportListApiUrl = _configuration.GetSection("MedicalHealthReport").GetSection("ReportListApiUrl").Value;
  379. string reportApiUrl = _configuration.GetSection("MedicalHealthReport").GetSection("ReportApiUrl").Value;
  380. var medicalHealthReportListInputDto = new MedicalHealthReportListInputDto
  381. {
  382. Page = 1,
  383. Size = 10,
  384. RecordNo = entity.PatientRegisterNo
  385. };
  386. var medicalHealthReportListResult = await CallAppServiceAsync<MedicalHealthReportListInputDto, MedicalHealthReportListDto>(baseAddress, reportListApiUrl, medicalHealthReportListInputDto, "post");
  387. if (medicalHealthReportListResult.Code == 200
  388. || medicalHealthReportListResult.Data.FirstOrDefault() == null
  389. || medicalHealthReportListResult.Data.FirstOrDefault().ReportStatus != "1")
  390. {
  391. throw new UserFriendlyException("没有报告单");
  392. }
  393. //报告单ID
  394. var resultId = medicalHealthReportListResult.Data.FirstOrDefault().ResultId;
  395. reportApiUrl = reportApiUrl + $"?resultId={resultId}"; //获取报告apiurl
  396. var medicalHealthReportResult = await CallAppServiceAsync<MedicalHealthReportDto, MedicalHealthReportDto>(baseAddress, reportApiUrl, null, "get");
  397. if (medicalHealthReportResult.Code == 200
  398. || string.IsNullOrWhiteSpace(medicalHealthReportResult.Data)
  399. )
  400. {
  401. throw new UserFriendlyException("没有报告单");
  402. }
  403. string reportUrl= medicalHealthReportResult.Data;
  404. var returnValue = new MedicalReportDto()
  405. {
  406. FilePath = reportUrl,
  407. FileBase64 = Shentun.Utilities.FileHelper.ToBase64(reportUrl)
  408. };
  409. return returnValue;
  410. }
  411. /// <summary>
  412. /// 获取校验码
  413. /// </summary>
  414. /// <param name="input"></param>
  415. /// <returns></returns>
  416. /// <exception cref="UserFriendlyException"></exception>
  417. [AllowAnonymous]
  418. [HttpPost("api/app/Person/GetSmsVerifyCode")]
  419. public async Task<SmsVerifyCodeDto> GetSmsVerifyCodeAsync(SmsVerifyCodeInputDto input)
  420. {
  421. if (input == null)
  422. {
  423. throw new UserFriendlyException("input不能为空");
  424. }
  425. //if (string.IsNullOrWhiteSpace(input.WechatOpenId))
  426. //{
  427. // throw new UserFriendlyException("WechatOpenId不能为空");
  428. //}
  429. //if (_cache.Get(CacheKeys.OpenIdKey + input.WechatOpenId) != input.WechatOpenId)
  430. //{
  431. // throw new UserFriendlyException("无效的WechatOpenId");
  432. //}
  433. if (string.IsNullOrWhiteSpace(input.SessionKey))
  434. {
  435. throw new UserFriendlyException("SessionKey不能为空");
  436. }
  437. if (_cache.Get(input.SessionKey) != input.SessionKeyValue)
  438. {
  439. throw new UserFriendlyException("无效的SessionKeyValue");
  440. }
  441. if (string.IsNullOrWhiteSpace(input.PersonName))
  442. {
  443. throw new UserFriendlyException("姓名不能为空");
  444. }
  445. if (string.IsNullOrWhiteSpace(input.MobileTelephone))
  446. {
  447. throw new UserFriendlyException("手机号码不能为空");
  448. }
  449. if (input.MobileTelephone.Length != 11)
  450. {
  451. throw new UserFriendlyException("手机号码必须为11位");
  452. }
  453. if (string.IsNullOrWhiteSpace(input.IdNo))
  454. {
  455. throw new UserFriendlyException("身份证号码不能为空");
  456. }
  457. input.IdNo = input.IdNo.Trim();
  458. if (input.IdNo.Length != 18)
  459. {
  460. throw new UserFriendlyException("身份证长度必须为18位");
  461. }
  462. //var sexByIdNo = ConvertExtr.ToSexByIdNo(idNo).ToCharArray();
  463. var person = await _repository.FindAsync(o => o.IdNo == input.IdNo);
  464. if (person != null)
  465. {
  466. var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId &&
  467. o.PhoneNumber == input.MobileTelephone).FirstOrDefault();
  468. if (user == null)
  469. {
  470. throw new UserFriendlyException("该身份证号已注册,但手机号码不一致");
  471. }
  472. //if (!string.IsNullOrWhiteSpace(person.WechatOpenId))
  473. //{
  474. // throw new UserFriendlyException("该微信号已注册");
  475. //}
  476. }
  477. var createSmsTaskDto = new CreateSmsTaskDto()
  478. {
  479. PersonId = "0001",
  480. PersonName = input.PersonName,
  481. MobileTelephone = input.MobileTelephone,
  482. CountryCode = "86",
  483. };
  484. var smsVerifyCodeKey = await SendVerifySms(createSmsTaskDto);
  485. var SmsVerifyCodeDto = new SmsVerifyCodeDto()
  486. {
  487. SmsVerifyCodeKey = smsVerifyCodeKey
  488. };
  489. return SmsVerifyCodeDto;
  490. }
  491. private async Task<UserTokenDto> GetTokenAsync(string request)
  492. {
  493. using var client = new HttpClient();
  494. HttpContent httpContent = new StringContent(request);
  495. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
  496. var url = _configuration.GetSection("AuthServer").
  497. GetSection("Authority").Value + "/connect/token";
  498. var tokenResult = await client.PostAsync(url
  499. , httpContent);
  500. var tokenResultStr = await tokenResult.Content.ReadAsStringAsync();
  501. if (tokenResult.IsSuccessStatusCode)
  502. {
  503. if (!string.IsNullOrEmpty(tokenResultStr))
  504. {
  505. if (tokenResultStr.ToLower().Contains("openid"))
  506. {
  507. var wechatUserDto = JsonSerializer.Deserialize<WechatUserDto>(tokenResultStr,
  508. new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
  509. var userTokenDto = new UserTokenDto
  510. {
  511. IsNewUser = "Y",
  512. OpenId = wechatUserDto.OpenId
  513. };
  514. var options = new DistributedCacheEntryOptions()
  515. .SetAbsoluteExpiration(TimeSpan.FromDays(3));
  516. _cache.Set(CacheKeys.OpenIdKey + wechatUserDto.OpenId,
  517. wechatUserDto.OpenId, options);
  518. return userTokenDto;
  519. }
  520. else
  521. {
  522. var signResult = JsonSerializer.Deserialize<SignInResultDto>(tokenResultStr,
  523. new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
  524. var userTokenDto = new UserTokenDto
  525. {
  526. IsNewUser = "N",
  527. AccessToken = signResult.access_token,
  528. RefreshToken = signResult.refresh_token
  529. };
  530. return userTokenDto;
  531. }
  532. }
  533. else
  534. {
  535. throw new UserFriendlyException("token值为空");
  536. }
  537. }
  538. else
  539. {
  540. //tokenResultStr = tokenResultStr.Replace("<", "").Replace(">", "");
  541. //var grantErrorDto = JsonSerializer.Deserialize<GrantErrorDto>(tokenResultStr,
  542. // new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
  543. throw new UserFriendlyException("获取token失败:" + tokenResultStr);
  544. }
  545. }
  546. public async Task<string> SendVerifySms(CreateSmsTaskDto createSmsTaskDto)
  547. {
  548. if (createSmsTaskDto == null)
  549. {
  550. throw new UserFriendlyException("createSmsTaskDto参数不能为空");
  551. }
  552. var message = Shentun.Utilities.Encrypt.RandomHelper.CreateRandom(Utilities.Enums.RandomType.Num, 6);
  553. var verifySmsValidTimeStr = _configuration.GetSection("Sms")
  554. .GetSection("VerifySmsValidTime").Value;
  555. if (!int.TryParse(verifySmsValidTimeStr, out var verifySmsValidTime))
  556. {
  557. throw new Exception("解析校验短信有效时间错误");
  558. }
  559. createSmsTaskDto.Content = message + "|" + verifySmsValidTime.ToString();
  560. //发送短信
  561. createSmsTaskDto.TaskCycleType = '0';
  562. await SmsClientHelper.CreateVerifySmsTask(createSmsTaskDto);
  563. //存储短信校验码
  564. var options = new DistributedCacheEntryOptions()
  565. .SetAbsoluteExpiration(TimeSpan.FromMinutes(verifySmsValidTime));
  566. var smsVerifyCodeKey = CacheKeys.SmsKey + createSmsTaskDto.MobileTelephone + Guid.NewGuid().ToString();
  567. _cache.Set(smsVerifyCodeKey, message, options);
  568. return smsVerifyCodeKey;
  569. }
  570. private async static Task<TOut> CallAppServiceAsync<TInput, TOut>(string baseAddress, string url, TInput? data, string method = "post")
  571. {
  572. using (var httpClientHandler = new HttpClientHandler())
  573. {
  574. using (var httpClient = new HttpClient(httpClientHandler))
  575. {
  576. httpClient.BaseAddress = new Uri(baseAddress);
  577. httpClient.DefaultRequestHeaders.Accept.Add(
  578. new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
  579. var jsonOptions = new JsonSerializerOptions
  580. {
  581. WriteIndented = true, // 设置为true以便于可读性更好的JSON输出
  582. PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
  583. // 如果你想要对日期进行格式化,可以使用JsonConverter
  584. Converters = { new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss") }
  585. };
  586. var sendData = System.Text.Json.JsonSerializer.Serialize(data, jsonOptions);
  587. using (HttpContent httpContent = new StringContent(sendData))
  588. {
  589. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  590. HttpResponseMessage response = null;
  591. if (method == "post")
  592. {
  593. response = await httpClient.PostAsync(url, httpContent);
  594. }
  595. else
  596. {
  597. response = await httpClient.GetAsync(url);
  598. }
  599. string result;
  600. if (!response.IsSuccessStatusCode)
  601. {
  602. result = response.Content.ReadAsStringAsync().Result;
  603. throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
  604. }
  605. result = await response.Content.ReadAsStringAsync();
  606. var resultDto = System.Text.Json.JsonSerializer.Deserialize<TOut>(result, jsonOptions);
  607. return resultDto;
  608. }
  609. }
  610. }
  611. }
  612. }
  613. }