using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web; using Ewide.Core; using Ewide.Core.Service; using Furion; using Furion.ClayObject.Extensions; using Furion.DatabaseAccessor; using Furion.DatabaseAccessor.Extensions; using Furion.DataEncryption; using Furion.DataEncryption.Extensions; using Furion.DynamicApiController; using Furion.FriendlyException; using Furion.RemoteRequest.Extensions; using Google.Protobuf.Reflection; using Mapster; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using NPOI.HPSF; using Vote.Services.Dto; using Vote.Services.Entities; namespace Vote.Services.ApiController { /// /// 外墙调查问卷 /// [ApiDescriptionSettings("outsidewall", Order = 0)] [Route("/gb/yjb/api/outsidewall")] public class OutsideWallService : IDynamicApiController { private readonly SqlSugarRepository repoutside_wall; private readonly SqlSugarRepository repoutside_wall_building; private readonly SqlSugarRepository repoutside_wall_building_photo; private readonly SqlSugarRepository repoutside_wall_photo; private readonly SqlSugarRepository rep_SysFile; private readonly IMemoryCache _memoryCache; readonly IOptions _options; /// /// /// /// /// /// /// /// public OutsideWallService(SqlSugarRepository _repoutside_wall, SqlSugarRepository _repoutside_wall_building, SqlSugarRepository _repoutside_wall_building_photo, SqlSugarRepository _repoutside_wall_photo, IMemoryCache memoryCache, SqlSugarRepository _rep_SysFile, IOptions options) { repoutside_wall = _repoutside_wall; repoutside_wall_building = _repoutside_wall_building; repoutside_wall_building_photo = _repoutside_wall_building_photo; repoutside_wall_photo = _repoutside_wall_photo; _memoryCache = memoryCache; _options = options; rep_SysFile = _rep_SysFile; } /// /// 获取三居系统中的社区 /// /// [AllowAnonymous] [HttpGet("query/{id}")] public async Task Query(string id) { var entity = await repoutside_wall.AsQueryable().FirstAsync(a => a.communityId == id); if (entity != null) { var outside_wall_photos = await repoutside_wall_photo.AsQueryable().Where(a => a.outsidewallId == entity.Id).ToListAsync(); entity.outside_wall_photos = outside_wall_photos; var outside_wall_buildings = await repoutside_wall_building.AsQueryable().Where(a => a.outsidewallId == entity.Id).ToListAsync(); entity.outside_wall_buildings = outside_wall_buildings; return entity; } return null; } /// /// 获取三居系统中的社区 /// /// [AllowAnonymous] [HttpGet("communitys")] public async Task> GetCommunitys(string searchkey) { var cacheKey = "cache_GetCommunitys"; List Communitys = null; Communitys = _memoryCache.Get>(cacheKey); if (Communitys == null || Communitys.Count == 0) { //var aaaaaaaaaaaaaa = repoutside_wall.AsQueryable().ToList(); var SanjuKey = App.GetConfig("OutsideWallSetting:SanjuKey"); var timeStamp = GetTimeStamp(); var sign = (SanjuKey + timeStamp).ToMD5Encrypt(); var GetCommunitysUrl = App.GetConfig("OutsideWallSetting:GetCommunitys"); var GetHouseInfoCitysByCommunityUrl = App.GetConfig("OutsideWallSetting:GetHouseInfoCitysByCommunity"); Communitys = await string.Format(GetCommunitysUrl, "") .SetHeaders(new Dictionary { { "sign", sign }, { "timeStamp", timeStamp } }) .GetAsAsync>(); _memoryCache.Set(cacheKey, Communitys, DateTime.Now.AddHours(1)); } if (!string.IsNullOrEmpty(searchkey)) return Communitys.Where(a => a.Name.Contains(searchkey)).ToList(); return Communitys; } /// /// 获取三居系统中的社区 /// /// [AllowAnonymous] [HttpGet("community/{id}")] public async Task GetCommunityInfo(string id) { var cacheKey = "cache_building_" + id; List building = _memoryCache.Get>(cacheKey); if (building == null) { var SanjuKey = App.GetConfig("OutsideWallSetting:SanjuKey"); var timeStamp = GetTimeStamp(); var sign = (SanjuKey + timeStamp).ToMD5Encrypt(); var GetHouseInfoCitysByCommunityUrl = App.GetConfig("OutsideWallSetting:GetHouseInfoCitysByCommunity"); building = await string.Format(GetHouseInfoCitysByCommunityUrl, id) .SetHeaders(new Dictionary { { "sign", sign }, { "timeStamp", timeStamp } }) .GetAsAsync>(); _memoryCache.Set(cacheKey, building, DateTime.Now.AddHours(1)); } return building; } /// /// 获取时间戳 /// /// private string GetTimeStamp() { TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalMilliseconds).ToString(); } /// /// 上传文件 /// /// /// [AllowAnonymous] [HttpPost("sysFileInfo/upload")] public async Task UploadFileDefault(IFormFile file) { return await UploadFile(file, _options.Value.Default); } /// /// 删除文件 /// /// /// [AllowAnonymous] [HttpGet("sysFileInfo/delete/{id}")] public async Task DeleteFile(string id) { var entity = await rep_SysFile.AsQueryable().FirstAsync(a => a.Id == id); _ = entity == null ? throw Oops.Oh("参数异常") : ""; var pathType = _options.Value.Default.path; var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, pathType); File.Delete(Path.Combine(filePath, entity.FileObjectName)); await rep_SysFile.DeleteAsync(id); } /// /// 预览文件 /// /// /// [AllowAnonymous] [HttpGet("sysFileInfo/preview/{id}")] public async Task PreviewFileInfo(string id) { var file = await rep_SysFile.AsQueryable().FirstAsync(a => a.Id == id); _ = file == null ? throw Oops.Oh("参数异常") : ""; var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, file.FileBucket, file.FileObjectName); var fileName = HttpUtility.UrlEncode(file.FileOriginName?.Replace(" ", null).Replace("\"", null), Encoding.UTF8); return new FileStreamResult(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Ewide.Core.Util.MimeMapping.GetMimeMapping(filePath)) { FileDownloadName = fileName }; //return await DownloadFileInfo(input); } /// /// 上传文件 /// /// /// /// private static async Task UploadFile(IFormFile file, FileDescription fileOption) { var pathType = fileOption.path; var mimeType = Ewide.Core.Util.MimeMapping.GetMimeMapping(file.FileName); if (!fileOption.contentType.Contains(mimeType)) { throw Oops.Oh("上传文件mimeType错误!"); } var fileId = Guid.NewGuid().ToString(); var fileSizeKb = (long)(file.Length / 1024.0); // 文件大小KB if (fileSizeKb > fileOption.maxSize) { throw Oops.Oh("文件大小超过最大限制!"); } var originalFilename = file.FileName; // 文件原始名称 var fileSuffix = Path.GetExtension(file.FileName).ToLower(); // 文件后缀 var finalName = fileId + fileSuffix; // 生成文件的最终名称 var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, pathType); if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath); using (var stream = File.Create(Path.Combine(filePath, finalName))) { await file.CopyToAsync(stream); } var sysFileInfo = new SysFile { Id = fileId, FileLocation = (int)FileLocation.LOCAL, FileBucket = pathType, FileObjectName = finalName, FileOriginName = originalFilename, FileSuffix = fileSuffix.TrimStart('.'), FileSizeKb = fileSizeKb }; //await rep_SysFile.InsertAsync(sysFileInfo); await sysFileInfo.InsertAsync(); return fileId; } /// /// 提交 /// /// [Consumes("application/json", "multipart/form-data")] [HttpPost("submit")] [AllowAnonymous] public async Task Submit([FromForm] OutsideWallInput args) { try { repoutside_wall.Ado.BeginTran(); var wall = args.Adapt(); wall.Id = Guid.NewGuid().ToString(); wall.createtime = DateTime.Now; wall.isdeleted = 0; wall = await repoutside_wall.InsertReturnEntityAsync(wall); if (args.fileList != null) { foreach (var item in args.fileList) { await repoutside_wall_photo.InsertReturnEntityAsync(new outside_wall_photo { outsidewallId = wall.Id, sysfileid = item }); } } foreach (var item in args.buildings) { var build = item.Adapt(); build.Id = Guid.NewGuid().ToString(); build.outsidewallId = wall.Id; build.BuildingId = build.Id; build.createtime = DateTime.Now; build = await repoutside_wall_building.InsertReturnEntityAsync(build); if (item.problemfiles != null) { foreach (var item1 in item.problemfiles) { await repoutside_wall_building_photo.InsertReturnEntityAsync(new outside_wall_building_photo { outsidewallBuildingId = build.Id, sysfileid = item1.file, toward = item1.Toward }); } } } repoutside_wall.Ado.CommitTran(); return "提交成功"; } catch (Exception ex) { repoutside_wall.Ado.RollbackTran(); throw Oops.Oh(ex.Message + ex.StackTrace); } //var lastSend = await repSmsCode.DetachedEntities.Where(p => p.phone == args.phone && !p.IsDeleted).OrderByDescending(a => a.CreatedTime).FirstOrDefaultAsync(); //_ = (lastSend == null || lastSend.code != args.code || lastSend.expire_time < DateTime.Now) ? throw Oops.Oh("验证码错误或已失效") : 1; //var totalCount = await repPerson.DetachedEntities.Where(a => !a.IsDeleted && a.date == args.date).CountAsync(); //_ = totalCount >= App.GetConfig("NingboZhiChun:TotalCount") ? throw Oops.Oh("提交失败,名额已满。") : 1; //_ = (await repPerson.DetachedEntities.Where(a => !a.IsDeleted && (a.phone == args.phone || a.cardno == args.cardno)).CountAsync() > 0) ? throw Oops.Oh("您已提交,无需再次提交") : 1; //var now = DateTime.Now; //var model = new Entities.nbzc_person //{ // address = args.address, // phone = args.phone, // cardno = args.cardno, // CreatedTime = DateTime.Now, // date = args.date, // hangye = args.hangye, // IsDeleted = false, // line = args.line, // name = args.name, // weixin_number = args.weixin_number //}; //model = await model.InsertOrUpdate(); //lastSend.IsDeleted = true; //await repSmsCode.UpdateIncludeAsync(lastSend, new string[] { nameof(lastSend.IsDeleted) }); //var token = JWTEncryption.Encrypt(new Dictionary() // 加密 //{ // { "UserId", model.Id }, // { "Account",model.phone } //}); //return new { success = true, token }; return 1; } } }