using Shentun.WebPeis.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Volo.Abp.Application.Services; using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Repositories; using Volo.Abp.Users; using Shentun.WebPeis.Wechats; using Microsoft.Extensions.Configuration; using System.Net.Http; using System.Net; using System.Text.Json; using Volo.Abp.Identity; using Volo.Abp; using Shentun.WebPeis.Enums; using System.Net.Http.Headers; using Microsoft.AspNetCore.Mvc; using OpenIddict.Abstractions; using Microsoft.AspNetCore.Identity; using Volo.Abp.ObjectMapping; using Microsoft.AspNetCore.Authorization; using Volo.Abp.Caching; using NPOI.SS.Formula.Functions; using System.Linq.Dynamic.Core.Tokenizer; using Microsoft.Extensions.Caching.Distributed; using Volo.Abp.Uow; using Scriban.Parsing; using System.IdentityModel.Tokens.Jwt; using Shentun.WebPeis.PatientRegisters; using Microsoft.AspNetCore.Http; using System.IO; using Shentun.WebPeis.CustomerOrgs; using Shentun.Utilities.Enums; using Shentun.Sms.Client; using Shentun.Utilities; using IdentityModel; using Shentun.WebPeis.SysParmValues; using Scriban.Syntax; using static SKIT.FlurlHttpClient.Wechat.TenpayV3.Models.DepositMarketingMemberCardOpenCardCodesResponse.Types; namespace Shentun.WebPeis.Persons { /// /// 微信人员 /// [ApiExplorerSettings(GroupName = "Work")] [Authorize] public class PersonAppService : ApplicationService { private readonly IRepository _questionRegisterRepository; private readonly IConfiguration _configuration; private readonly IRepository _identityUserRepository; private readonly IdentityUserManager _userManager; private readonly IRepository _repository; private readonly PersonManager _personManager; private readonly IDistributedCache _cache; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly IRepository _personKinshipRepository; private readonly IRepository _patientRegisterRepository; private readonly IRepository _patientRepository; private readonly CacheService _cacheService; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IRepository _customerOrgRepository; private readonly SysParmValueManager _sysParmValueManager; private readonly IRepository _registerCheckRepository; private readonly IRepository _registerCheckAsbitemRepository; private readonly IRepository _asbitemRepository; private readonly IRepository _customerOrgRegisterRepository; public PersonAppService(IRepository repository, IConfiguration configuration, IRepository identityUserRepository, IdentityUserManager userManager, PersonManager personManager, IUnitOfWorkManager unitOfWorkManager, IDistributedCache cache, IRepository personKinshipRepository, IRepository patientRegisterRepository, IRepository patientRepository, CacheService cacheService, IHttpContextAccessor httpContextAccessor, IRepository customerOrgRepository, IRepository questionRegisterRepository, SysParmValueManager sysParmValueManager, IRepository registerCheckRepository, IRepository registerCheckAsbitemRepository, IRepository asbitemRepository, IRepository customerOrgRegisterRepository) { _repository = repository; _configuration = configuration; _identityUserRepository = identityUserRepository; _userManager = userManager; _personManager = personManager; _unitOfWorkManager = unitOfWorkManager; _cache = cache; _personKinshipRepository = personKinshipRepository; _patientRegisterRepository = patientRegisterRepository; _patientRepository = patientRepository; _cacheService = cacheService; _httpContextAccessor = httpContextAccessor; _customerOrgRepository = customerOrgRepository; _questionRegisterRepository = questionRegisterRepository; _sysParmValueManager = sysParmValueManager; _registerCheckRepository = registerCheckRepository; _registerCheckAsbitemRepository = registerCheckAsbitemRepository; _asbitemRepository = asbitemRepository; _customerOrgRegisterRepository = customerOrgRegisterRepository; } public async Task GetByIdAsync(PersonIdInputDto input) { var entity = await _repository.GetAsync(o => o.PersonId == input.PersonId); var entityDto = ObjectMapper.Map(entity); var user = await _identityUserRepository.GetAsync(input.PersonId); entityDto.MobileTelephone = user.PhoneNumber; entityDto.PersonName = user.Name; entityDto.SexName = await _cacheService.GetSexNameAsync(entityDto.SexId); entityDto.MaritalStatusName = await _cacheService.GetMaritalStatusNameAsync(entityDto.MaritalStatusId); entityDto.NationName = await _cacheService.GetNationNameAsync(entityDto.NationId); var questionRegister = await _questionRegisterRepository.FindAsync(o => o.PersonId == input.PersonId); if (questionRegister != null) { entityDto.IsHaveQuestionRegister = 'Y'; } else { entityDto.IsHaveQuestionRegister = 'N'; } return entityDto; } /// /// 微信用户登录 /// /// /// [AllowAnonymous] [HttpPost("api/app/Person/WeChatUserLogin")] public async Task WeChatUserLoginAsync(WechatUserJsCodeInputDto input) { var weChatClientId = _configuration.GetSection("AuthServer").GetSection("WeChatClientId").Value; var secret = _configuration.GetSection("AuthServer").GetSection("WeChatClientSecret").Value; var commonScopes = new List { OpenIddictConstants.Permissions.Scopes.Address, OpenIddictConstants.Permissions.Scopes.Email, OpenIddictConstants.Permissions.Scopes.Phone, OpenIddictConstants.Permissions.Scopes.Profile, OpenIddictConstants.Permissions.Scopes.Roles, "WebPeis" }; var dic = new Dictionary { {"jsCode",input.JsCode}, {"client_id",weChatClientId}, {"client_secret",secret}, {"grant_type",WeChatGrant.GrantType}, {"scope","WeChat offline_access"} }; var dicStr = dic.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n); var token = await GetTokenAsync(dicStr); var options = new DistributedCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromDays(3)); var sessionKey = CacheKeys.SessionKey + Guid.NewGuid().ToString(); var sessionKeyValue = Guid.NewGuid().ToString(); _cache.Set(sessionKey, sessionKeyValue, options); token.SessionKey = sessionKey; token.SessionKeyValue = sessionKeyValue; var isOpenPersonalAppointmentStr = await _sysParmValueManager.GetSysParmValueAsync(Guid.Empty, "is_open_personal_appointment"); if (string.IsNullOrWhiteSpace(isOpenPersonalAppointmentStr)) isOpenPersonalAppointmentStr = "Y"; token.IsOpenPersonalAppointment = Convert.ToChar(isOpenPersonalAppointmentStr); return token; } [AllowAnonymous] [HttpPost("api/app/Person/Create")] [UnitOfWork(IsDisabled = false)] public async Task CreateAsync(CreatePersonDto input) { if (input == null) throw new UserFriendlyException("input参数不能为空"); using (var unitOfWork = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) { var entity = ObjectMapper.Map(input); if (string.IsNullOrWhiteSpace(input.JsCode)) { throw new UserFriendlyException("jsCode不能为空"); } if (string.IsNullOrWhiteSpace(input.WechatOpenId)) { throw new UserFriendlyException("WechatOpenId不能为空"); } if (_cache.Get(CacheKeys.OpenIdKey + input.WechatOpenId) != input.WechatOpenId) { throw new UserFriendlyException("无效的WechatOpenId"); } if (string.IsNullOrWhiteSpace(input.MobileTelephone)) { throw new UserFriendlyException("手机号码不能为空"); } if (input.MobileTelephone.Length != 11) { throw new UserFriendlyException("手机号码必须为11位"); } if (string.IsNullOrWhiteSpace(input.SmsVerifyCodeKey)) { throw new UserFriendlyException("短信校验码键不能为空"); } if (_cache.Get(input.SmsVerifyCodeKey) != input.SmsVerifyCode) { throw new UserFriendlyException("无效的短信校验码或已过期"); } var person = await _repository.FindAsync(o => o.IdNo == input.IdNo); if (person != null) { var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId && o.PhoneNumber == input.MobileTelephone).FirstOrDefault(); if (user == null) { throw new UserFriendlyException("该身份证号已注册,但手机号码不一致"); } if (!string.IsNullOrWhiteSpace(person.WechatOpenId)) { throw new UserFriendlyException("该身份证跟手机号已被其他微信号注册"); } person.WechatOpenId = input.WechatOpenId; await _repository.UpdateAsync(person); } else { entity.WechatOpenId = input.WechatOpenId; var userWithPerson = await _personManager.CreateAsync(entity, input.PersonName, input.Email, input.MobileTelephone); await _identityUserRepository.InsertAsync(userWithPerson.User); await _repository.InsertAsync(userWithPerson.Person); //设置密码 (await _userManager.RemovePasswordAsync(userWithPerson.User)).CheckErrors(); (await _userManager.AddPasswordAsync(userWithPerson.User, Shentun.Utilities. Encrypt.RandomHelper.CreateRandom(Utilities.Enums.RandomType.NumAndChar, 10) + "0Cz*")).CheckErrors(); } await unitOfWork.CompleteAsync(); } using (var unitOfWork = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: false)) { var weChatClientId = _configuration.GetSection("AuthServer").GetSection("WeChatClientId").Value; var secret = _configuration.GetSection("AuthServer").GetSection("WeChatClientSecret").Value; var dic = new Dictionary { {"jsCode",input.JsCode}, {"client_id",weChatClientId}, {"client_secret",secret}, {"grant_type",WeChatGrant.GrantType}, {"scope","WeChat offline_access"} }; var dicStr = dic.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n); var token = await GetTokenAsync(dicStr); //var entityDto = ObjectMapper.Map(userWithPerson.Person); await unitOfWork.CompleteAsync(); return token; } } /// /// 更新 /// /// /// /// [HttpPost("api/app/Person/Update")] public async Task UpdateAsync(UpdatePersonDto input) { if (input == null) throw new UserFriendlyException("input参数不能为空"); var entity = ObjectMapper.Map(input); if (string.IsNullOrWhiteSpace(input.MobileTelephone)) { throw new UserFriendlyException("手机号码不能为空"); } if (input.MobileTelephone.Length != 11) { throw new UserFriendlyException("手机号码必须为11位"); } if (string.IsNullOrWhiteSpace(input.SmsVerifyCodeKey)) { throw new UserFriendlyException("短信校验码键不能为空"); } if (_cache.Get(input.SmsVerifyCodeKey) != input.SmsVerifyCode) { throw new UserFriendlyException("无效的短信校验码或已过期"); } //更新人员信息 var person = await _repository.GetAsync(o => o.PersonId == input.PersonId); await _personManager.UpdateAsync(entity, person); await _repository.UpdateAsync(person); //更新用户信息 var user = await _identityUserRepository.GetAsync(person.PersonId); user.Name = input.PersonName; user.SetPhoneNumber(input.MobileTelephone, false); await _identityUserRepository.UpdateAsync(user); return ObjectMapper.Map(person); } /// /// 更新资料不带手机号码 /// /// /// /// [HttpPost("api/app/Person/UpdateNoMobileTelephone")] public async Task UpdateNoMobileTelephoneAsync(UpdatePersonDto input) { if (input == null) throw new UserFriendlyException("input参数不能为空"); var entity = ObjectMapper.Map(input); //更新人员信息 var person = await _repository.GetAsync(o => o.PersonId == input.PersonId); await _personManager.UpdateAsync(entity, person); await _repository.UpdateAsync(person, true); //更新用户信息 var user = await _identityUserRepository.GetAsync(person.PersonId); user.Name = input.PersonName; await _identityUserRepository.UpdateAsync(user, true); var personDto = await GetByIdAsync(new PersonIdInputDto() { PersonId = input.PersonId }); //personDto.MobileTelephone = user.PhoneNumber; //personDto.PersonName = user.Name; return personDto; } /// /// 创建亲属 /// /// /// /// [HttpPost("api/app/Person/CreatePersonKinship")] public async Task CreatePersonKinshipAsync(CreatePersonKinshipDto input) { if (input == null) throw new UserFriendlyException("input参数不能为空"); var entity = ObjectMapper.Map(input); if (string.IsNullOrWhiteSpace(input.KinshipId)) { throw new UserFriendlyException("亲属关系不能为空"); } if (string.IsNullOrWhiteSpace(input.SmsVerifyCodeKey)) { throw new UserFriendlyException("短信校验码键不能为空"); } if (_cache.Get(input.SmsVerifyCodeKey) != input.SmsVerifyCode) { throw new UserFriendlyException("无效的短信校验码或已过期"); } var person = await _repository.FindAsync(o => o.IdNo == input.IdNo); if (person != null) { var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId && o.PhoneNumber == input.MobileTelephone).FirstOrDefault(); if (user == null) { throw new UserFriendlyException("该身份证号已注册,但手机号码不一致"); } var personKinshipExist = new PersonKinship() { PersonId = person.PersonId, ParentPersonId = (Guid)CurrentUser.Id, KinshipId = input.KinshipId, }; await _personKinshipRepository.InsertAsync(personKinshipExist); return; } var userWithPerson = await _personManager.CreateAsync(entity, input.PersonName, input.Email, input.MobileTelephone); var personKinship = new PersonKinship() { PersonId = userWithPerson.Person.PersonId, ParentPersonId = (Guid)CurrentUser.Id, KinshipId = input.KinshipId, }; await _identityUserRepository.InsertAsync(userWithPerson.User); await _repository.InsertAsync(userWithPerson.Person); await _personKinshipRepository.InsertAsync(personKinship); //设置密码 (await _userManager.RemovePasswordAsync(userWithPerson.User)).CheckErrors(); (await _userManager.AddPasswordAsync(userWithPerson.User, Shentun.Utilities. Encrypt.RandomHelper.CreateRandom(Utilities.Enums.RandomType.NumAndChar, 10) + "0Cz*")).CheckErrors(); } /// /// 取消人员绑定 /// /// /// [HttpPost("api/app/Person/CancelPersonKinship")] public async Task CancelPersonKinshipAsync(PersonIdInputDto input) { var personKinship = await _personKinshipRepository.GetAsync(o => o.ParentPersonId == (Guid)CurrentUser.Id && o.PersonId == input.PersonId); await _personKinshipRepository.DeleteAsync(personKinship); } /// /// 获取体检次数列表 显示报告的列表 /// /// /// [HttpPost("api/app/Person/GetMedicalTimesListByPersonId")] public async Task> GetMedicalTimesListByPersonIdAsync(PersonIdInputDto input) { var entityList = (from user in await _identityUserRepository.GetQueryableAsync() join person in await _repository.GetQueryableAsync() on user.Id equals person.PersonId join patient in await _patientRepository.GetQueryableAsync() on new { idNo = person.IdNo, phone = user.PhoneNumber } equals new { idNo = patient.IdNo, phone = patient.MobileTelephone } join patientRegister in await _patientRegisterRepository.GetQueryableAsync() on patient.PatientId equals patientRegister.PatientId where user.Id == input.PersonId && (patientRegister.CompleteFlag == PatientRegisterCompleteFlag.SumCheck) && !string.IsNullOrWhiteSpace(patientRegister.ReportFile) orderby patientRegister.MedicalStartDate select new PersonMedicalTimesDto() { PatientRegisterId = patientRegister.PatientRegisterId, PersonName = patient.PatientName, MedicalStartDate = patientRegister.MedicalStartDate, }).ToList(); return entityList; } /// /// 获取pacs文件检查的项目列表 /// /// /// [HttpPost("api/app/Person/GetIsPacsCheckList")] public async Task> GetIsPacsCheckListAsync(PatientRegisterIdInputDto input) { var query = (from patientRegister in await _patientRegisterRepository.GetQueryableAsync() join registerCheck in await _registerCheckRepository.GetQueryableAsync() on patientRegister.PatientRegisterId equals registerCheck.PatientRegisterId join registerCheckAsbitem in await _registerCheckAsbitemRepository.GetQueryableAsync() on registerCheck.RegisterCheckId equals registerCheckAsbitem.RegisterCheckId join asbitem in await _asbitemRepository.GetQueryableAsync() on registerCheckAsbitem.AsbitemId equals asbitem.AsbitemId where patientRegister.PatientRegisterId == input.PatientRegisterId && registerCheck.IsPacsCheck == 'Y' select new { registerCheck.CheckRequestNo, asbitem.AsbitemName, registerCheck.PacsCheckDate }).ToList(); var entListDto = new List(); if (query.Count > 0) { entListDto = query.GroupBy(g => g.CheckRequestNo).Select(s => new GetIsPacsCheckListDto { CheckRequestNo = s.Key, AsbitemName = string.Join(",", s.Select(ss => ss.AsbitemName).Distinct().ToList()), PacsCheckDate = DataHelper.ConversionDateToString(s.FirstOrDefault().PacsCheckDate) }).ToList(); } return entListDto; } /// /// 获取本人和亲属列表 /// /// [HttpPost("api/app/Person/GetPersonKinshipList")] public async Task> GetPersonKinshipList() { var personKinshipIds = (await _personKinshipRepository.GetQueryableAsync()) .Where(o => o.ParentPersonId == CurrentUser.Id) .Select(o => o.PersonId).ToList(); personKinshipIds.Add((Guid)CurrentUser.Id); var personList = (from user in await _identityUserRepository.GetQueryableAsync() join person in await _repository.GetQueryableAsync() on user.Id equals person.PersonId join questionRegister in await _questionRegisterRepository.GetQueryableAsync() on person.PersonId equals questionRegister.PersonId into emptyQuestionRegister from haveQuestionRegister in emptyQuestionRegister.DefaultIfEmpty() where personKinshipIds.Contains(user.Id) orderby user.CreationTime select new PersonDto { PersonId = user.Id, PersonNo = person.PersonNo, MedicalCenterId = person.MedicalCenterId, PersonName = user.Name, SexId = person.SexId, SexName = _cacheService.GetSexNameAsync(person.SexId).Result, MaritalStatusId = person.MaritalStatusId, MaritalStatusName = _cacheService.GetMaritalStatusNameAsync(person.MaritalStatusId).Result, BirthDate = person.BirthDate, NationId = person.NationId, NationName = _cacheService.GetNationNameAsync(person.NationId).Result, BirthPlaceId = person.BirthPlaceId, IdNo = person.IdNo, PostalCode = person.PostalCode, Email = user.Email, MobileTelephone = user.PhoneNumber, Address = person.Address, IdTypeId = person.IdTypeId, CountryCode = person.CountryCode, IsAllowBind = person.IsAllowBind, IsHaveQuestionRegister = haveQuestionRegister == null ? 'N' : 'Y', Height = person.Height, Weight = person.Weight }).Distinct().ToList(); for (var i = 0; i < personList.Count; i++) { personList[i].DisplayOrder = i + 1; if (personList[i].PersonId == CurrentUser.Id) { personList[i].DisplayOrder = 0; //本人强行排第一个 } } personList = personList.OrderBy(o => o.DisplayOrder).ToList(); return personList; } /// /// 获取PDF体检报告 /// /// /// /// [HttpPost("api/app/Person/GetMedicalReportByPatientRegisterId")] public async Task GetMedicalReportByPatientRegisterIdAsync(PatientRegisterIdInputDto input) { var entity = await _patientRegisterRepository.GetAsync(o => o.PatientRegisterId == input.PatientRegisterId); if (string.IsNullOrWhiteSpace(entity.ReportFile)) { throw new UserFriendlyException("没有报告单"); } #region 检查是否需要填写问卷 var isQuestion =await _customerOrgRegisterRepository.FirstOrDefaultAsync(f => f.CustomerOrgRegisterId == entity.CustomerOrgRegisterId && f.IsQuestion == 'Y'); if (isQuestion != null) { string baseAddress = _configuration.GetSection("MedicalHealthReport").GetSection("BaseAddress").Value; string isQuestionApiUrl = _configuration.GetSection("MedicalHealthReport").GetSection("IsQuestionApiUrl").Value; isQuestionApiUrl = isQuestionApiUrl + $"?recordNo={entity.PatientRegisterNo}"; //查询是否填写问卷 var isQuestionResult = await CallAppServiceAsync(baseAddress, isQuestionApiUrl, null, "get"); if (isQuestionResult.code != 200 || isQuestionResult.data != true ) { throw new UserFriendlyException("请先填写问卷再来查看"); } } #endregion var Host = $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host.Host}:{_httpContextAccessor.HttpContext.Request.Host.Port}"; var returnValue = new MedicalReportDto() { FilePath = entity.ReportFile, FileBase64 = Shentun.Utilities.FileHelper.ToBase64(Host + entity.ReportFile) }; return returnValue; } /// /// 获取健康评估报告 /// /// /// /// [HttpPost("api/app/Person/GetMedicalHealthReportByPatientRegisterId")] public async Task GetMedicalHealthReportByPatientRegisterIdAsync(PatientRegisterIdInputDto input) { var entity = await _patientRegisterRepository.GetAsync(o => o.PatientRegisterId == input.PatientRegisterId); string baseAddress = _configuration.GetSection("MedicalHealthReport").GetSection("BaseAddress").Value; string reportListApiUrl = _configuration.GetSection("MedicalHealthReport").GetSection("ReportListApiUrl").Value; string reportApiUrl = _configuration.GetSection("MedicalHealthReport").GetSection("ReportApiUrl").Value; var medicalHealthReportListInputDto = new MedicalHealthReportListInputDto { Page = 1, Size = 10, RecordNo = entity.PatientRegisterNo }; var medicalHealthReportListResult = await CallAppServiceAsync(baseAddress, reportListApiUrl, medicalHealthReportListInputDto, "post"); if (medicalHealthReportListResult.Code != 200 || medicalHealthReportListResult.Data.FirstOrDefault() == null || medicalHealthReportListResult.Data.FirstOrDefault().ReportStatus != "1") { throw new UserFriendlyException("没有健康评估报告"); } //报告单ID var resultId = medicalHealthReportListResult.Data.FirstOrDefault().ResultId; reportApiUrl = reportApiUrl + $"?resultId={resultId}"; //获取报告apiurl var medicalHealthReportResult = await CallAppServiceAsync(baseAddress, reportApiUrl, null, "get"); if (medicalHealthReportResult.Code != 200 || string.IsNullOrWhiteSpace(medicalHealthReportResult.Data) ) { throw new UserFriendlyException("没有健康评估报告"); } string reportUrl = medicalHealthReportResult.Data; if (reportUrl.IndexOf(baseAddress) == -1) { //替换路径为代理地址 reportUrl = reportUrl.Replace("http://", "").Replace("https://", ""); reportUrl = baseAddress + reportUrl.Substring(reportUrl.IndexOf('/')); } var returnValue = new MedicalReportDto() { FilePath = reportUrl, FileBase64 = Shentun.Utilities.FileHelper.ToBase64(reportUrl) }; return returnValue; } /// /// 获取校验码 /// /// /// /// [AllowAnonymous] [HttpPost("api/app/Person/GetSmsVerifyCode")] public async Task GetSmsVerifyCodeAsync(SmsVerifyCodeInputDto input) { if (input == null) { throw new UserFriendlyException("input不能为空"); } //if (string.IsNullOrWhiteSpace(input.WechatOpenId)) //{ // throw new UserFriendlyException("WechatOpenId不能为空"); //} //if (_cache.Get(CacheKeys.OpenIdKey + input.WechatOpenId) != input.WechatOpenId) //{ // throw new UserFriendlyException("无效的WechatOpenId"); //} if (string.IsNullOrWhiteSpace(input.SessionKey)) { throw new UserFriendlyException("SessionKey不能为空"); } if (_cache.Get(input.SessionKey) != input.SessionKeyValue) { throw new UserFriendlyException("无效的SessionKeyValue"); } if (string.IsNullOrWhiteSpace(input.PersonName)) { throw new UserFriendlyException("姓名不能为空"); } if (string.IsNullOrWhiteSpace(input.MobileTelephone)) { throw new UserFriendlyException("手机号码不能为空"); } if (input.MobileTelephone.Length != 11) { throw new UserFriendlyException("手机号码必须为11位"); } if (string.IsNullOrWhiteSpace(input.IdNo)) { throw new UserFriendlyException("身份证号码不能为空"); } input.IdNo = input.IdNo.Trim(); if (input.IdNo.Length != 18) { throw new UserFriendlyException("身份证长度必须为18位"); } //var sexByIdNo = ConvertExtr.ToSexByIdNo(idNo).ToCharArray(); if (input.PersonId == null || input.PersonId == default(Guid)) { var person = await _repository.FindAsync(o => o.IdNo == input.IdNo); if (person != null) { var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId && o.PhoneNumber == input.MobileTelephone).FirstOrDefault(); if (user == null) { throw new UserFriendlyException("该身份证号已注册,但手机号码不一致"); } //if (!string.IsNullOrWhiteSpace(person.WechatOpenId)) //{ // throw new UserFriendlyException("该微信号已注册"); //} } } var createSmsTaskDto = new CreateSmsTaskDto() { PersonId = "0001", PersonName = input.PersonName, MobileTelephone = input.MobileTelephone, CountryCode = "86", }; var smsVerifyCodeKey = await SendVerifySms(createSmsTaskDto); var SmsVerifyCodeDto = new SmsVerifyCodeDto() { SmsVerifyCodeKey = smsVerifyCodeKey }; return SmsVerifyCodeDto; } private async Task GetTokenAsync(string request) { using var client = new HttpClient(); HttpContent httpContent = new StringContent(request); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); var url = _configuration.GetSection("AuthServer"). GetSection("Authority").Value + "/connect/token"; var tokenResult = await client.PostAsync(url , httpContent); var tokenResultStr = await tokenResult.Content.ReadAsStringAsync(); if (tokenResult.IsSuccessStatusCode) { if (!string.IsNullOrEmpty(tokenResultStr)) { if (tokenResultStr.ToLower().Contains("openid")) { var wechatUserDto = JsonSerializer.Deserialize(tokenResultStr, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }); var userTokenDto = new UserTokenDto { IsNewUser = "Y", OpenId = wechatUserDto.OpenId }; var options = new DistributedCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromDays(3)); _cache.Set(CacheKeys.OpenIdKey + wechatUserDto.OpenId, wechatUserDto.OpenId, options); return userTokenDto; } else { var signResult = JsonSerializer.Deserialize(tokenResultStr, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }); var userTokenDto = new UserTokenDto { IsNewUser = "N", AccessToken = signResult.access_token, RefreshToken = signResult.refresh_token }; return userTokenDto; } } else { throw new UserFriendlyException("token值为空"); } } else { //tokenResultStr = tokenResultStr.Replace("<", "").Replace(">", ""); //var grantErrorDto = JsonSerializer.Deserialize(tokenResultStr, // new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }); throw new UserFriendlyException("获取token失败:" + tokenResultStr); } } public async Task SendVerifySms(CreateSmsTaskDto createSmsTaskDto) { if (createSmsTaskDto == null) { throw new UserFriendlyException("createSmsTaskDto参数不能为空"); } var message = Shentun.Utilities.Encrypt.RandomHelper.CreateRandom(Utilities.Enums.RandomType.Num, 6); var verifySmsValidTimeStr = _configuration.GetSection("Sms") .GetSection("VerifySmsValidTime").Value; var isTemplateTimeStr = _configuration.GetSection("Sms") .GetSection("IsTemplateTime").Value; if (!int.TryParse(verifySmsValidTimeStr, out var verifySmsValidTime)) { throw new Exception("解析校验短信有效时间错误"); } if (isTemplateTimeStr == "N") { createSmsTaskDto.Content = message; } else { createSmsTaskDto.Content = message + "|" + verifySmsValidTime.ToString(); } //发送短信 createSmsTaskDto.TaskCycleType = '0'; await SmsClientHelper.CreateVerifySmsTask(createSmsTaskDto); //存储短信校验码 var options = new DistributedCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromMinutes(verifySmsValidTime)); var smsVerifyCodeKey = CacheKeys.SmsKey + createSmsTaskDto.MobileTelephone + Guid.NewGuid().ToString(); _cache.Set(smsVerifyCodeKey, message, options); return smsVerifyCodeKey; } private async static Task CallAppServiceAsync(string baseAddress, string url, TInput? data, string method = "post") { using (var httpClientHandler = new HttpClientHandler()) { using (var httpClient = new HttpClient(httpClientHandler)) { httpClient.BaseAddress = new Uri(baseAddress); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型 var jsonOptions = new JsonSerializerOptions { WriteIndented = true, // 设置为true以便于可读性更好的JSON输出 PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 如果你想要对日期进行格式化,可以使用JsonConverter Converters = { new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss") } }; var sendData = System.Text.Json.JsonSerializer.Serialize(data, jsonOptions); using (HttpContent httpContent = new StringContent(sendData)) { httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = null; if (method == "post") { response = await httpClient.PostAsync(url, httpContent); } else { response = await httpClient.GetAsync(url); } string result; if (!response.IsSuccessStatusCode) { result = response.Content.ReadAsStringAsync().Result; throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result); } result = await response.Content.ReadAsStringAsync(); var resultDto = System.Text.Json.JsonSerializer.Deserialize(result, jsonOptions); return resultDto; } } } } #region 注册信息列表 /// /// 查询注册信息 /// /// /// [HttpPost("api/app/Person/GetPersonList")] public async Task> GetPersonListAsync(GetPersonListInputDto input) { var query = from user in await _identityUserRepository.GetQueryableAsync() join person in await _repository.GetQueryableAsync() on user.Id equals person.PersonId select new { user, person }; if (!string.IsNullOrWhiteSpace(input.PatientName)) { query = query.Where(m => m.user.Name == input.PatientName); } if (input.SexId != null) { query = query.Where(m => m.person.SexId == input.SexId); } if (!string.IsNullOrWhiteSpace(input.IdNo)) { query = query.Where(m => m.person.IdNo == input.IdNo); } if (!string.IsNullOrWhiteSpace(input.MobileTelephone)) { query = query.Where(m => m.user.PhoneNumber == input.MobileTelephone); } var entListDto = query.Select(s => new PersonListDto { CreationTime = DataHelper.ConversionDateShortToString(s.person.CreationTime), IdNo = s.person.IdNo, MobileTelephone = s.user.PhoneNumber, PatientName = s.user.Name, SexName = _cacheService.GetSexNameAsync(s.person.SexId).GetAwaiter().GetResult() }).ToList(); return entListDto; } #endregion } }