using System;
using System.Linq;
using System.Threading.Tasks;

using FMSAdmin.Data;
using FMSAdmin.Models;
using FMSAdmin.Entities;
using FMSApp.Services;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using FMSAdmin.Helpers;
using System.Data;
using System.IO;
using OfficeOpenXml;

namespace FMSApp.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/app/[controller]")]
    public class ComplaintsController : Controller {
        private readonly ILogger<ComplaintsController> _logger;
        private readonly FMSContext _context;
        private readonly ComplaintsService _service;
        private readonly StorageHelper _storage;

        public ComplaintsController(
            ILogger<ComplaintsController> logger,
            FMSContext context,
            ComplaintsService service,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _service = service;
            _storage = storage;
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string siteId) {
            var query = _FilterAndSort(req);
            if (!string.IsNullOrEmpty(siteId)) {
                query = query.Where(x => x.SiteId == Util.ToInt(siteId));
            }
            var list = query.Select(x => new {
                x.SiteId,
                x.ComplaintId,
                ComplaintTypeName = x.FmsComplaintCodeType.Name,
                x.Name,
                Dates = new {
                    StartDate = x.StartDate == null ? null : ((DateTime)x.StartDate).ToString("yyyy.MM.dd"),
                    EndDate = x.EndDate == null ? null : ((DateTime)x.EndDate).ToString("yyyy.MM.dd"),
                },
                x.ComplaintTypeId,
                x.DepartmentId,
                DepartmentName = x.CmDepartment.Name,
                x.ComplaintLocation
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] string siteId, [FromQuery] string complaintId) {
            var query = _service.GetAll().Where(x => x.ComplaintId == Util.ToInt(complaintId)).Where(x => x.SiteId == Util.ToInt(siteId));
            var item = query.Select(x => new {
                x.SiteId, //사이트ID
                x.ComplaintId, //ComplaintId
                x.ComplaintTypeId, //사고유형ID
                ComplaintTypeName = x.FmsComplaintCodeType.Name,
                x.Name, //사고명
                x.ComplaintLocation, //사고위치
                x.StartDate,//사고발생일
                x.EndDate,//조치완료일
                x.CompanyId, //회사
                CompanyName = x.CmCompany.Name,
                x.DepartmentId, //부서
                DepartmentName = x.CmDepartment.Name,
                x.Reason, //사고원인
                x.Action, //조치내용
                x.Damage, //피해내용
                x.Measurement, //향후대책
                CmFile1 = _storage.ParseFile(x.CmFile1), //첨부파일
                CmFile2 = _storage.ParseFile(x.CmFile2), //첨부파일
                CmFile3 = _storage.ParseFile(x.CmFile3) //첨부파일
            }).FirstOrDefault();

            return Ok(item);
        }

        // 검색 & 정렬 공통
        private IQueryable<FmsComplaints> _FilterAndSort(PagingRequest req) {
            var query = _service.GetAll();

            // 기본 Entity 검색
            query = query.Filter(req.conditions);

            // 기본 Entity 정렬
            query = query.Sort(req.sort);

            return query;
        }

        /// <summary>
        /// 저장
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public IActionResult Save([FromBody] FmsComplaints data) {
            _logger.LogInformation("Save");
            //_logger.LogInformation(data.Dump());

            if (ModelState.IsValid) {
                _service.Save(data);
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

        [HttpDelete("{siteId}/{complaintId}")]
        public IActionResult Delete(int siteId, int complaintId) {
            _service.Delete(siteId, complaintId);
            return Ok();
        }

    }
}