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; namespace Shentun.WebPeis.Persons { /// /// 微信人员 /// [ApiExplorerSettings(GroupName = "Work")] [Authorize] public class PersonAppService : ApplicationService { 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; 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) { _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; } public async Task GetByIdAsync(PersonIdInputDto input) { var entity = await _repository.GetAsync(o => o.PersonId == input.PersonId); var entityDto = ObjectMapper.Map(entity); 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); return token; } [AllowAnonymous] [HttpPost("api/app/Person/Create")] [UnitOfWork(IsDisabled = false)] public async Task CreateAsync(CreatePersonDto 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"); } 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); await unitOfWork.SaveChangesAsync(); await unitOfWork.CompleteAsync(); } 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.SaveChangesAsync(); 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/CreatePersonKinship")] public async Task CreatePersonKinshipAsync(CreatePersonKinshipDto input) { var entity = ObjectMapper.Map(input); if (string.IsNullOrWhiteSpace(input.KinshipId)) { 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/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.Audit) orderby patientRegister.MedicalStartDate select new PersonMedicalTimesDto() { PatientRegisterId = patientRegister.PatientRegisterId, PersonName = patient.PatientName, MedicalStartDate = patientRegister.MedicalStartDate, }).ToList(); return entityList; } /// /// 获取本人和亲属列表 /// /// [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 where personKinshipIds.Contains(user.Id) orderby user.CreationTime select new PersonDto { PersonId = user.Id, PersonName = user.Name, SexId = person.SexId, SexName = _cacheService.GetSexNameAsync(person.SexId).Result, MaritalStatusId = person.MaritalStatusId, MaritalStatusName = _cacheService.GetMaritalStatusNameAsync(person.MaritalStatusId).Result, IdNo = person.IdNo, MobileTelephone = user.PhoneNumber }).ToList(); for(var i = 0; io.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("没有报告单"); } 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; } 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.FromMinutes(720)); _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); } } private async Task SendSms(string phone, string msg) { if (phone.Length == 11) { phone = "+86" + phone; } else { throw new Exception("手机号必须是11位长"); } //发送短信 //存储短信校验码 _cache.Set(phone, msg); } } }