using System; using System.IO; using System.Linq; using FMSAdmin.Data; using FMSAdmin.Entities; using FMSAdmin.Helpers; using FMSAdmin.Models; using FMSAdmin.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using OfficeOpenXml; namespace FMSAdmin.Controllers { [Authorize] [ApiController] [ApiVersion("1")] [Route("api/[controller]")] public class AccidentController : Controller { private readonly ILogger _logger; private readonly FMSContext _context; private AccidentService _service; private readonly StorageHelper _storage; public AccidentController( ILogger logger, FMSContext context, AccidentService service, StorageHelper storage ) { _logger = logger; _context = context; _service = service; _storage = storage; } /// /// 검색 & 정렬 /// /// /// private IQueryable _FilterAndSort(PagingRequest req) { var query = _service.GetAll(); query = query.Filter(req.conditions); if (req.siteId != null) { query = query.Where(x => x.SiteId == Util.ToInt(req.siteId)); } if (req.siteIds != null && req.siteIds.Length > 0) { query = query.Where(x => req.siteIds.Contains(x.SiteId)); } var sortQuery = query.OrderBy(x => x.CmSite.SortOrderNo); sortQuery = sortQuery.ThenByDescending(x => x.StartDate); sortQuery = sortQuery.ThenSort(req.sort); return sortQuery; } /// /// 셀렉트 공통 /// /// /// private dynamic _ListSelect(IQueryable query) { var list = query.Select(x => new { x.AccidentId, x.AccidentTypeId, x.SiteId, SiteName = x.CmSite.Name, AccidentTypeName = x.FmsAccidentCodeType.Name, x.Name, DepartmentName = x.CmDepartment.Name, StartDate = x.StartDate != null ? x.StartDate.Value.ToString("yyyy/MM/dd") : null, EndDate = x.EndDate != null ? x.EndDate.Value.ToString("yyyy/MM/dd") : null, ClosingDate = x.ClosingDate != null ? x.ClosingDate.Value.ToString("yyyy/MM/dd") : null }); return list; } /// /// 목록 /// /// /// /// [HttpGet] public IActionResult List([FromQuery] PagingRequest req) { var query = _FilterAndSort(req); var list = _ListSelect(query); var paging = PagingList.Pagination(list, req.page, req.limit); return Ok(paging); } // 엑셀 다운로드 [AllowAnonymous] [HttpGet("excel")] public IActionResult ExportExcel([FromQuery] PagingRequest req, string filename) { var query = _FilterAndSort(req); var list = _ListSelect(query); _logger.LogError("#############"); var stream = new MemoryStream(); using (var package = new ExcelPackage(stream)) { var workSheet = package.Workbook.Worksheets.Add("Sheet1"); workSheet.Cells.LoadFromCollection(list, true); if (req.columns != null && req.columns.Length > 0) { workSheet.AddStyle(req.columns, req.sort?.order?.ToLower() == "asc", filename); } package.Save(); } stream.Position = 0; string excelName = $"excel-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx"; return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName); } /// /// 조회 /// [HttpGet("{siteId}/{id}")] public IActionResult Get(int siteId, int id) { var data = _service.Get(id, siteId); if (data.Count() == 0) { return NotFound("사이트 정보를 찾을 수 없습니다."); } var list = data.Select(x => new { x.AccidentId, x.AccidentTypeId, x.SiteId, CmSite = new { x.CmSite.Name, }, x.Name, x.AccidentLocation, FmsAccidentCodeType = new { x.FmsAccidentCodeType.Name }, x.StartDate, x.EndDate, x.ClosingDate, CmCompany = new { x.CmCompany.Name }, CmDepartment = new { x.CmDepartment.Name }, x.CompanyId, x.DepartmentId, x.Reason, x.Action, x.Action2, x.Damage, x.Measurement, CmFile1 = _storage.ParseFile(x.CmFile1), CmFile2 = _storage.ParseFile(x.CmFile2), CmFile3 = _storage.ParseFile(x.CmFile3), CmFile4 = _storage.ParseFile(x.CmFile4), x.Firstwitness, x.VictimAge, x.VictimName, x.VictimRelation, x.IsInsurance, x.InsuranceContent }); return Ok(list.First()); } /// /// 수정 /// [HttpPost("{siteId}/{id}")] public IActionResult Edit(int siteId, int id, [FromBody] FmsAccident data) { _logger.LogInformation("Edit"); _logger.LogInformation("id:" + id); _logger.LogInformation("siteId:" + siteId); if (id != data.AccidentId) { return BadRequest("잘못된 접근입니다."); } if (ModelState.IsValid) { _service.Edit(id, siteId, data); } else { return BadRequest(ModelState); } return Ok(); } /// /// 등록 /// [HttpPut] public IActionResult Create([FromBody] FmsAccident data) { _logger.LogInformation("Create"); if (ModelState.IsValid) { _service.Create(data); } else { return BadRequest(ModelState); } return Ok(); } /// /// 삭제 /// [HttpDelete("{siteId}/{id}")] public IActionResult Delete(int siteId, int id) { _service.Delete(id, siteId); return Ok(); } /// /// 보고서 /// [AllowAnonymous] [HttpGet("Report/{siteId}/{id}")] public IActionResult Report(int siteId, int id) { var data = _service.Get(id, siteId); if (data.Count() == 0) { return NotFound("사이트 정보를 찾을 수 없습니다."); } var list = data.Select(x => new { x.AccidentId, x.AccidentTypeId, x.SiteId, SiteName = x.CmSite.Name, x.Name, x.AccidentLocation, AccidentCodeTypeName = x.FmsAccidentCodeType.Name, x.StartDate, x.EndDate, ClosingDate = x.ClosingDate != null ? x.ClosingDate.Value.ToString("yyyy/MM/dd") : "", CompanyName = x.CmCompany.Name, DepartmentName = x.CmDepartment.Name, x.CompanyId, x.DepartmentId, x.Reason, x.Action, x.Action2, x.Damage, x.Measurement, CmFileUrl1 = x.CmFile1 != null && x.CmFile1.ContentType.IndexOf("image/") != -1 ? _storage.ParseFileUrl(x.CmFile1) : "", CmFileUrl2 = x.CmFile2 != null && x.CmFile2.ContentType.IndexOf("image/") != -1 ? _storage.ParseFileUrl(x.CmFile2) : "", CmFileUrl3 = x.CmFile3 != null && x.CmFile3.ContentType.IndexOf("image/") != -1 ? _storage.ParseFileUrl(x.CmFile3) : "", CmFileUrl4 = x.CmFile4 != null && x.CmFile4.ContentType.IndexOf("image/") != -1 ? _storage.ParseFileUrl(x.CmFile4) : "", x.Firstwitness, x.VictimAge, x.VictimName, x.VictimRelation, IsInsurance = x.IsInsurance == true ? "네" : "아니오", x.InsuranceContent }); return Ok(list.ToList()); } } }