using Magicodes.ExporterAndImporter.Core; using Magicodes.ExporterAndImporter.Core.Extension; using Magicodes.ExporterAndImporter.Excel; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; using TaskManager.Entity; using TaskManager.EntityFramework; using TaskManager.EntityFramework.Repository; using Wood.Entity; using Wood.Util; using Wood.Util.Filters; namespace Wood.Service.Controllers { [AllowAnonymous] public class NormalBaseController:ControllerBase,ITransient where T:BaseEntity ,new() { protected readonly JobDbContext _context; protected readonly IServiceProvider _builder; protected readonly IConfiguration _configuration; protected readonly IRepository _repository; public NormalBaseController(JobDbContext context, IServiceProvider builder, IConfiguration configuration, IRepository repository) { _builder = builder; _context = context; _configuration = configuration; _repository = repository; } /// /// 通过UID获得实体 /// /// /// [HttpGet("{id}")] public async virtual Task> GetById(int id) { var entity = await _repository.GetByIdAsync(id); if (entity == null) return NotFound(); return entity; } /// /// 创建实体 /// /// /// [HttpPost] public async virtual Task> Create(T entity) { entity.CreationTime = DateTime.Now; var createdEntity = await _repository.AddAsync(entity); return new JsonResult(new { Code = 200, Message = "创建成功!" }); } /// /// 更新实体UID /// /// /// [HttpPut] [Route("Update/{UId}")] public async virtual Task Update(T entity) { if (entity.UId == 0) { throw new Exception("更新时,实体主键UId不能为空或0"); } var target = await _repository.GetByIdAsync(entity.UId); if (target == null) { throw new Exception($"NormalBaseController.Update报错:根据UId{entity.UId}没有找到记录"); return new JsonResult(new { Code = 400, Message = "修改失败!" }); } EntityMapper.Trans(entity, target, "UId"); await _repository.UpdateAsync(target); return new JsonResult(new { Code = 200, Message = "修改成功!" }); } /// /// 删除实体通过UID /// /// /// [HttpDelete("{id}")] public async virtual Task Delete(int id) { await _repository.DeleteAsync(id); return new JsonResult(new { Code = 200, Message = "删除成功!" }); ; } ///// ///// 分页 ///// ///// ///// ///// ///// ///// ///// //[HttpGet] //public async virtual Task GetPaged( //[FromQuery] int pageNumber = 1, //[FromQuery] int pageSize = 10, //[FromQuery] string sortBy = "", //[FromQuery] bool isAscending = true, //[FromQuery] Dictionary filters = null) //{ // var pagingParams = new PagingParams // { // PageNumber = pageNumber, // PageSize = pageSize, // SortBy = sortBy, // IsAscending = isAscending, // Filters = filters // }; // // 可以在这里构建表达式树过滤条件 // Expression> filter = null; // var pagedResult = await _repository.GetPagedAsync(filter, pagingParams); // return Ok(pagedResult); //} /// /// 分页New /// /// /// [HttpPost] public async virtual Task>> GetDataPaged(RequestInputBase input) { var pagingParams = new PagingParams { PageNumber = input.pageNumber, PageSize = input.pageSize, SortBy = input.sortBy, IsAscending = input.isAscending, }; // 可以在这里构建表达式树过滤条件 Expression> filter = null; var pagedResult = await _repository.GetDataPagedAsync(filter, pagingParams, input.Condition); return Ok(pagedResult); } /// /// 导出New /// /// /// [HttpPost] public async virtual Task ExportData(RequestInputBase input) { var pagingParams = new PagingParams { PageNumber = input.pageNumber, PageSize = input.pageSize, SortBy = input.sortBy, IsAscending = input.isAscending, }; // 可以在这里构建表达式树过滤条件 //Expression> filter = null; var pagedResult = await _repository.GetDataPagedAsync(null, pagingParams, input.Condition); return await ExportFile(pagedResult.Data, Guid.NewGuid().ToString() + ".xlsx"); } // /// // /// 导出 // /// // /// // /// // /// // /// // /// // /// // [HttpGet] // public async virtual Task Export([FromQuery] int pageNumber = 1, //[FromQuery] int pageSize = 10, //[FromQuery] string sortBy = "", //[FromQuery] bool isAscending = true, //[FromQuery] Dictionary filters = null) // { // var pagingParams = new PagingParams // { // PageNumber = pageNumber, // PageSize = pageSize, // SortBy = sortBy, // IsAscending = isAscending, // Filters = filters // }; // // 可以在这里构建表达式树过滤条件 // //Expression> filter = null; // var pagedResult = await _repository.GetPagedAsync(null, pagingParams); // return await ExportFile(pagedResult.Data, Guid.NewGuid().ToString() + ".xlsx"); // } protected async Task ExportFile(ICollection dtos, string fileName) { var excelExporter = HttpContext.RequestServices.GetRequiredService(); var res = await excelExporter.ExportAsByteArray(dtos); return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "_" + fileName }; } /// /// 导入模板 /// /// [HttpGet] public async virtual Task GetImportTemplate() { try { // 创建导入模板生成器 var importer = new ExcelImporter(); // 生成导入模板流(这里假设使用 YourModel 作为导入模型) var bytes = await importer.GenerateTemplateBytes(); //using var stream = new MemoryStream(bytes); //stream.Seek(0, SeekOrigin.Begin); // 设置友好的文件名,例如:"导入模板_20250530.xlsx" var fileName = $"导入模板_{DateTime.Now:yyyyMMdd}.xlsx"; // 返回文件流结果 return new FileStreamResult(new MemoryStream(bytes), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "_" + fileName }; //return File( // fileStream: stream, // contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // fileDownloadName: fileName); } catch (Exception ex) { // 记录异常日志 Console.WriteLine($"生成导入模板时出错: {ex.Message}"); // 返回错误响应 return StatusCode(500, "生成导入模板时发生错误"); } } /// /// 导入 /// /// /// [HttpPost("Import")] public async virtual Task Import(IFormFile file) { if (file == null || file.Length <= 0) { return NotFound("No file uploaded."); } try { var excelImporter = HttpContext.RequestServices.GetRequiredService(); var importResult = await excelImporter.Import(file.OpenReadStream()); if (importResult.HasError) { StringBuilder sb = new StringBuilder(); foreach (var rowErr in importResult.RowErrors) { string temp = string.Join(";", rowErr.FieldErrors.Select(itm => $"第{rowErr.RowIndex}行:{itm.Key}-{itm.Value}")); sb.AppendLine(temp); } foreach (var templateErr in importResult.TemplateErrors) { string temp = $"列名:{templateErr.RequireColumnName},错误信息:{templateErr.Message}"; sb.AppendLine(temp); } throw new Exception(sb.ToString()); } // 处理导入的数据 List list = importResult.Data.ToList(); await ImportBefore(list); // 校验数据长度 var validationErrors = ValidationHelper.ValidateDataLength(list, _context); if (validationErrors.Any()) { throw new Exception("数据校验失败:" + string.Join(", ", validationErrors)); } foreach (var item in list) { item.ReadState = true; item.CreationTime = CommonHelper.CurrentTime; } await _context.BulkInsertAsync(list); await ImportAfter(list); return new JsonResult(new { Code = 200, Message = "修改成功!" }); } catch (Exception ex) { //await _logger.AddError(ex.Message, TaskName); return new JsonResult(new { Code = 400, Message = "导入失败:" + ex.Message }); } } protected virtual async Task ImportBefore(List p_list) { } protected virtual async Task ImportAfter(List p_list) { } /// /// 高级查询字段 /// /// [HttpGet("fields")] public IActionResult GetQueryFields() { // 获取实体类的所有属性 Type entityType = typeof(T); var properties = entityType.GetProperties(); // 构建字段信息列表 var fields = new List(); foreach (var property in properties) { // 获取ExporterHeader特性中的DisplayName var exporterHeader = property.GetCustomAttribute(); string displayName = exporterHeader?.DisplayName ?? property.Name; // 获取属性类型 string dataType = property.PropertyType.Name; // 添加到字段列表 fields.Add(new QueryFieldInfo { FieldName = property.Name, DisplayName = displayName, DataType = dataType }); } return Ok(fields); } } }